我尝试了以下代码,但是遇到了以上错误。我看到了类似的问题,但没有得到适当的解决方案。请帮帮我!
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
mnist=tf.keras.datasets.mnist #download the dataset
(xtrain, ytrain),(xtest, ytest)=mnist.load_data() #split the dataset in test and train
xtrain=tf.keras.utils.normalize(xtrain, axis=1)
xtest=tf.keras.utils.normalize(xtest, axis=1)
model=tf.keras.models.Sequential() # start building the model
model.add(tf.keras.layers.Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Conv2D(32, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Flatten()) # converting matrix to vector
model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) # adding a layer with 10 nodes(as only 10 outputs are possible) and softmax activaation function
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # specifiying hyperparameters
model.fit(xtrain,ytrain,epochs=5,) # load the model
model.save('Ashwatdhama') # save the model with a unique name
myModel=tf.keras.models.load_model('Ashwatdhama') # make an object of the model
prediction=myModel.predict((xtest)) # run the model object
for i in range(10):
print(np.argmax(prediction[i]))
plt.imshow(xtest[i]) # make visuals of mnist dataset
plt.show() #output
答案 0 :(得分:1)
您的网络需要黑白图像(1通道),因此您必须相应地修改数据。只需在拟合前为图像添加尺寸即可
xtrain = xtrain[...,None] # (batch_dim, 28, 28, 1)
xtest = xtest[...,None] # (batch_dim, 28, 28, 1)