MNIST Tensorflow-ValueError:输入数组应具有与目标数组相同的样本数

问题描述 投票:0回答:2

我在Tensorflow中实现MNIST数据集时遇到麻烦。

ValueError:输入数组应具有与目标数组相同数量的样本。找到60000个输入样本和10000个目标样本。

我理解错误,但这是验证数据而不是培训数据。如果有人可以建议我会很高兴。

# --->>> MNIST Handwriting Classifier - Tensorflow | Py3
from __future__ import absolute_import, division, print_function, unicode_literals

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

# Download and load dataset.
mnist = keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

print ("MNIST Dataset loaded")

# Each image is mapped to a single label.
class_names = ['0', '1', '2', '3', '4',
               '5', '6', '7', '8', '9']

# Explore the training dataset
print ("Training Dataset Shape:", (x_train.shape))
print ("Nunber of labels:", (len(y_train)))
print (y_train)

#Explore validation dataset.
print ("Validation Dataset Shape:", (x_test.shape))
print ("Nunber of labels:", (len(y_test)))
print (y_test)

# Pre-process the data.
plt.figure()
plt.imshow(x_train[0])
plt.colorbar()
plt.grid(False)
plt.show()

# Remap / Normalize pixel value from 0-255 ->  0-1
x_train = x_train / 255.0
x_test = x_train / 255.0

#Verify and inspect training dataset.
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(x_train[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[y_train[i]])
plt.show()

# Define the layers of the neural network. Layers extract representations of the data feed into them.
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])

# Compile the model and define loss function, optimizer and metrics.
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

# Train the model using the model.fit method.
model.fit(x_train, y_train, epochs=10)

# Evaluate accuracy of model using test / validation dataset.
test_loss, test_acc = model.evaluate(x_test,  y_test, verbose=2)
python tensorflow deep-learning artificial-intelligence mnist
2个回答
0
投票

你做了什么

# Remap / Normalize pixel value from 0-255 ->  0-1
x_train = x_train / 255.0
x_test = x_train / 255.0

您必须执行以下操作来替换上面的行

x_train=x_train/255.0
x_test=x_test/255.0
© www.soinside.com 2019 - 2024. All rights reserved.