python - 这是什么错误,为什么会显示?深度学习 MNIST
问题描述
我正在从《用 Python 进行深度学习》一书中学习深度学习。我有以下代码,
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
train_labels
test_images.shape
len(test_labels)
test_labels
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 keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc',test_acc)
到目前为止,一切都运行良好。当我运行以下代码时出现错误
digit = train_images[4]
import matplotlib.pyplot as plt
plt.imshow(digit, cmap=plt.cm.binary)
plt.show()
它给出以下错误
C:\ProgramData\Anaconda\lib\site-packages\matplotlib\image.py in set_data(self, A)
688 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
689 raise TypeError("Invalid shape {} for image data"
--> 690 .format(self._A.shape))
691
692 if self._A.ndim == 3:
TypeError: Invalid shape (784,) for image data
这是什么意思?你能详细解释一下,因为我是深度学习的初学者。其次,我也在形状/尺寸和轴之间感到困惑。您能否解释一下以及如何解决上述错误?
解决方案
#mnist contain images of hand-written numbers from 0 to 9
#we are going to recognize them using this code
import tensorflow as tf
print(tf.__version__)
#myCallback is to stop the training once a desirable accuracy (99%) is reached.
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epochs, logs={}):
if (logs.get('accuracy') > 0.99):
print("\nReached 99% accuracy so stopping training....")
self.model.stop_training = True
#use the built-in dataset mnist from tensorflow
mnist = tf.keras.datasets.mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images.reshape(60000, 28, 28, 1)
training_images=training_images / 255.0
test_images = test_images.reshape(10000, 28, 28, 1)
test_images=test_images/255.0
callbacks = myCallback()
#the convolutional neural network model,
model = tf.keras.models.Sequential([
#use a single convolutional layer here with a 3x3 filter.
# 1 stands for 1 byte for colour (since greyscale images)
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
#10 neurons since 10 classes for numbers 0 to 9
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=10, callbacks = [callbacks])
#testing for unknown data
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_acc)
希望能帮助到你!
推荐阅读
- exception - 捕获 Doctrine 异常后持久化实体
- r - 有没有办法在 rmarkdown 的另一个目录中通知 bookdown YAML 中的配置文件?
- google-cloud-platform - 是否可以跟踪 Google Compute Engine API 调用以查看其来源?
- python - 按组重复值的运行计数
- html - 样式子元素没有 id 仅使用父 id
- haskell - 运行 runSMT 时获得一个随机可满足的解决方案(或多个解决方案)
- regex - 在 Canvas 测验中使用单个正则表达式不重复的交替组
- c# - 如何在 wpf 中获取 windowsApps 文件夹 (C:\Program Files\WindowsApps) 权限?
- vb.net - 如何对 dgv 列的一部分进行排序
- arrays - i+1 与 i++ 相对