【发布时间】:2021-10-05 18:58:18
【问题描述】:
致所有偶然发现此问题的人:
我最近在做图像分类(将 CNN 拟合到一些标记数据上),我想使用 keras 的模块进行数据增强。但是,我得到了一个 NotImplementedError。更具体地说,它逐字逐句地说:
NotImplementedError:无法将符号张量 (sequential_3/sequential/random_rotation/rotation_matrix/strided_slice:0) 转换为 numpy 数组。此错误可能表明您正在尝试将张量传递给 NumPy 调用,这是不受支持的
这是我为增强层编写的代码:
angle = 15
data_augmentation = keras.Sequential([
layers.experimental.preprocessing.RandomFlip('horizontal'),
layers.experimental.preprocessing.RandomRotation(angle/360)
])
所以我想要将所有图像水平翻转并随机旋转 15 度。我直接将它插入我的 CNN:
layers_2 = [
#image augmentation layer
data_augmentation,
#convolution layer
keras.layers.Conv2D(16, 3, padding = 'same', activation = 'relu'),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(32, 3, padding = 'same', activation = 'relu'),
keras.layers.MaxPooling2D(),
keras.layers.Conv2D(64, 3, padding = 'same', activation = 'relu'),
keras.layers.MaxPooling2D(),
keras.layers.Flatten(),
#dropout for regularization
keras.layers.Dropout(0.2),
#MLP layer
keras.layers.Dense(128, activation = 'relu'),
keras.layers.Dense(64, activation = 'relu'),
keras.layers.Dense(3, activation = 'softmax')
]
model_2 = keras.Sequential(layers_2)
model_2.compile(optimizer = tf.optimizers.Adam(),
loss = tf.keras.losses.SparseCategoricalCrossentropy(),
metrics = [tf.metrics.SparseCategoricalAccuracy()]
)
epochs_2 = 15
#fitting
history_2 = model_2.fit(
normalized_train_ds,
validation_data = normalized_val_ds,
epochs = epochs_2
)
其中 normalized_train_ds 和 normalized_val_ds 都是标准化的 tensorflow.data.Dataset 对象。
必要的上下文:我在我的本地机器上运行它,在 Python 3.9.7 配置的环境中。我的 NumPy 版本是 1.21.2,我的 TensorFlow 版本是 2.5.0。早在 2021 年 2 月,我就遇到过类似的问题,但他们注意到运行 Python 3.9.1 和 TensorFlow 2.4.1 以及 NumPy 1.20+ 的人也存在同样的问题(该问题的链接:https://github.com/tensorflow/tensorflow/issues/47360)。
实际问题:是我写了一些糟糕的代码,还是我的 Python、TensorFlow、NumPy 版本不兼容?我尝试安装以前版本的 numpy(1.20+),但它给我带来了同样的问题。如果我在 google Colab 笔记本上运行它,这将不再是问题。
【问题讨论】:
-
面临同样的问题。 TensorFlow 2.6.0 似乎兼容 1.19.5 或更低版本
-
我检查过了,这在
TF2.7和tf-nightly中得到了解决。
标签: python-3.x numpy tensorflow2.0