python 搭建神经网络 示例
时间: 2023-09-06 20:06:48 浏览: 96
以下是一个简单的示例,展示如何使用 Python 搭建神经网络:
```python
import numpy as np
# 定义神经网络类
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# 初始化权重
self.W1 = np.random.randn(input_size, hidden_size)
self.W2 = np.random.randn(hidden_size, output_size)
def forward(self, X):
# 前向传播
self.z = np.dot(X, self.W1)
self.z2 = self.sigmoid(self.z)
self.z3 = np.dot(self.z2, self.W2)
y_hat = self.sigmoid(self.z3)
return y_hat
def sigmoid(self, x):
# sigmoid 激活函数
return 1 / (1 + np.exp(-x))
# 创建神经网络实例
input_size = 2
hidden_size = 3
output_size = 1
nn = NeuralNetwork(input_size, hidden_size, output_size)
# 输入数据
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# 训练神经网络
learning_rate = 0.1
epochs = 10000
for i in range(epochs):
# 前向传播
阅读全文