报错解决:valueError: When using data tensors as input to a model, you should specify the steps_per_epoch argument.
Keras小白开始入手深度学习的时候,使用Sequence()建模的很舒服,突然有一天要使用到Model()的时候,就开始各种报错。
from keras.models import Sequential
from keras.layers import Dense, Activation
...
model = Sequential([
Dense(32, input_shape=(784,)),
Dense(10),
Activation('softmax'),
])
history = model.fit(data_x_train, data_y_train, epoch=epoch,
batch_size=batch_size,
validation_data=(data_x_val, data_y_val),
callbacks=callbacks, verbose=1, shuffle=True)
等到了使用Model()来建模的时候,需要指定input:
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Input
...
input1 = Input(batch_shape=(None, 28, 28), dtype=tf.float32)
des1 = Dense(32)(input1)
des2 = Dense(10)(des1)
y = Activation('softmax')(des2)
model = Model(inputs=input1, outputs=y)
history = model.fit(data_x_train, data_y_train, epoch=epoch,
batch_size=batch_size,
validation_data=(data_x_val, data_y_val),
callbacks=callbacks, verbose=1, shuffle=True)
到开始fit的时候就开始报错
ValueError: When using data tensors as input to a model, you should specify the steps_per_epoch argument.
真的是找遍各种百度都解决不了的问题,我看Keras的教程中也有使用Model()建模然后使用batch_size训练的,百思不得其解。最后用Sequence蒙混过关,直到过了半年又得改成Model,我才发现:
怪不得说是tensor as input,我这里用了tf.float32,那可不就是变成tensor data了嘛,解决方法:
import numpy as np
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Input
...
input1 = Input(batch_shape=(None, 28, 28), dtype=np.float32)
des1 = Dense(32)(input1)
des2 = Dense(10)(des1)
y = Activation('softmax')(des2)
把tf改成np就可以解决问题
需要注意的是,只要在代码中出现了数据的reshape用到了tf,那么数据就变成了tensor data格式,例如
#data_x_train.shape = (256, 28)
tf.reshape(data_x_train, (256, 28, 1), name=tf.float32)
tf.reshape(data_x_train, (256, 28, 1), name=np.float32)
上述的两种写法都会使得数据从array或dataFrame或list变成tensor,所以为了避免使用steps_per_epoch(好多时候有问题都不知道怎么改,反正我是不喜欢用这个),可以用numpy的reshape方法来修改数据的维度:
# type(data_x_train) = DataFrame
data_x_train = np.array(data_x_train).reshape(256, 28, 1)
之前有看到博主说删掉验证集可以解决这个问题,但我那时候也没成功,可能就是因为reshape的时候用了tf.float32
裂开
——2021.2.25 随笔