我无法加载我的模型,它一直显示错误
ValueError:层“dense_2”需要 1 个输入,但它收到了 2 个输入张量。收到的输入: [<KerasTensor shape=(None, 7, 7, 1280), dtype=float32,稀疏=False, name=keras_tensor_2896>, <KerasTensor shape=(None, 7, 7, 1280), dtype=float32,稀疏=False,name=keras_tensor_2897>]
这是我的代码
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
# )
epochs = 20
batch_size = 32
for epoch in range(epochs):
print(f"Epoch {epoch + 1}/{epochs}")
# Training
# Use model.fit for training instead of manual iteration
history = model.fit(
train_dataset,
epochs=1, # Train for one epoch at a time within the outer loop
validation_data=validation_dataset,
steps_per_epoch=train_dataset.samples // batch_size,
validation_steps=validation_dataset.samples // batch_size,
verbose=1
)
# Validation - This part can remain the same
val_loss, val_accuracy = model.evaluate(validation_dataset)
print(f"Validation - Loss: {val_loss:.4f}, Accuracy: {val_accuracy:.4f}")
print("Training complete.")from keras.models import load_model
model_save_path = '/content/drive/MyDrive/Machine Learning/saved_models/model_plastik.h5'
model.save(model_save_path,save_format='keras')
model.summary()
print(f'Model disimpan di: {model_save_path}')
# 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.")
我尝试加载模型,我希望它加载以进行测试
错误信息“ValueError:层“dense_2”需要 1 个输入,但它收到了 2 个输入张量”表明正在尝试将两个输入传递给的模型中应该只接收一个输入的层。这可能是由于如何从
MobileNetV2
模型中提取和使用子模型的方式造成的。
以下是如何解决此问题的步骤:
- 加载模型时不要提取子模型:
当前的代码在加载保存的模型后会立即提取一个子模型。这可能会导致问题,因为它会更改模型的预期输入结构。首先,尝试加载完整的模型,而无需提取任何层:
python
loaded_model = tf.keras.models.load_model(model_save_path)
- 检查加载模型的摘要:
加载完整模型后,打印其摘要以了解其结构和输入/输出形状:
python
loaded_model.summary()
- 如果需要,请修改输入/输出:
如果需要使用
loaded_model
的一部分进行预测或进一步的训练,则可以定义一个新的模型,该模型将
loaded_model
的特定层作为输入和输出。例如,如果想从
dense_2
层获取输出,可以这样做:
```python from tensorflow.keras.models import Model
intermediate_layer_model = Model(inputs=loaded_model.input, outputs=loaded_model.get_layer('dense_2').output) ```
这将创建一个名为
intermediate_layer_model
的新模型,该模型以与
loaded_model
相同的输入作为输入,但输出
dense_2
层的输出。
确保以下内容:
- 的输入数据形状与加载的模型的输入层预期形状相匹配。
- 如果修改模型以提取子模型或添加新层,请确保新模型的输入和输出定义正确。
通过按照上述步骤操作,应该能够解决该错误并成功加载和使用保存的模型。如果有任何进一步的问题或需要更多帮助,请随时提供更多上下文或代码片段,以便我能够为提供更具体的指导。
标签:python,tensorflow,machine-learning,keras,tf.keras From: 78846949