【问题标题】:ValueError: Input 0 of layer sequential_6 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [32, 28, 28]ValueError: 层序号_6 的输入 0 与层不兼容:预期 ndim=4,发现 ndim=3。收到的完整形状:[32、28、28]
【发布时间】:2020-11-16 10:50:37
【问题描述】:

我尝试了以下代码,但遇到了上述错误。我看到了一些类似的问题,但我没有得到适当的解决方案。请帮帮我!

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

mnist=tf.keras.datasets.mnist  #download the dataset
(xtrain, ytrain),(xtest, ytest)=mnist.load_data() #split the dataset in test and train
xtrain=tf.keras.utils.normalize(xtrain, axis=1)
xtest=tf.keras.utils.normalize(xtest, axis=1)

model=tf.keras.models.Sequential() # start building the model
model.add(tf.keras.layers.Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Conv2D(32, kernel_size=3, activation='relu', input_shape=(28,28,1)))
model.add(tf.keras.layers.Flatten()) # converting matrix to vector
model.add(tf.keras.layers.Dense(10,activation=tf.nn.softmax)) # adding a layer with 10 nodes(as only 10 outputs are possible) and softmax activaation function
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # specifiying hyperparameters
model.fit(xtrain,ytrain,epochs=5,) # load the model
model.save('Ashwatdhama') # save the model with a unique name

myModel=tf.keras.models.load_model('Ashwatdhama')  # make an object of the model
prediction=myModel.predict((xtest)) # run the model object
for i in range(10): 
  print(np.argmax(prediction[i]))
  plt.imshow(xtest[i]) # make visuals of mnist dataset
  plt.show() #output

【问题讨论】:

  • 别忘了点赞并接受它;-)
  • 是的,当然,你也请为我的问题投票!

标签: python-3.x keras tensorflow2.0 numpy-ndarray conv-neural-network


【解决方案1】:

您的网络需要黑白图像(1 个通道),因此您必须相应地修改数据。这可以在拟合之前简单地为您的图像添加维度

xtrain = xtrain[...,None] # (batch_dim, 28, 28, 1)
xtest = xtest[...,None] # (batch_dim, 28, 28, 1)

【讨论】:

  • 我这样做了 ----> 9 xtrain = xtrain[1, 28, 28, 1] # (batch_dim, 28, 28, 1) 10 xtest = xtest[1, 28, 28, 1] 11 model=tf.keras.models.Sequential() # 开始构建模型 IndexError: too many indices for array\
  • xtrain[1,28,28,1] 与 xtrain[...,None] 不同。请听从我的建议。这里是正在运行的笔记本:colab.research.google.com/drive/… 不要忘记接受它;-)
  • [...,None]是什么意思?你能解释一下吗?
  • [...,None] 在最后一个位置添加一个简单的维度...它与 np.expand_dims(xtrain, -1) 相同
  • 非常感谢您的帮助!
猜你喜欢
  • 2020-11-26
  • 2020-03-20
  • 2020-11-15
  • 2023-03-17
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多