总的来说,我是 Tensorflow 和机器学习的新手。我正在尝试创建一个模型来通过 MRI 检测脑肿瘤。
我正在使用 validation_split
拆分数据。编译模型后,当我尝试使用 .fit
函数进行拟合时,出现此错误。谷歌搜索后我发现我可能是因为我在调用 y
函数时没有传递 fit
参数。
代码:
datagen = ImageDataGenerator(validation_split=0.2, rescale=1. / 255)
train_generator = datagen.flow_from_directory(
TRAIN_DIR,
target_size=(150, 150),
batch_size=32,
class_mode='binary',
subset='training'
)
val_generator = datagen.flow_from_directory(
TRAIN_DIR,
target_size=(150, 150),
batch_size=32,
class_mode='binary',
subset='validation'
)
model = tf.keras.models.Sequential()
model.add(
tf.keras.layers.Conv2D(
16,
(3, 3),
activation='relu',
input_shape=(150, 150, 3)
)
)
model.add(
tf.keras.layers.MaxPool2D(2, 2)
)
...
# some more layers
...
model.compile(
optimizer='adam',
loss=None,
metrics=['accuracy'],
)
print(model.summary())
Test = model.fit(
train_generator,
epochs=2,
verbose=1,
validation_data=val_generator
)
我做错了什么?
图片的文件夹结构:
images
|
├── training
│ ├── no
│ ├── yes
├── testing
│ ├── no
│ ├── yes
确切的错误信息:
ValueError: No gradients provided for any variable: ['conv2d/kernel:0', 'conv2d/bias:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0', 'conv2d_2/kernel:0', 'conv2d_2/bias:0', 'dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0'].
model.summary() 的输出:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 148, 148, 16) 448
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 74, 74, 16) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 72, 72, 32) 4640
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 36, 36, 32) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 34, 34, 64) 18496
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 17, 17, 64) 0
_________________________________________________________________
flatten (Flatten) (None, 18496) 0
_________________________________________________________________
dense (Dense) (None, 512) 9470464
_________________________________________________________________
dense_1 (Dense) (None, 2) 1026
=================================================================
Total params: 9,495,074
Trainable params: 9,495,074
Non-trainable params: 0
答案 0 :(得分:1)
这是因为您将损失设置为 None
,所以没有从损失函数返回到您的模型的梯度。修改
model.compile(
optimizer='adam',
loss=None,
metrics=['accuracy'],
)
到
model.compile(
optimizer='adam',
loss='mse', # or some other loss
metrics=['accuracy'],
)