Colab 中的 Tensorflow 错误 - ValueError: Shapes (None, 1) 和 (None, 10) 不兼容 [英] Tensorflow error in Colab - ValueError: Shapes (None, 1) and (None, 10) are incompatible

查看:59
本文介绍了Colab 中的 Tensorflow 错误 - ValueError: Shapes (None, 1) 和 (None, 10) 不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 MNIST 数据集为 NN 执行一小段代码以进行字符识别.当涉及到拟合线时,我得到 ValueError: Shapes (None, 1) and (None, 10) is incompatible

I'm trying to execute a small code for NN using the MNIST dataset for characters recognition. When it comes to the fit line I get ValueError: Shapes (None, 1) and (None, 10) are incompatible

import numpy as np

#Install Tensor Flow
try:
  #Tensorflow_version solo existe en Colab
  %tensorflow_version 2.x

except Exception:
  pass

import tensorflow as tf

tf.__version__

mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)
print(np.unique(y_train))
print(np.unique(y_test))

import matplotlib.pyplot as plt
plt.imshow(x_train[0], cmap='Greys');

y_train[0]

x_train, x_test = x_train / 255.0, x_test / 255.0
x_train.shape

model = tf.keras.Sequential([
                           tf.keras.layers.Flatten(input_shape=(28, 28)),
                           tf.keras.layers.Dense(units=512, activation='relu'),
                           tf.keras.layers.Dense(units=10, activation='softmax')
])
model.summary()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
h = model.fit(x_train, y_train, epochs=10, batch_size=256)

我在最后一行收到一个错误,比如 x_train 和 y_train 的大小是否不同.但是 X_train 是 60000x28x28 而 y_train 是 60000x1

I get an error in the last line, like if x_train and y_train would be of different size. But X_train is 60000x28x28 and y_train is 60000x1


Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
flatten (Flatten)            (None, 784)               0         
_________________________________________________________________
dense (Dense)                (None, 512)               401920    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                5130      
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________
Epoch 1/10
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-50705bca2031> in <module>()
      6 model.summary()
      7 model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
----> 8 h = model.fit(x_train, y_train, epochs=10, batch_size=256)

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

ValueError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:533 train_step  **
        y, y_pred, sample_weight, regularization_losses=self.losses)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:205 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:143 __call__
        losses = self.call(y_true, y_pred)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:246 call
        return self.fn(y_true, y_pred, **self._fn_kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:1527 categorical_crossentropy
        return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py:4561 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_shape.py:1117 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (None, 1) and (None, 10) are incompatible

推荐答案

在将 y_train 向量传递给 fit 方法之前,您需要对其进行一次热编码.您可以使用以下代码执行此操作:

You need to one hot encode your y_train vectors before passing them to the fit method. You can do that using the following code:

from keras.utils import to_categorical

# make the model and load the training dataset.

y_train = to_categorical(y_train)

# call the fit method.

这篇关于Colab 中的 Tensorflow 错误 - ValueError: Shapes (None, 1) 和 (None, 10) 不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆