簡體   English   中英

這是什么錯誤,為什么會顯示? 深度學習 MNIST

[英]What is this error and why it is showing ? Deep Learning 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)

希望能幫助到你!

train_images 被重寫,添加以下代碼結束

print('test_acc:', test_acc)
import numpy as np
print(train_images.shape)
digit = train_images[1]
digit = np.reshape(digit, (28, 28))
print(digit.shape)
print(digit.shape)
# print(digit)
print(digit.shape)
import matplotlib.pyplot as plt
plt.imshow(digit, cmap=plt.cm.binary)
plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM