我在使用Keras神经网络的新功能API时,使用了一热编码。我遇到了下面的错误:
Failed to find data adapter that can handle input: (<class 'list'> containing values of types {'(<class 'list'> containing values of types {\'(<class \\\'list\\\'> containing values of types {\\\'(<class \\\\\\\'list\\\\\\\'> containing values of types {"<class \\\\\\\'int\\\\\\\'>"})\\\'})\'})'}), (<class 'dict'> containing {"<class 'str'>"} keys and {'(<class 'list'> containing values of types {\'(<class \\\'list\\\'> containing values of types {"<class \\\'int\\\'>"})\'})'} values)
如果我没记错的话,我认为网络不接受一热编码作为合适的输出。有没有人知道解决这个错误的方法?
代码片段:
import numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersboard_inputs = keras.Input(shape=(8, 8, 12))conv1= layers.Conv2D(10, 3, activation='relu')conv2 = layers.Conv2D(10, 3, activation='relu')pooling1 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)pooling2 = layers.MaxPooling2D(pool_size=(2, 2), strides=None, padding="valid", data_format=None,)flatten = keras.layers.Flatten(data_format=None)x = conv1(board_inputs)x = pooling1(x)x = conv2(x)x = flatten(x)piece_output = layers.Dense(12,name = 'piece')(x)alpha_output = layers.Dense(7,name = 'alpha')(x)number_output = layers.Dense(7,name = 'number')(x)model = keras.Model(inputs=board_inputs, outputs=[piece_output,alpha_output,number_output], name="chess_ai_v3")model.compile( loss=keras.losses.mse, optimizer=keras.optimizers.Adam(), metrics=None,)keras.utils.plot_model(model, "multi_input_and_output_model.png", show_shapes=True)history = model.fit( trans_data[:len(trans_data)], {"piece": pieces, "alpha": alphas,"number": numbers}, epochs=2, batch_size=32,)# history = model.fit(trans_data[:len(trans_data)],pieces[:len(trans_data)],batch_size=64, epochs=1000)# print(type(numbers[0]))
回答:
我使用下面的代码能够重现你的错误。错误与Keras的多输入/输出无关。当我们将输入作为list of array
、array of list
或dict
类型传递给model.fit()
时,会出现此错误。我使用的是tensorflow version 2.2.0
。
重现错误的代码 –
输出 –
---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-85-2b4ecdfa5a74> in <module>() 17 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) 18 ---> 19 model.fit(data_a,labels, epochs=10, steps_per_epoch=4)3 frames/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/data_adapter.py in select_data_adapter(x, y) 961 "Failed to find data adapter that can handle " 962 "input: {}, {}".format(--> 963 _type_name(x), _type_name(y))) 964 elif len(adapter_cls) > 1: 965 raise RuntimeError(ValueError: Failed to find data adapter that can handle input: <class 'numpy.ndarray'>, (<class 'list'> containing values of types {"<class 'int'>"})
如果你将数据作为list of arrays
传递,如下所示 –
data_a = [np.array(300), np.array(455), np.array(350), np.array(560), np.array(700), np.array(800), np.array(200), np.array(250)]
那么你会得到如下的错误 –
ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'numpy.ndarray'>"}), (<class 'list'> containing values of types {"<class 'int'>"}).
如果你将数据作为dict
类型传递 –
data_a = {'a':300, 'b':455, 'c':350, 'd':560, 'e':700, 'f':800, 'g':200, 'h':250}
那么你会得到如下的错误 –
ValueError: Failed to find data adapter that can handle input: (<class 'dict'> containing {"<class 'str'>"} keys and {"<class 'int'>"} values), (<class 'list'> containing values of types {"<class 'int'>"})
解决方案 – 当我将数据转换为相同类型时,错误得到了修复 – array of array
或 list of list
。
修改,
data_a = [300, 455, 350, 560, 700, 800, 200, 250]labels = [455, 350, 560, 700, 800, 200, 250, 300]
为
data_a = np.array([300, 455, 350, 560, 700, 800, 200, 250])labels = np.array([455, 350, 560, 700, 800, 200, 250, 300])
修复后的代码 –
输出 –
Ran Successfully
另外,回答你另一个问题,
如果我没记错的话,我认为网络不接受一热编码作为合适的输出。有没有人知道解决这个错误的方法?
下面是一个简单的例子,我在其中做了Ytrain = np_utils.to_categorical(Ytrain)
完整代码 –
输出 –
2.2.0(150, 3)Model: "model_13"_________________________________________________________________Layer (type) Output Shape Param # =================================================================input_21 (InputLayer) [(None, 10, 1)] 0 _________________________________________________________________conv1d_9 (Conv1D) (None, 10, 32) 352 _________________________________________________________________batch_normalization_15 (Batc (None, 10, 32) 128 _________________________________________________________________activation_9 (Activation) (None, 10, 32) 0 _________________________________________________________________global_average_pooling1d_9 ( (None, 32) 0 _________________________________________________________________dense_14 (Dense) (None, 3) 99 =================================================================Total params: 579Trainable params: 515Non-trainable params: 64_________________________________________________________________Ran Successfully
希望这能回答你的问题。祝你学习愉快。