生成一段python语言编写的,深度学习模型
时间: 2024-09-25 08:03:49 浏览: 38
在Python中,深度学习模型通常使用深度学习库如TensorFlow、PyTorch等编写。这里是一个简单的例子,展示如何使用Keras库创建一个基本的全连接神经网络(Dense Neural Network,DNN):
```python
# 导入所需库
from tensorflow import keras
import numpy as np
# 数据准备(假设我们有MNIST数据集)
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
# 定义模型结构
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(784,)), # 输入层,64个节点,ReLU激活
keras.layers.Dense(64, activation='relu'), # 隐藏层,64个节点
keras.layers.Dense(10, activation='softmax') # 输出层,10个类别,Softmax激活用于多分类
])
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
# 评估模型性能
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f'Test accuracy: {test_acc}')
阅读全文
相关推荐


















