keras:形状 (None, 1) 和 (None, 3) 不兼容
keras: Shapes (None, 1) and (None, 3) are incompatible
我正在参加这个 kaggle 比赛,我必须将这个 X 射线分为 3 类细菌、病毒或正常。
我不明白为什么它让我给出同样的错误。
图像是 rgb,输出形状是 (none,3)
所以我真的不知道形状是 (none,1)
的东西在哪里。
有人可以帮助我吗?
这是我的代码:
将 tensorflow 导入为 tf
从 tensorflow 导入 keras
来自 tensorflow.keras 导入图层
TRAIN_DIR = 'D:/tf/archiveBilanciato/chest_xray/train/PNEUMONIA'
TEST_DIR = 'D:/tf/archiveBilanciato/chest_xray/test'
IMG_SIZE = 224 #224 è quella migliore
IMAGE_SIZE = (IMG_SIZE, IMG_SIZE)
BATCH_SIZE = 32
LR = 1e-3
import os
nt = 0
for folder_name in ("bacteria", "normal","virus"):
folder_path = os.path.join("D:/tf/NeoArchiveBilanciato/chest_xray", folder_name)
for fname in os.listdir(folder_path):
fpath = os.path.join(folder_path, fname)
nt += 1
print("Totale immagini di questa categoria: %d" % nt)
nt = 0
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
"D:/tf/NeoArchiveBilanciato/chest_xray",
validation_split=0.2,
subset="training",
seed=1337,
color_mode='rgb',
image_size=IMAGE_SIZE,
batch_size=BATCH_SIZE,
)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
"D:/tf/NeoArchiveBilanciato/chest_xray",
validation_split=0.2,
subset="validation",
seed=1337,
color_mode='rgb',
image_size=IMAGE_SIZE,
batch_size=BATCH_SIZE,
)
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.applications import DenseNet121
from keras.layers import GlobalAveragePooling2D,Dense
def pre_model():
base_model = tf.keras.applications.DenseNet121(
weights='imagenet', include_top=False, input_shape=(224, 224, 3))
x = base_model.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(14, activation="softmax")(x)
pre_model = keras.Model(inputs=base_model.input, outputs=predictions)
return pre_model
base_model = pre_model()
base_model.load_weights("D:/tf/nih_pretrained_chest_model.h5")
print("base_model")
print(base_model.summary())
base_model.trainable = False
mio_classificatore = Dense(3, activation='softmax')(base_model.layers[-2].output)
print("mio_classificatore.get_shape()")
print(mio_classificatore.get_shape())
nuovo_model = keras.Model(inputs=base_model.input, outputs=mio_classificatore)
print("nuovo_model")
print(nuovo_model.summary())
train = train_ds.prefetch(buffer_size=32)
val = val_ds.prefetch(buffer_size=32)
callbacks = [
keras.callbacks.ModelCheckpoint("save_at_{epoch}.h5"),
]
nuovo_model.compile(optimizer=keras.optimizers.Adam(LR),
loss=keras.losses.CategoricalCrossentropy(),
metrics=[keras.metrics.Accuracy()])
nuovo_model.fit(train,batch_size=32, epochs=14,callbacks=callbacks, validation_data=val)
错误发生在 model.fit(...) 我收到此消息的位置:
ValueError: Shapes (None, 1) and (None, 3) are incompatible
与 keras 的 DataImageGenerator
不同,image_dataset_from_directory
默认为整数标签。
如果要使用categorical_crossentropy
损失函数,需要在image_dataset_from_directory()中定义label_mode='categorical'
得到One-Hot编码标签
我正在参加这个 kaggle 比赛,我必须将这个 X 射线分为 3 类细菌、病毒或正常。
我不明白为什么它让我给出同样的错误。
图像是 rgb,输出形状是 (none,3)
所以我真的不知道形状是 (none,1)
的东西在哪里。
有人可以帮助我吗?
这是我的代码: 将 tensorflow 导入为 tf 从 tensorflow 导入 keras 来自 tensorflow.keras 导入图层
TRAIN_DIR = 'D:/tf/archiveBilanciato/chest_xray/train/PNEUMONIA'
TEST_DIR = 'D:/tf/archiveBilanciato/chest_xray/test'
IMG_SIZE = 224 #224 è quella migliore
IMAGE_SIZE = (IMG_SIZE, IMG_SIZE)
BATCH_SIZE = 32
LR = 1e-3
import os
nt = 0
for folder_name in ("bacteria", "normal","virus"):
folder_path = os.path.join("D:/tf/NeoArchiveBilanciato/chest_xray", folder_name)
for fname in os.listdir(folder_path):
fpath = os.path.join(folder_path, fname)
nt += 1
print("Totale immagini di questa categoria: %d" % nt)
nt = 0
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
"D:/tf/NeoArchiveBilanciato/chest_xray",
validation_split=0.2,
subset="training",
seed=1337,
color_mode='rgb',
image_size=IMAGE_SIZE,
batch_size=BATCH_SIZE,
)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
"D:/tf/NeoArchiveBilanciato/chest_xray",
validation_split=0.2,
subset="validation",
seed=1337,
color_mode='rgb',
image_size=IMAGE_SIZE,
batch_size=BATCH_SIZE,
)
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.applications import DenseNet121
from keras.layers import GlobalAveragePooling2D,Dense
def pre_model():
base_model = tf.keras.applications.DenseNet121(
weights='imagenet', include_top=False, input_shape=(224, 224, 3))
x = base_model.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(14, activation="softmax")(x)
pre_model = keras.Model(inputs=base_model.input, outputs=predictions)
return pre_model
base_model = pre_model()
base_model.load_weights("D:/tf/nih_pretrained_chest_model.h5")
print("base_model")
print(base_model.summary())
base_model.trainable = False
mio_classificatore = Dense(3, activation='softmax')(base_model.layers[-2].output)
print("mio_classificatore.get_shape()")
print(mio_classificatore.get_shape())
nuovo_model = keras.Model(inputs=base_model.input, outputs=mio_classificatore)
print("nuovo_model")
print(nuovo_model.summary())
train = train_ds.prefetch(buffer_size=32)
val = val_ds.prefetch(buffer_size=32)
callbacks = [
keras.callbacks.ModelCheckpoint("save_at_{epoch}.h5"),
]
nuovo_model.compile(optimizer=keras.optimizers.Adam(LR),
loss=keras.losses.CategoricalCrossentropy(),
metrics=[keras.metrics.Accuracy()])
nuovo_model.fit(train,batch_size=32, epochs=14,callbacks=callbacks, validation_data=val)
错误发生在 model.fit(...) 我收到此消息的位置:
ValueError: Shapes (None, 1) and (None, 3) are incompatible
与 keras 的 DataImageGenerator
不同,image_dataset_from_directory
默认为整数标签。
如果要使用categorical_crossentropy
损失函数,需要在image_dataset_from_directory()中定义label_mode='categorical'
得到One-Hot编码标签