能否提供一个用Python实现的基于多层感知机(Multilayer Perceptron)的简单趣味实验代码示例?
时间: 2024-11-05 12:33:54 浏览: 27
当然可以。这里是一个简单的多层感知机(MLP)模型在Python中使用Keras库实现的示例,用于手写数字识别。我们将使用经典的MNIST数据集:
```python
# 导入所需库
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
# 加载并预处理MNIST数据
def load_data():
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 归一化到0-1范围
train_images, test_images = train_images / 255.0, test_images / 255.0
# 将标签转换为独热编码
train_labels, test_labels = to_categorical(train_labels), to_categorical(test_labels)
return (train_images, train_labels), (test_images, test_labels)
# 创建MLP模型
def create_model(input_shape):
model = Sequential([
Dense(128, activation='relu', input_shape=input_shape),
Dense(64, activation='relu'),
Dense(10, activation='softmax') # 输出层有10个节点,对应0-9的手写数字
])
return model
# 编译模型
def compile_model(model):
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
def train_model(model, train_data, epochs=10):
train_images, train_labels = train_data
model.fit(train_images, train_labels, epochs=epochs)
# 测试模型
def evaluate_model(model, test_data):
test_images, test_labels = test_data
_, accuracy = model.evaluate(test_images, test_labels)
print(f"Test Accuracy: {accuracy * 100:.2f}%")
# 主函数
if __name__ == "__main__":
(train_data, _), (test_data, _) = load_data()
model = create_model(train_data[0].shape[1:])
compile_model(model)
train_model(model, train_data)
evaluate_model(model, test_data)
阅读全文