我正在尝试将旧的tflearn模型转换为keras模型,因为我已从TF 1.15迁移到TF 2.0,在此不再支持tflearn。我的keras模型是:
model = tf.keras.Sequential([
tf.keras.layers.Dense(8, input_shape=(None, len(train_x[0]))),
tf.keras.layers.Dense(8),
tf.keras.layers.Dense(len(train_y[0]), activation="softmax"),
])
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(train_x, train_y, epochs=epochs, batch_size=batch_size)
test_loss, test_acc = model.evaluate(train_x, train_y)
print("Tested Acc:", test_acc)
运行它时,出现以下错误:
ValueError:检查输入时出错:预期density_input具有3维,但数组的形状为(49,51)
我不知道如何解决此错误。我需要以某种方式重新定义模型吗?我究竟做错了什么?
作为参考,我的旧tflearn模型是:
tf.reset_default_graph()
net = tflearn.input_data(shape=[None, len(train_x[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')
net = tflearn.regression(net)
model = tflearn.DNN(net, tensorboard_dir='tflearn_logs')
model.fit(train_x, train_y, n_epoch=epochs, batch_size=batch_size, show_metric=True)
正如我们在注释中发现的那样,您的代码存在两个问题。
首先,不得在input_shape
参数cf中指定批次尺寸。Keras的文档Dense
。
其次,因为train_y.shape = (?, 6)
,您需要使用categorical_crossentropy
和sparse_categorical_crossentropy
。Keras文档中有一条注释,详细描述了差异。
这是更正的代码:
model = tf.keras.Sequential([
tf.keras.layers.Dense(8, input_shape=(len(train_x[0]))),
tf.keras.layers.Dense(8),
tf.keras.layers.Dense(len(train_y[0]), activation="softmax"),
])
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
model.fit(train_x, train_y, epochs=epochs, batch_size=batch_size)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句