ValueError: Shapes (1, 1) and (1, 5) are incompatible

import tensorflow as tf
import numpy as np
import warnings
warnings.filterwarnings(“ignore”)

x_train=np.random.random((10,8))
y_train=np.random.randint(10,size=(10,1))

x_test=np.random.random((5,8))
y_test=np.random.randint(10,size=(5,1))

model=tf.keras.Sequential()

model.add(tf.keras.layers.Dense(10,input_shape=(8,)))
model.add(tf.keras.layers.Dense(5,activation=”relu”))
model.add(tf.keras.layers.Dense(3,activation=”relu”))
model.add(tf.keras.layers.Dense(5,activation=”softmax”))

model.compile(optimizer=tf.keras.optimizers.Adam(0.001),loss=tf.keras.losses.categorical_crossentropy,metrics=tf.keras.metrics.categorical_accuracy)

model.fit(x_train,y_train,epochs=10,batch_size=1,validation_data=(x_test,y_test))

model.save(“model.h5”)

报错:
Traceback (most recent call last):
File “D:/python/flask/app.py”, line 26, in
model.fit(x_train,y_train,epochs=10,batch_size=1,validation_data=(x_test,y_test))
File “C:\Users\dky\AppData\Roaming\Python\Python37\site-packages\keras\utils\traceback_utils.py”, line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File “C:\Users\dky\AppData\Roaming\Python\Python37\site-packages\keras\backend.py”, line 4994, in categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)

ValueError: Shapes (1, 1) and (1, 5) are incompatible

产生此错误的原因是测试数据为(1,1)形数据。

[En]

The reason for this error is that the test data is a (1, 1) shaped data.

[[8]
[3]
[1]
[9]
[4]],
但模型设置输出是一个(1,5)形状的数据。
将model.add(tf.keras.layers.Dense(5,activation=”softmax”))修改为model.add(tf.keras.layers.Dense(1,activation=”softmax”))即可。

Original: https://blog.csdn.net/qq_32271493/article/details/122125007
Author: liyoo Yin
Title: ValueError: Shapes (1, 1) and (1, 5) are incompatible

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/496851/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球