Skip to main content
 首页 » 编程设计

python之在图像上训练 Keras 模型时,出现错误 "Invalid argument: Attr shrink_axis_mask has value 4294967295 out of range for an int32"

2024年11月24日36jiqing9006

我正在尝试训练一个模型来识别图像类别。图片的宽度为 50x50 像素。当我尝试运行代码时,出现错误

2019-04-15 08:55:48.737185: W tensorflow/core/framework/op_kernel.cc:1378] OP_REQUIRES failed at 
strided_slice_op.cc:88 : Invalid argument: Attr shrink_axis_mask has value 4294967295 out of rang 
e for an int32 
Traceback (most recent call last): 
  File "Final.py", line 108, in <module> 
    model.fit(as_np_arr, all_image_labels, epochs=5, shuffle=False) 
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 
880, in fit 
    validation_steps=validation_steps) 
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_arrays.py" 
, line 310, in model_iteration 
    ins_batch = slice_arrays(ins[:-1], batch_ids) + [ins[-1]] 
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/utils/generic_utils.py", l 
ine 526, in slice_arrays 
    return [None if x is None else x[start] for x in arrays] 
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/keras/utils/generic_utils.py", l 
ine 526, in <listcomp> 
    return [None if x is None else x[start] for x in arrays] 
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py", line 654, in 
_slice_helper 
    name=name) 
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py", line 820, in 
strided_slice 
    shrink_axis_mask=shrink_axis_mask) 
  File "/usr/local/lib/python3.7/site-packages/tensorflow/python/ops/gen_array_ops.py", line 9334 
, in strided_slice 
    _six.raise_from(_core._status_to_exception(e.code, message), None) 
  File "<string>", line 3, in raise_from 
tensorflow.python.framework.errors_impl.InvalidArgumentError: Attr shrink_axis_mask has value 4294967295 out of range for an int32 [Op:StridedSlice] name: strided_slice/ 

这是正在使用的代码。 tf_raw 是表示为 numpy 数组的图像列表,all_image_labels 是每个图像的类的 python 列表。

print("Creating model") 
model = keras.Sequential({ 
    # keras.layers.Flatten(input_shape=(3670, 50, 50, 3)), 
    keras.layers.Dense(2500, activation = tf.nn.relu), 
    keras.layers.Dense(20, activation = tf.nn.softmax) 
}) 
print("Compiled") 
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics = ['accuracy']) 
print("Turning into array") 
as_np_arr = tf.convert_to_tensor(tf_raws) 
print("Converted images") 
all_image_labels = tf.convert_to_tensor(all_image_labels) 
print(str(len(as_np_arr)) + " -> " + str(len(all_image_labels))) 
print("TRAINING THE MODEL") 
model.fit(as_np_arr, all_image_labels, epochs=5, shuffle=False) 
print("Model is trained!") 

请您参考如下方法:

我有同样的问题,我尝试将 numpy 数组提供给 fit() 函数而不是张量。基本上将代码的倒数第二行替换为:

model.fit(as_np_arr.numpy(), all_image_labels.numpy(), epochs=5, shuffle=False) 

我希望这对您有用,因为这是一种快速解决方法..但我期待有经验的人提供适当的解释。