我正在关注我最近收到的一本新书,但出现此错误,我不知道我做错了什么
ValueError: Shapes (None, 10, 2, 2) 和 (None, 10) 不兼容
这是代码
from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
network.compile(optimizer = 'rmsprop',
loss = 'categorical_crossentropy',
metrics=['accuracy'])
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
from tensorflow.keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network.fit(train_images, train_labels, epochs=1, batch_size = 128)
答案 0 :(得分:0)
您发布的代码看起来不错,我只是运行它!有用。 我认为您在以正确的方式导入数据集时遇到了问题。 我使用 MNIST 数据集来测试您的代码,并在导入行前添加了注释。 尝试复制它并告诉我问题是否仍然存在。
from keras import models
from keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
from keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
(train_X, train_y), (test_X, test_y) = mnist.load_data() # Load mnist
# I wrote train_X... but changed it later
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
network.compile(optimizer = 'rmsprop',
loss = 'categorical_crossentropy',
metrics=['accuracy'])
train_images = train_X.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_X.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
train_labels = to_categorical(train_y)
test_labels = to_categorical(test_y)
network.fit(train_images, train_labels, epochs=1, batch_size = 128)
答案 1 :(得分:0)
train_labels
的方式。您可能正在将函数 to_categorical()
应用于已经导致维度错误的分类数据。train_labels
的尺寸并确保其尺寸类似于 (60000, 10)
。 60000 可能会有所不同,但元组中的第二个值应该是 10。