【问题标题】:What is this error and why it is showing ? Deep Learning MNIST这是什么错误,为什么会显示?深度学习 MNIST
【发布时间】:2020-04-03 21:49:49
【问题描述】:

我正在从《用 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

这是什么意思?你能详细解释一下,因为我是深度学习的初学者。其次,我也在形状/尺寸和轴之间感到困惑。您能否解释一下以及如何解决上述错误?

【问题讨论】:

  • 只是一个建议,试试 input_shape(28, 28, 1)。并且还尝试在 reshape 语句中使用 , 而不是 * 。不确定,但我就是这样做的。但是我的代码和你的不一样。
  • 它不工作它给出一个错误检查输入时出错:预期dense_3_input有4维,但得到的数组形状为(10000, 784)
  • 嗨朋友们,有什么帮助吗?
  • 嗨!我也在学习这个东西。是你想要的,对一些图像进行分类吗?然后可以使用示例数据集的代码。这会有帮助吗?
  • 是的@StackerRook,请分享代码

标签: python matplotlib deep-learning


【解决方案1】:
#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)

希望对你有帮助!

【讨论】:

  • 嗨@stackRook 感谢分享代码。我以某种方式设法使用以下代码显示该图,但不明白哪里错了,为什么? first_image = test_images[44] first_image = np.array(first_image, dtype='float') pixel = first_image.reshape((28, 28)) plt.imshow(pixels, cmap='gray') plt.show() 可以您还可以分享您的详细信息,以便我在学习深度学习时与您联系,两者都有相同的目标,我们可以互相帮助
  • @Parag 好的,让我们在 LinkedIn 上连接
  • 谢谢,我在Linkedin上找不到你,我的个人资料是linkedin.com/in/parag-patankar-920362a
猜你喜欢
  • 2020-02-01
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 2018-11-05
  • 2019-06-07
  • 1970-01-01
  • 2017-02-12
  • 2023-04-10
相关资源
最近更新 更多