Keras框架使用过程遇到ValueError
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected.
检查模型输入时出错:传递给模型的Numpy数组列表不是模型预期的大小
遇到的问题
Traceback (most recent call last):
File "train.py", line 88, in <module>
train()
File "train.py", line 77, in __call__
self.fit()
File "train.py", line 71, in fit
self._fit()
File "train.py", line 58, in _fit
validation_steps=c_d_v.get_lst_size(self.val_fileid_lst, 'Vaild') // self.BATCH_SIZE)
File "E:\Anaconda3\envs\hw1\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "E:\Anaconda3\envs\hw1\lib\site-packages\keras\engine\training.py", line 1415, in fit_generator
initial_epoch=initial_epoch)
File "E:\Anaconda3\envs\hw1\lib\site-packages\keras\engine\training_generator.py", line 213, in fit_generator
class_weight=class_weight)
File "E:\Anaconda3\envs\hw1\lib\site-packages\keras\engine\training.py", line 1209, in train_on_batch
class_weight=class_weight)
File "E:\Anaconda3\envs\hw1\lib\site-packages\keras\engine\training.py", line 749, in _standardize_user_data
exception_prefix='input')
File "E:\Anaconda3\envs\hw1\lib\site-packages\keras\engine\training_utils.py", line 101, in standardize_input_data
str(len(data)) + ' arrays: ' + str(data)[:200] + '...')
ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 ar
t of 1 arrays: [array([[[ 0. , 0. , 1. , 1.15957451],
[-0.24468085, 0.26595744, 0.30851063, 0.09574468],
[-0.05319149, -0.0212766 , 0.06382979, 0.36170211],
问题原因
keras在多输入多输出模型时,训练时传入的数据不满足模型定义
解决办法:
修改model.fit
或者model.fit_generator
中参数,使模型定义的输入输出列表和自适应处的调用一致
模型定义的输出输出列表
model = Model(inputs=[a1, a2], outputs=[b1, b3, b3])
自适应处的调用
model.fit([a1, a2], [b1, b3, b3],
validation_data=([a1, a2], [b1, b3, b3]),
epochs=1, batch_size=64)
def gen():
yield [a1, a2], [b1, b3, b3]
model.fit_generator(gen(),
validation_data=gen(),
epochs=1, batch_size=64)
踩过的坑
- 除了训练数据,还要注意验证数据
model.fit([a1, a2], [b1, b3, b3], # 训练数据
validation_data=([a1, a2], [b1, b3, b3]), # 验证数据
epochs=1, batch_size=64)
model.fit_generator
注意生成器中yield所有返回格式都要一致
if count >= batch_size:
X, Y = data2npy(dList, max_len)
yield [X,Y],Y # 第一处返回
count = 0
dList = []
if dList:
X, Y = data2npy(dList, max_len)
yield [X,Y],Y # 第二处返回相同的格式