python - 为什么 tensorflow reshape 数组超出范围

标签 python python-3.x tensorflow deep-learning artificial-intelligence

我有数组 reshape 和大小问题

由于我还是新手,所以我没有尝试任何事情,而且我不想搞乱与该问题无关的事情

import tensorflow as tf
import numpy as np


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

x_train = tf.keras.utils.normalize(x_train, axis=1)  # scales data between 0 and 1
x_test = tf.keras.utils.normalize(x_test, axis=1) 

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(32,)))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))

x_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
x_test = np.reshape(x_test, (x_test.shape[0], 1, x_test.shape[1]))

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy', 
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=3)

val_loss, val_acc = model.evaluate(x_test, y_test)
print(val_loss)
print(val_acc)
  File "t1.py", line 17, in <module>
    x_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
  File "<__array_function__ internals>", line 6, in reshape
  File "H:\Program Files\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 301, in reshape
    return _wrapfunc(a, 'reshape', newshape, order=order)
  File "H:\Program Files\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 61, in _wrapfunc
    return bound(*args, **kwds)
ValueError: cannot reshape array of size 47040000 into shape (60000,1,28)```

最佳答案

model.add(tf.keras.layers.Flatten(input_shape=(28,28)))

它是一个 28x28 图像而不是 32 矢量 所以我们知道它不应该是 32 的向量 留下一个论点

关于python - 为什么 tensorflow reshape 数组超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57681345/

相关文章:

python-3.x - googleapiclient.errors.HttpError 与 google Drive v3 api 上传错误

python-3.x - 使用 PIP 安装时遇到问题

tensorflow - 无法启用 Tensorflows Eager execution

python - pandas 系列元素明智乘法

python - Matlab 的 tic 和 toc 函数的 Python 等价物是什么?

python - try-except 和 RuntimeWarning

tensorflow - 如何微调通用句子编码器 3 嵌入到自己的语料库

python - Python 中的 RE - lastindex 属性

python - 如何将 ndarray 转换为 scipy 中的矩阵?

javascript - 错误 : The shape of dict ['input' ] provided in model.execute(dict) 必须是 [1,224,224,3],但实际上是 [1,244,244,3]