WARNING:tensorflow:Model was constructed with shape (None, None, 240, 240, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None,None,240,240,3)

问题描述 投票:0回答:0

我正在创建一个用于脑肿瘤分类的 CNN-LSTM 模型。将模型拟合到给定数据时出现错误。这是那个错误👇🏻请尽快帮我清除这个错误。提前致谢。 (我在下面附上了我的代码) 警告:tensorflow:模型是用形状(无,无,64,64,3)构造的输入KerasTensor(type_spec = TensorSpec(shape =(None,None,64,64,3),dtype = tf.float32,name = 'time_distributed_36_input'), name='time_distributed_36_input', description="created by layer 'time_distributed_36_input'"), 但它是在形状不兼容的输入上调用的(无,无,无,无)。

我试过很多次改变图像的大小,但都无法达到正确的大小。 数据集链接:https://www.kaggle.com/datasets/navoneel/brain-mri-images-for-brain-tumor-detection 我的代码:

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, LSTM, Flatten, TimeDistributed, BatchNormalization
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score
import matplotlib.pyplot as plt
dataset_dir = "C:\Desktop\Final Year Project\RP"
batch_size = 120
img_size = (240,240)
datagen = ImageDataGenerator(
            validation_split=0.3,
            rescale=1./255,
            rotation_range=45,
            zoom_range=0.2,
            brightness_range=(0.5, 1.5),
            horizontal_flip=True
            )
train_ds = datagen.flow_from_directory(
        dataset_dir,
        batch_size=batch_size,
        subset="training",
        shuffle=True,
        class_mode="binary",
        target_size=img_size,
        classes={'no': 0., 'yes': 1.}
    )
val_ds = datagen.flow_from_directory(
        dataset_dir,
        batch_size=batch_size,
        subset="validation",
        shuffle=True,
        class_mode="binary",
        target_size=img_size,
        classes={'no': 0., 'yes': 1.}
    )
total_images = np.concatenate([train_ds.labels, val_ds.labels])
print('\n\n',{"No brain tumor cases": len(np.where(total_images==0)[0]),
             "Brain tumor cases": len(np.where(total_images==1)[0])})
fig, ax = plt.subplots(3,3, figsize=(10,10))
fig.suptitle("Brain Tumor Images")
for k in range(9):
    images, labels = train_ds.next()
    i, j = k//3, k%3
    ax[i, j].imshow(images[0])
    ax[i, j].set_title(f"label {int(labels[0])}")
    ax[i, j].axis('off')
plt.show()
# Define the CNN-LSTM model architecture
model = Sequential()
model.add(TimeDistributed(Conv2D(32, (3,3), activation='relu'), input_shape=(None,)+img_size+(3,)))
model.add(TimeDistributed(Conv2D(64, (3,3), activation='relu')))
model.add(TimeDistributed(MaxPooling2D((2,2))))
model.add(TimeDistributed(Flatten()))
model.add(LSTM(64, return_sequences=True))
model.add(LSTM(64, return_sequences=True))
model.add(LSTM(64, return_sequences=True))
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# Compile the model using SGD optimizer and binary cross-entropy loss function
sgd = SGD(learning_rate=0.0001)
model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy'])
# Train the model using cross-validation and data augmentation techniques
history = model.fit(train_ds, epochs=1, validation_data=val_ds)

WARNING:tensorflow:Model was constructed with shape (None, None, 240, 240, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, None, 240, 240, 3), dtype=tf.float32, name ='time_distributed_93_input'), name='time_distributed_93_input', description="created by layer 'time_distributed_93_input'"), 但它是在具有不兼容形状(无、无、无、无)的输入上调用的。 输出超出大小限制。在文本编辑器中打开完整的输出数据---------------------------------------- ---------------------------------- ValueError Traceback(最后一次调用) ~\AppData\Local\Temp/ipykernel_2312/3091208446.py 在() 1 # 使用交叉验证和数据增强技术训练模型 ----> 2 history = model.fit(train_ds, epochs=1, validation_data=val_ds)

c:\Users huva\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils raceback_utils.py in error_handler(*args, **kwargs) 68 # 要获取完整的堆栈跟踪,请调用: 69#

tf.debugging.disable_traceback_filtering()
---> 70 从 None 提高 e.with_traceback(filtered_tb) 71 最后: 72 删除 filtered_tb c:\Users huva\AppData\Local\Programs\Python\Python310\lib\site-packages\keras ngine raining.py in tf__train_function(迭代器) 13 尝试: 14 do_return = 真 ---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), 无, fscope) 16 除了: 17 do_return = 假 ValueError:在用户代码中: 文件“c:\Users huva\AppData\Local\Programs\Python\Python310\lib\site-packages\keras ngine raining.py”,第 1249 行,在 train_function * 返回 step_function(自我,迭代器) 文件“c:\Users huva\AppData\Local\Programs\Python\Python310\lib\site-packages\keras ngine raining.py”,第 1233 行,在 step_function ** ... 层“sequential_24”(类型 Sequential)收到的调用参数: • inputs=tf.Tensor(shape=(None, None, None, None), dtype=float32) • 训练=真 • 掩码=无`

tensorflow deep-learning conv-neural-network lstm valueerror
© www.soinside.com 2019 - 2024. All rights reserved.