【问题标题】:I need fix with with ValueError in Keras我需要用 Keras 中的 ValueError 修复
【发布时间】:2020-11-26 21:45:44
【问题描述】:

我尤其是 ML 和 CNN 的新手,我正在学习视频教程,已经学习并练习了课程。 现在,为了练习更多我学到的东西。我让自己陷入了这个错误。我的数据集由带注释的癌症图像组成。我的简单设置遵循此过程,图像代表我的特征,而带注释的描述(即文件名)是数据集的标签。

以下代码提取图像,对其进行归一化

import numpy as np
import cv2
import pathlib
import sys

DATA_DIR='lung_cancer/'

def load_data(img):
  data_root=pathlib.Path(img)
  all_image_paths = list(data_root.glob('*/*'))
  return all_image_paths


data,target=[],[]

def process_image(image_path):
   min = sys.maxsize
   max = -sys.maxsize
   for image in image_path:
      image = cv2.imread(str(image))
      img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
      img_resize=cv2.resize(img,(64,64),interpolation=cv2.INTER_AREA)
      np_image = np.asarray(img_resize)
      if min > np_image.min():
         min = np_image.min()
      if max < np_image.max():
         max = np_image.max()

      np_image = np_image.astype('float32')
      np_image -= min
      np_image /= (max - min)
      data.append(np_image)

def data_set_split(img):
     image_paths=load_data(img)
     for image in image_paths:
         label = str(image)
         target.append(label.split('\\')[1])
      process_image(image_paths)

data_set_split(DATA_DIR)
x=np.asarray(data)
target =np.array(target).reshape(-1, 1)

from sklearn.preprocessing import LabelEncoder,OneHotEncoder
label=OneHotEncoder()
y=label.fit_transform(target)
from sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.20,random_state=54)
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D, Flatten, Dropout, MaxPooling2D
   

当我用x_train.shape 打印出 x_train 的形状时,我得到了这个x_train shape : (80, 64, 64)

以下是我对 CNN 的设置,

cnn_model = Sequential()
cnn_model.add(Conv2D(32,3,3, input_shape=(64, 64,1), activation='relu'))
cnn_model.add(MaxPooling2D(pool_size=(2,2)))
cnn_model.add(Flatten())

cnn_model.add(Dense(32, activation ='relu'))
cnn_model.add(Dense(10, activation ='sigmoid'))
cnn_model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')
epoch = 10

使用此代码cnn_model.summary() 进行上述设置的摘要如下:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 21, 21, 32)        320       
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 10, 10, 32)        0         
_________________________________________________________________
flatten (Flatten)            (None, 3200)              0         
_________________________________________________________________
dense (Dense)                (None, 32)                102432    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                330       
=================================================================
Total params: 103,082
Trainable params: 103,082
Non-trainable params: 0

所以,每当我执行以下代码部分时,都会出现以下错误

cnn_model.fit(x_train,
              y_train,
              batch_size=10,
              epochs = epoch,
              validation_data=(x_test, y_test)

              )

错误信息是

ValueError: 层序的输入 0 与 层::预期 min_ndim=4,发现 ndim=3。收到的完整形状: [无,64、64]

【问题讨论】:

  • 这个错误是不言自明的,当模型需要一个 4D 张量时,您正在传递一个 3D 张量。

标签: python tensorflow keras-layer


【解决方案1】:

如果你的输入形状是 (80, 64, 64),那么它与你的 CNN 的第一层不兼容,它期望输入的形状是 (64, 64, 1)。

(64, 64, 1) 表示 64 x 64 图像的 1 个样本。 要解决该错误,请使用 x_train.reshape(64,64,80) 重塑您的输入数据

有关在 CNN 中管理形状和通道的更多详细信息,请阅读:https://carlthome.github.io/posts/nhwc-vs.-nchw%20/

【讨论】:

  • 感谢您的建议,在更新代码以反映您的建议后,我现在收到此错误。错误消息是ValueError: Dimensions 64 and 80 are not compatible。你能提供关于需要做什么的线索吗?
  • 如果你的输入层有 (64, 64,1) 作为输入,并且你有 80 个样本,那么你的 x_train 的形状应该是 (80,64,64,1) 你可以通过循环遍历样本并将每个样本放入列表中。
猜你喜欢
  • 2019-06-03
  • 2015-06-10
  • 2023-03-31
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 2014-10-17
相关资源
最近更新 更多