基于一维数组的神经网络代码
时间: 2023-11-14 21:08:33 浏览: 32
以下是一个基于一维数组的神经网络的代码示例,该示例使用 Python 和 NumPy 库实现:
```python
import numpy as np
# 定义神经网络类
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
# 初始化权重和偏差
self.weights1 = np.random.randn(input_size, hidden_size)
self.bias1 = np.zeros((1, hidden_size))
self.weights2 = np.random.randn(hidden_size, output_size)
self.bias2 = np.zeros((1, output_size))
def forward(self, X):
# 前向传播
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = np.tanh(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = np.sigmoid(self.z2)
return self.a2
def backward(self, X, y, output):
# 反向传播
self.error = output - y
self.delta2 = np.multiply(self.error, np.multiply(self.a2, 1 - self.a2))
self.weights2_gradient = np.dot(self.a1.T, self.delta2)
self.bias2_gradient = np.sum(self.delta2, axis=0, keepdims=True)
self.delta1 = np.multiply(np.dot(self.delta2, self.weights2.T), np.multiply(self.a1, 1 - self.a1))
self.weights1_gradient = np.dot(X.T, self.delta1)
self.bias1_gradient = np.sum(self.delta1, axis=0)
def train(self, X, y, epochs, learning_rate):
# 训练模型
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
# 更新权重和偏差
self.weights1 -= learning_rate * self.weights1_gradient
self.bias1 -= learning_rate * self.bias1_gradient
self.weights2 -= learning_rate * self.weights2_gradient
self.bias2 -= learning_rate * self.bias2_gradient
def predict(self, X):
# 预测结果
output = self.forward(X)
predictions = np.round(output)
return predictions
```
在这个示例中,神经网络的输入和输出都是一维数组。`input_size` 表示输入层的大小,`hidden_size` 表示隐藏层的大小,`output_size` 表示输出层的大小。在初始化函数中,我们随机初始化权重和偏差。
`forward` 函数执行前向传播,计算每一层的加权和,并将其输入激活函数中得到每一层的输出。在这个示例中,我们使用 tanh 函数作为隐藏层的激活函数,使用 sigmoid 函数作为输出层的激活函数。
`backward` 函数执行反向传播,计算每一层的误差并使用梯度下降算法更新权重和偏差。
`train` 函数用于训练模型,它接受训练数据、标签、迭代次数和学习率作为参数。我们可以在这个函数中多次调用前向传播和反向传播函数来更新权重和偏差。
`predict` 函数用于预测新的输入数据的结果。它接受输入数据作为参数,并返回模型的预测结果。在这个示例中,我们将输出四舍五入到最接近的整数来得到预测结果。