神经网络的python代码
时间: 2023-09-01 12:07:19 浏览: 69
bp 神经网络算法. python代码实例
以下是一个简单的神经网络的 Python 代码示例:
```python
import numpy as np
# 定义神经网络类
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
# 初始化权重矩阵
self.weights1 = np.random.randn(self.input_size, self.hidden_size)
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
def forward(self, X):
# 前向传播计算输出
self.hidden = np.dot(X, self.weights1)
self.hidden_activation = self.sigmoid(self.hidden)
self.output = np.dot(self.hidden_activation, self.weights2)
return self.output
def sigmoid(self, x):
# sigmoid 激活函数
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
# sigmoid 激活函数的导数
return x * (1 - x)
def backward(self, X, y, output):
# 反向传播计算误差
self.output_error = y - output
self.output_delta = self.output_error * self.sigmoid_derivative(output)
self.hidden_error = np.dot(self.output_delta, self.weights2.T)
self.hidden_delta = self.hidden_error * self.sigmoid_derivative(self.hidden_activation)
# 梯度下降更新权重矩阵
self.weights1 += np.dot(X.T, self.hidden_delta)
self.weights2 += np.dot(self.hidden_activation.T, self.output_delta)
def train(self, X, y, epochs):
# 训练神经网络
for epoch in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
```
这是一个基本的单层神经网络,包含前向传播、反向传播和训练过程。你可以根据需求进行修改和扩展。
阅读全文