我无法加载我的模型,它一直说错误
ValueError:层“dense_2”需要 1 个输入,但它收到了 2 个输入张量。收到的输入:[
这是我的代码
image_generator = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
zoom_range=0.2,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
validation_split=0.2
)
train_dataset = image_generator.flow_from_directory(
directory=path_to_dataset,
target_size=(224, 224),
batch_size=32,
subset='training'
)
validation_dataset = image_generator.flow_from_directory(
directory=path_to_dataset,
target_size=(224, 224),
batch_size=32,
subset='validation'
)
# Menentukan jumlah kelas (num_classes) berdasarkan jumlah subfolder dalam dataset
num_classes = len(train_dataset.class_indices)
from tensorflow.keras.applications.mobilenet import MobileNet
# Load the MobileNet model
pre_trained_model = tf.keras.applications.MobileNetV2(input_shape=(224, 224, 3),
include_top=False,
weights='imagenet')
pre_trained_model.summary()
# Print dataset information for debugging
print(f"Training dataset shape: {train_dataset.image_shape}")
print(f"Validation dataset shape: {validation_dataset.image_shape}")
pre_trained_model.trainable = False
# Menambahkan layer kustom di atas model pre-trained
model = tf.keras.Sequential([
pre_trained_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_classes, activation='softmax')
])
# Compile model
#from tensorflow.keras.optimizers import RMSprop
model.compile(optimizer=Adam(learning_rate=0.0001),
loss='categorical_crossentropy',
metrics=['accuracy'])
batch=40
history = model.fit(train_dataset,
validation_data=validation_dataset,
epochs=20,
steps_per_epoch = train_dataset.samples//batch,
validation_steps = validation_dataset.samples//batch,
verbose = 1
)
# Load the model
model_save_path = '/content/drive/MyDrive/Machine Learning/saved_models/model_plastik.h5'
# Load the model, ensuring it's compiled if needed
loaded_model = tf.keras.models.load_model(model_save_path)
# Now you can modify the loaded model if necessary
# For example, if you want to extract a sub-model:
input_layer_index = 0 # Replace with the actual index
dense_2_index = 3 # Replace with the actual index
loaded_model = tf.keras.models.Model(inputs=loaded_model.layers[input_layer_index].input,
outputs=loaded_model.layers[dense_2_index].output)
# Check the configuration of the loaded model
for i, layer in enumerate(loaded_model.layers):
print(f"Layer {i}: {layer.name} - Input shape: {layer.input_shape} - Output Shape: {layer.output_shape}")
print("Revised model loaded successfully.")
我尝试加载模型,我希望它加载到测试
有同样的问题,只需尝试使用功能 API 实现相同的架构即可。