我在实现MNIST数据集时出错了,
ValueError:输入数组应该与目标数组具有相同数量的样本。发现60000个输入样本和10000个目标样本。
和我尝试重塑和规范化training_images和test_images的建议相同的错误,但没有成功
import tensorflow as tf
from os import path, getcwd, chdir
path = f"{getcwd()}/../tmp2/mnist.npz"
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
def train_mnist():
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('acc')>0.998):
print("/n Reached 99.8% accuracy so cancelling training!")
self.model.stop_training = True
mnist = tf.keras.datasets.mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data(path=path)
callbacks=myCallback()
training_images=training_images.reshape(60000, 28, 28, 1)
test_images=test_images.reshape(10000, 28, 28, 1)
training_images = training_images / 255.0
test_images = test_images / 255.0
model = tf.keras.models.Sequential([
# YOUR CODE STARTS HERE
tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
# YOUR CODE ENDS HERE
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(training_images,test_images,epochs=19,callbacks=[callbacks])
return history.epoch, history.history['acc'][-1]
_, _ = train_mnist
误差
WARNING: Logging before flag parsing goes to stderr.
W0127 18:52:34.933709 140418551342912 deprecation.py:506] From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-1ff3c304aec3> in <module>
----> 1 _, _ = train_mnist_conv()
<ipython-input-3-57c5d09d3058> in train_mnist_conv()
42 history = model.fit(
43 # YOUR CODE STARTS HERE
---> 44 training_images,test_images,epochs=19,callbacks=[callbacks]
45
46 # YOUR CODE ENDS HERE
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
707 steps=steps_per_epoch,
708 validation_split=validation_split,
--> 709 shuffle=shuffle)
710
711 # Prepare validation data.
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
2686 # Check that all arrays have the same length.
2687 if not self._distribution_strategy:
-> 2688 training_utils.check_array_lengths(x, y, sample_weights)
2689 if self._is_graph_network and not self.run_eagerly:
2690 # Additional checks to avoid users mistakenly using improper loss fns.
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training_utils.py in check_array_lengths(inputs, targets, weights)
481 'the same number of samples as target arrays. '
482 'Found ' + str(list(set_x)[0]) + ' input samples '
--> 483 'and ' + str(list(set_y)[0]) + ' target samples.')
484 if len(set_w) > 1:
485 raise ValueError('All sample_weight arrays should have '
ValueError: Input arrays should have the same number of samples as target arrays. Found 60000 input samples and 10000 target samples.
当你拟合你的模型时,你需要传递训练图像为了学习它们,你还需要通过训练标签。
Label是你要预测的数字。所以应该是这样的:
history = model.fit(training_images,training_labels,epochs=19,callbacks=[callbacks])