单隐层神经网络算法实现代码
时间: 2023-11-20 13:07:49 浏览: 27
单隐层神经网络算法实现代码可以使用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 sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def forward(self, X):
self.hidden = self.sigmoid(np.dot(X, self.weights1))
self.output = np.dot(self.hidden, self.weights2)
return self.output
def sigmoid_derivative(self, x):
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)
self.weights1 += np.dot(X.T, self.hidden_delta)
self.weights2 += np.dot(self.hidden.T, self.output_delta)
def train(self, X, y, epochs):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return self.forward(X)
```
这个代码实现了一个单隐层神经网络,其中包括输入层、隐层和输出层。在初始化时,随机生成权重矩阵。在前向传播过程中,使用sigmoid函数计算隐层和输出层的值。在反向传播过程中,计算输出误差和隐藏误差,并更新权重矩阵。在训练过程中,重复进行前向传播和反向传播,直到达到指定的迭代次数。在预测过程中,使用前向传播计算输出值。