调用cnn.h5模型参数,训练mnist数据集
时间: 2023-05-28 20:06:41 浏览: 212
以下是使用Keras库调用CNN模型并训练MNIST数据集的示例代码:
```python
import numpy as np
from keras.models import load_model
from keras.datasets import mnist
from keras.utils import np_utils
# Load the pre-trained model
model = load_model('cnn.h5')
# Load the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Preprocess the data
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# Train the model on the MNIST data
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=128)
# Evaluate the model on the test data
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
在这个示例中,我们首先使用`load_model`函数从`cnn.h5`文件中加载预先训练的模型。然后,我们使用`mnist.load_data`函数加载MNIST数据集,并将数据预处理为模型所需的格式。最后,我们使用`fit`函数在MNIST数据集上训练模型,并使用`evaluate`函数在测试数据上评估模型的性能。
阅读全文