神经网络python代码详解
时间: 2024-09-28 13:14:15 浏览: 47
神经网络是一种模拟人脑工作原理的计算模型,通过连接多个节点(节点即神经元),处理复杂的输入数据并学习预测输出。Python作为流行的机器学习语言,有许多库如TensorFlow、PyTorch等可以方便地创建和训练神经网络。
以下是一个简单的例子,使用Keras库构建一个全连接神经网络(Multilayer Perceptron, MLP):
```python
# 导入所需的库
import tensorflow as tf
from tensorflow import keras
# 数据准备(这里假设我们已经有了输入数据X和目标标签y)
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
X_train, X_test = X_train / 255.0, X_test / 255.0 # 归一化像素值到0-1范围
# 创建一个Sequential模型
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)), # 展平输入数据
keras.layers.Dense(128, activation='relu'), # 全连接层,ReLU激活函数
keras.layers.Dropout(0.2), # 防止过拟合,设置dropout比例
keras.layers.Dense(10, activation='softmax') # 输出层,Softmax用于分类
])
# 编译模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test))
# 测试模型性能
test_loss, test_acc = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_acc}")
```
在这个例子中,首先导入了必要的库,然后加载MNIST数据集,接着创建了一个简单的神经网络模型结构,并配置了优化器、损失函数和评估指标。最后,模型进行了训练,并在测试集上进行了性能评估。
阅读全文
相关推荐


















