python 写个神经网络模型
时间: 2023-07-08 21:26:37 浏览: 67
好的,以下是一个简单的神经网络模型的 Python 代码:
```python
import numpy as np
# 定义激活函数及其导数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
# 定义神经网络类
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_layer = sigmoid(np.dot(X, self.weights1))
self.output_layer = sigmoid(np.dot(self.hidden_layer, self.weights2))
return self.output_layer
def backward(self, X, y, output):
# 反向传播
self.output_error = y - output
self.output_delta = self.output_error * sigmoid_derivative(output)
self.hidden_error = np.dot(self.output_delta, self.weights2.T)
self.hidden_delta = self.hidden_error * sigmoid_derivative(self.hidden_layer)
# 更新权重矩阵
self.weights2 += np.dot(self.hidden_layer.T, self.output_delta)
self.weights1 += np.dot(X.T, self.hidden_delta)
def train(self, X, y, epochs):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
```
这个模型包含一个输入层、一个隐藏层和一个输出层。在初始化时,权重矩阵随机初始化。前向传播和反向传播都是基于 sigmoid 激活函数及其导数进行计算的。`train` 函数用于训练模型。
阅读全文