简体   繁体   English

如何修复:ValueError:检查输入时出错:预期 conv2d_130_input 具有形状 (1, 512, 512) 但得到形状为 (79, 512, 512) 的数组

[英]How to fix: ValueError: Error when checking input: expected conv2d_130_input to have shape (1, 512, 512) but got array with shape (79, 512, 512)

I am a beginner at working with CNNs.我是使用 CNN 的初学者。

So, I am building a 2D convolutional neural network that predicts brain tumor type and have a question about NumPy arrays.所以,我正在构建一个预测脑肿瘤类型的 2D 卷积神经网络,并有一个关于 NumPy 数组的问题。 The input-shape of my model is (1, 512, 512) as (channels, img_height, img_width).我的模型的输入形状是 (1, 512, 512) as (channels, img_height, img_width)。 The 4th dimension is num_images which seems to be automatically defined by TensorFlow.第 4 个维度是 num_images,它似乎是由 TensorFlow 自动定义的。 This is just a quick background.这只是一个快速的背景。 I have 3064 ".mat" extension files with MRI scans of brain tumors.我有 3064 个“.mat”扩展文件,其中包含脑肿瘤的 MRI 扫描。 Everything is setup.一切都设置好了。 I converted ".mat" files into numpy matrices and appended the entire list of matrices in a single numpy array to pass as input for the CNN.我将“.mat”文件转换为 numpy 矩阵,并将整个矩阵列表附加到单个 numpy 数组中以作为 CNN 的输入传递。 I also have the corresponding labels (index-linked to the images when passing input into the model) as a numpy array.我也有相应的标签(将输入传递到模型时链接到图像的索引)作为一个 numpy 数组。 All the numbers are of float type in both images and labels.图像和标签中的所有数字都是浮点型。

Again, my input shape is (1, 512, 512).同样,我的输入形状是 (1, 512, 512)。 However, when fitting my model I get the following error:但是,在拟合我的模型时,出现以下错误:

ValueError: Error when checking input: expected conv2d_130_input to have shape (1, 512, 512) but got array with shape (79, 512, 512) ValueError:检查输入时出错:预期 conv2d_130_input 具有形状 (1, 512, 512) 但得到形状为 (79, 512, 512) 的数组

So, I am slicing my NumPy arrays to create train_images, train_labels, test_images, test_labels.所以,我正在切片我的 NumPy 数组以创建 train_images、train_labels、test_images、test_labels。 I have verified the length of each both train and test sets with there labels match.我已经用标签匹配验证了每个训练集和测试集的长度。 They are also arrays, I checked multiple times.它们也是数组,我检查了多次。 And this is a value error.这是一个价值错误。 So, how do I fix this?那么,我该如何解决这个问题?

I don't even know where the input shape became (79,512,512).我什至不知道输入形状变成了什么 (79,512,512)。 I have a loop to convert f"{n}.mat" images to a matrix.我有一个循环将 f"{n}.mat" 图像转换为矩阵。 I am using 100 images to test and have 80 train and 20 test.我使用 100 张图像进行测试,并进行了 80 次训练和 20 次测试。 I think the mistake is here, the input shape is (channels, img-hght, img-wdth), but the number of images left to train is being placed in the channel's value instead.我认为错误就在这里,输入形状是 (channels, img-hght, img-wdth),但是剩下要训练的图像数量被放置在通道的值中。 So, the input is being placed as (num_images, img-hght, img-wdth).因此,输入被放置为 (num_images, img-hght, img-wdth)。 This is wrong and should be changed, but I don't know how to do it.这是错误的,应该更改,但我不知道该怎么做。 Or, I could be wrong and what I said might not make sense.或者,我可能是错的,我说的话可能没有意义。 I am providing all the code, running it on Colab.我提供了所有代码,并在 Colab 上运行它。 Make sure to change the image paths if you download the code and want to run it in order to help me out.如果您下载代码并想运行它以帮助我,请确保更改图像路径。 Thanks a lot!非常感谢!

Dataset: https://figshare.com/articles/brain_tumor_dataset/1512427/5数据集: https : //figshare.com/articles/brain_tumor_dataset/1512427/5

#Importing the necessary libraries through PIP to the Virtual Environment
try:
  !python -m pip install --upgrade pip #Quickly update PIP to latest version
  !python -m pip install pymatreader
  !python -m pip install pyswarm #An interesting library for testing purposes
  print("""
The following libraries are available and have been successfully fetched:
  >>> PyMatReader
  >>> Particle Swarm""")
except Exception:
  print("""
The following libraries have unavailable and have not been fetched:
  >>> PyMatReader
  >>> Particle Swarm""")
  pass
#Importing the necessary libraries to the Virtual Environment
from __future__ import absolute_import, division, print_function, unicode_literals
import random as rnd
from random import shuffle
import numpy as np
import sys
import scipy as sp
from scipy.ndimage import gaussian_filter
import pymatreader as pym
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.image as mplimg
import matplotlib.pyplot as plt
import PIL
from PIL import Image
import imageio
import sklearn as sk
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import image
import sklearn.metrics as skm

print("""
The following libraries have been successfully imported:
  >>> Future
  >>> Random (with shuffle)
  >>> NumPy
  >>> System
  >>> SciPy (with gaussian filter)
  >>> PyMatReader
  >>> Pandas
  >>> Seaborn
  >>> Matplotlib (with PyPlot & Image)
  >>> PIL (with Image)
  >>> Imageio
  >>> Sci-Kit Learn (with metrics & train_test_split)
  >>> Sci-kit Learn Feature Extraction (with Image)
""")

try:
  %tensorflow_version 2.x
  import keras
  import tensorflow as tf
  print("TensorFlow version 2.x is available and has been successfully imported.")
except Exception:
  %tensorflow_version 1.x
  import keras
  import tensorflow as tf
  print("TensorFlow version 2.x is unavailable. TensorFlow version 1.x has been imported instead.")
  pass

from tensorflow.keras import datasets, layers, models
import keras.preprocessing
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from keras.optimizers import Adam
import pyswarm
from pyswarm import pso

autoTune = tf.data.experimental.AUTOTUNE

print("""
The following deep learning optimizers have been successfully imported:
  >>> Adam
  >>> Particle Swarm (with pso)
""")

print("All libraries have been successfully imported.")
#Understanding the Image Data using Seaborn and Matplotlib
classNames = {1 : "Meningioma", 2 : "Glioma", 3 : "Pituitary Tumor", 4 : "Unkown", 5 : "Unkown"}
outputSize = len(classNames)

chooseImgNum = 2978
example = pym.read_mat(f'/content/gdrive/My Drive/My Files/Neuroimaging/Neuroimaging Datasets/MATLAB Files/{chooseImgNum}.mat')
cjdata = example['cjdata']
pid = cjdata['PID']
img = cjdata['image']
label = cjdata['label']

tumorBorder = cjdata['tumorBorder']
tumorMask = cjdata['tumorMask']
print("Tumor Border is: \n", tumorBorder, "\n")
print("Tumor Mask is: \n", tumorMask, "\n")

def printImage():
  plt.figure(figsize=(5, 5))
  plt.imshow(img, cmap=None)

def matrixConv(): #Data Visualization only
  matrix = np.asmatrix(tumorBorder)
  plt.figure(figsize=(5, 5))
  return matrix

def applyGrayscale():
  plt.figure(figsize=(5, 5))
  plt.imshow(img, cmap='gray')

print("""
      Below is the original image followed by a grayscale application:
____________________________________________________________________________
""")

printImage()
applyGrayscale()
#Preprocessing Brain Images from Dataset
range1 = np.arange(0, 100)
imgMatrices = []
imgNum = 1
i = 1

while imgNum in range1:
  imgNum = pym.read_mat(f'/content/gdrive/My Drive/My Files/Neuroimaging/Neuroimaging Datasets/MATLAB Files/{imgNum}.mat')
  cjdata = imgNum['cjdata']
  imgMatrix = cjdata['image']
  # plt.figure(figsize=(5, 5))
  # plt.imshow(image_matrix, cmap='gray')
  imgMatrixNP = np.asmatrix(imgMatrix)
  imgArrayNP = np.asarray(imgMatrixNP)
  imgMatrices.append(imgArrayNP)
  imgNum = i
  i = i + 1

print("The length of the image input list is:", len(imgMatrices))

imgMatricesNP = np.asarray(imgMatrices)
print("The length of the converted image input array is:", len(imgMatricesNP), "\n")

print("The image input array:")
imgMatricesNP #Prints the raw array
#Supervised Learning: Understanding Cancer Type labels
np.set_printoptions(threshold=3)
#np.set_printoptions(threshold=sys.maxsize) #To check the content of the entire array

rawMatData = pym.read_mat('/content/gdrive/My Drive/My Files/Neuroimaging/Neuroimaging Datasets/cvind.mat')
print("Labels file in \".mat\" format converted to dictionary format:", rawMatData)

matDataList = list(rawMatData.values())
print("Labels converted to list format:", matDataList)

matDataArray = np.asarray(matDataList)
print("Labels converted to array format:", matDataArray, "\n")
shapedMatDataArray = matDataArray.reshape(-1, 3064, 1)
print("Reshaped labels in array format:\n", shapedMatDataArray, "\n")

matData = pd.DataFrame(matDataArray)
print("Labels converted to a Pandas DataFrame:")
matData #Prints out the DataFrame
#Viewing labels based on image number
def imgLabelCheck(n):
  callback = matData.at[0, n-1]
  print(f"Image Number {n} has the following Cancer Type: {classNames[callback]}.")
  return

pickImg = 1 #Choose an image number to look for its Cancer Type
imgLabelCheck(pickImg)
#Preparing the Datasets: Looping Train Set & Test Set
print("___________________________________________________________________________________\n")

train_images = np.array([imgMatricesNP[0:79]])
print("Training images range is:\n", train_images, "\n")

uppTrBn = len(train_images)
loqTrRng = 0
uppTrRng = 79
train_labels = np.asarray(matData.loc[:, loqTrRng:uppTrRng], dtype=float, order='A')
print("Training labels range is:", train_labels)

print("___________________________________________________________________________________\n")

test_images = np.array([imgMatricesNP[80:100]])
print("Testing images range is: \n", test_images, "\n")

uppTsBn = len(test_images)
loqTsRng = 80
uppTsRng = 100
test_labels = np.asarray(matData.loc[:, loqTsRng:uppTsRng], dtype=float, order='A')
print("Testing labels range is:", test_labels)

print("___________________________________________________________________________________")
#train_labels #Verify if the ranges are in fact NumPy arrays
#test_labels
#Defining the Convolutional Neural Network
model = models.Sequential()

model.add(layers.Conv2D(512, (3, 3), activation='relu', data_format="channels_first", input_shape=(1, 512, 512))) #The Input Layer
#model.add(layers.Dropout(0.5, noise_shape=None, seed=None)) #Optional Dropout Layer

model.add(layers.MaxPooling2D((2, 2), padding='same')) #MaxPooling Layer 1
model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same')) #Hidden Convolutional Layer 1
model.add(layers.Dropout(0.5, noise_shape=None, seed=None)) #Optional Dropout Layer

model.add(layers.MaxPooling2D((2, 2), padding='same')) #MaxPooling Layer 2
model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same')) #Hidden Convolutional Layer 2
#model.add(layers.Dropout(0.5, noise_shape=None, seed=None)) #Optional Dropout Layer

model.add(layers.MaxPooling2D((2, 2), padding='same')) #MaxPooling Layer 3
model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same')) #Hidden Convolutional Layer 3
model.add(layers.Dropout(0.5, noise_shape=None, seed=None)) #Optional Dropout Layer

model.add(layers.MaxPooling2D((2, 2), padding='same')) #MaxPooling Layer 4
model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same')) #Hidden Convolutional layer 4
#model.add(layers.Dropout(0.5, noise_shape=None, seed=None)) #Optional Dropout Layer

model.add(layers.MaxPooling2D((2, 2), padding='same')) #MaxPooling Layer 5
model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same')) #Hidden Convolutional Layer 5
model.add(layers.Dropout(0.5, noise_shape=None, seed=None)) #Optional Dropout Layer

model.add(layers.MaxPooling2D((2, 2), padding='same')) #MaxPooling Layer 6
model.add(layers.Conv2D(1024, (3, 3), activation='relu', padding='same')) #Hidden Convolutional Layer 6
#model.add(layers.Dropout(0.5, noise_shape=None, seed=None)) #Optional Dropout Layer

model.add(layers.Flatten()) #The Flattening Layer

model.add(layers.Dense(512, activation='relu')) #Dense Layer 1
model.add(layers.Dense(256, activation='relu')) #Dense Layer 2
model.add(layers.Dense(128, activation='relu')) #Dense Layer 3
model.add(layers.Dense(64, activation='relu')) #Dense Layer 4
model.add(layers.Dense(32, activation='relu')) #Dense Layer 5
model.add(layers.Dense(16, activation='relu')) #Dense Layer 6

model.add(layers.Dense(outputSize, activation='softmax')) #The Output Layer

model.summary()
#Compiling the Convolutional Neural Network with an Optimizer
#The Adam Optimizer is ideal for biological image classification.
#The Optimizer automatically performs forward and backward propagation.

model.compile(
    optimizer='Adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'],
    loss_weights=None,
    sample_weight_mode=None,
    weighted_metrics=None,
    target_tensors=None
  )

print("The Neuroimaging Model has been successfully compiled.")
#Training the Convolutional Neural Network
history = model.fit(train_images, train_labels, epochs=10, batch_size=1, verbose=1,
                    validation_data=(test_images, test_labels))

print("\nThe Neuroimaging Model has been successfully trained.")

Each code box on this page represents a single code cell for Colab or Jupyter notebook.此页面上的每个代码框代表 Colab 或 Jupyter 笔记本的单个代码单元。 Once again, all help is welcome and appreciated!再次欢迎并感谢所有帮助! (The model is not fully built, but layers are added for experimentation only. (该模型尚未完全构建,但添加层仅用于实验。

Add the line:添加行:

train_images = np.reshape(train_images, (-1,1,512,512))

after the below line in your code在您的代码中的以下行之后

train_images = np.array([imgMatricesNP[0:79]])

to get the individual images' input_shape=(1, 512, 512) instead of (79, 512, 512) because the model is expecting an input shape of (1, 1, 512, 512) (according to the dimensions (batch_size, channels, height, width) ) while your current code provides an input shape of (1, 79, 512, 512) .获得单个图像的input_shape=(1, 512, 512)而不是(79, 512, 512)因为模型期望输入形状为(1, 1, 512, 512) (根据尺寸(batch_size,通道, 高度, 宽度) ) 而您当前的代码提供的输入形状为(1, 79, 512, 512) If you have sufficient compute resources, increase the batch_size to 8 (say), so that your total input shape would be (8, 1, 512, 512) .如果您有足够的计算资源,请将 batch_size 增加到8 (比如说),这样您的总输入形状将为(8, 1, 512, 512)

Also, perform a similar operation on test_images :另外,对test_images执行类似的操作:

test_images = np.reshape(test_images, (-1,1,512,512))

after the line:行后:

test_images = np.array([imgMatricesNP[80:100]])

PS: Also, it seems that your intent is to slice the first 80 images from the input imgMatricesNP . PS:此外,您的意图似乎是从输入imgMatricesNP切出前 80 张图像。 However, with imgMatricesNP[0:79] , you only get the first 79 images (as the last index of a slice is excluded in Python).但是,使用imgMatricesNP[0:79] ,您只能获得前 79 个图像(因为 Python 中排除了切片的最后一个索引)。 So, the correction would be:因此,更正将是:

train_images = np.array([imgMatricesNP[0:80]])

and assign uppTrRng=80 .并分配uppTrRng=80

Hope this helps!希望这可以帮助! :) :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ValueError:检查输入时出错:预期conv2d_1_input具有4维,但数组的形状为(454,512,512) - ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (454, 512, 512) 期望conv1d_1_input具有形状(15,512)但是具有形状的数组(4,512) - expected conv1d_1_input to have shape (15, 512) but got array with shape (4, 512) ValueError:检查时出错:预期density_1_input具有2维,但数组的形状为(1,16,16,512) - ValueError: Error when checking : expected dense_1_input to have 2 dimensions, but got array with shape (1, 16, 16, 512) ValueError:检查输入时出错:预期flatten_1_input具有形状(4、4、512),但数组的形状为(128、128、3) - ValueError: Error when checking input: expected flatten_1_input to have shape (4, 4, 512) but got array with shape (128, 128, 3) ValueError:检查时出错:预期flatten_1_input具有形状(无,4、4、512),但数组的形状为(1、150、150、3) - ValueError: Error when checking : expected flatten_1_input to have shape (None, 4, 4, 512) but got array with shape (1, 150, 150, 3) 检查目标时出错:预期的activation_2的形状为(512,),但数组的形状为(1,) - Error when checking target: expected activation_2 to have shape (512,) but got array with shape (1,) ValueError:检查输入时出错:预期conv2d_79_input具有4个维,但数组的形状为(99,4457,4) - ValueError: Error when checking input: expected conv2d_79_input to have 4 dimensions, but got array with shape (99, 4457, 4) 未捕获(承诺)错误:检查时出错:预期flatten_1_input具有形状[null,7,7,512],但数组的形状为[1,224,224,3] - Uncaught (in promise) Error: Error when checking : expected flatten_1_input to have shape [null,7,7,512] but got array with shape [1,224,224,3] 无法将输入数组从形状 (512,512,100) 广播到形状 (512,512) - could not broadcast input array from shape (512,512,100) into shape (512,512) 无法将输入数组从形状 (512,512) 广播到形状 (512,512,2) - could not broadcast input array from shape (512,512) into shape (512,512,2)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM