【问题标题】:MNIST dataset input arrays should have the same number of samples as target arraysMNIST 数据集输入数组应具有与目标数组相同数量的样本
【发布时间】:2021-01-27 19:12:59
【问题描述】:

我在实现 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.

【问题讨论】:

    标签: python python-3.x tensorflow keras


    【解决方案1】:

    在拟合模型时,您需要传递训练图像,为了学习它们,您还需要传递训练标签。

    标签是您要预测的数字。 所以应该是这样的:

    history = model.fit(training_images,training_labels,epochs=19,callbacks=[callbacks])
    

    【讨论】:

    • @Frightera,谢谢。不好意思,没注意
    猜你喜欢
    • 2020-06-13
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2020-08-31
    • 2023-03-10
    • 2019-05-30
    相关资源
    最近更新 更多