TensorFlow v1到v2版本兼容指南

Lkeme SVIP+

前言

记录TensorFlow 中v2版本使用v1代码的各种问题

问题一

Question:

1
2
from keras.utils import multi_gpu_model
ImportError: cannot import name 'multi_gpu_model' from 'keras.utils'...

Answer:

1
2
3
4
5
from keras.utils import multi_gpu_model

to:

from keras.utils.multi_gpu_utils import multi_gpu_model

问题二

Question:

1
ValueError: Subshape must have computed start >= end since stride is negative, but is 0 and 2 (computed from start 0 and end 9223372036854775807 over shape with rank 2 and stride-1)

Answer:

1
2
3
4
5
6
7
box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[::-1], K.dtype(feats))
box_wh = K.exp(feats[..., 2:4]) * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats))

to:

box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[..., ::-1], K.dtype(feats))
box_wh = K.exp(feats[..., 2:4]) * anchors_tensor / K.cast(input_shape[..., ::-1], K.dtype(feats))

问题三

Question:

1
TypeError: Tensors are unhashable. (KerasTensor(type_spec=TensorSpec(shape=(None, None, None, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'"))Instead, use tensor.ref() as the key.

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from keras import backend as K

....
self.sess = K.get_session()

to:

from keras import backend as K
import tensorflow as tf
tf.compat.v1.disable_eager_execution()

.....
self.sess = K.get_session()

问题四

Question:

1
ImportError: cannot import name 'BatchNormalization' from 'keras.layers.norm...

Answer:

1
2
3
4
5
from keras.layers.normalization import BatchNormalization

to:

from keras.layers.normalization.batch_normalization import BatchNormalization

END.

  • 标题: TensorFlow v1到v2版本兼容指南
  • 作者: Lkeme
  • 创建于 : 2021-09-15 09:08:27
  • 更新于 : 2024-05-15 18:51:35
  • 链接: https://mudew.com/2021/09/15/TensorFlow v1到v2版本兼容指南/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
此页目录
TensorFlow v1到v2版本兼容指南