我应该运行一个来自MNIST数据的0,1,2,3,4,5标签的模型,并检查准确性。
这是我得到的:
> import tensorflow as tf
from tensorflow import keras
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train.shape
y_train.shape
y_train[0:10]
x_train_new, y_train_new = x_train[(y_train==0) | (y_train==1) | (y_train==2) | (y_train==3) | (y_train==4) | (y_train==5)], y_train[(y_train==0) | (y_train==1) | (y_train==2) | (y_train==3) | (y_train==4) | (y_train==5)]
x_train_new.shape
y_train_new.shape
y_train_new[0:10]
y_train_onehot = tf.one_hot(y_train_new, depth=6)
y_test_onehot = tf.one_hot(y_test, depth=6)
x_train_final = x_train_new.reshape((-1, 784))
x_train_final.shape
x_test_new, y_test_new = x_test[(y_test==0) | (y_test==1) | (y_test==2) | (y_test==3) | (y_test==4) | (y_test==5)], y_test[(y_test==0) | (y_test==1) | (y_test==2) | (y_test==3) | (y_test==4) | (y_test==5)]
x_test_new.shape
x_test_final = x_test_new.reshape((-1, 784))
x_train_final = x_train_final / 255
x_test_final = x_test_final / 255
model = keras.Sequential([keras.layers.Dense(1,activation='softmax')])
model.compile(optimizer="sgd",loss="categorical_crossentropy",metrics=["accuracy"])
model.fit(x=x_train_final,y=y_train_new,epochs=5)
但是,运行后的准确性非常低(0.1872)。当我尝试将Dense从1更改为6时,得到“ValueError:形状(None,1)和(None,6)不兼容”。那么问题是什么?有人能帮助我修复我的代码吗?:(TIA
1条答案
按热度按时间zzwlnbp81#
在训练模型时,您不会将one_hot编码标签传递到model.fit。此外,现在您有6个标签(0、1、2、3、4、5),您需要根据提供的数据集,在模型的最后一层提及这些标签的类别计数。
请检查以下固定代码:
输出量:
请参阅类似的link以了解更多详细信息。