使用python实现BP,并且输入层为10列的矩阵,输出层为1列的矩阵,实现对输入层和输出层矩阵的标准化,并提供一个测试数据以得出预测结果
时间: 2024-05-04 11:18:46 浏览: 12
好的,下面是使用Python实现BP神经网络,并对输入层和输出层进行标准化的代码:
```python
import numpy as np
class MLP:
def __init__(self, n_input, n_hidden, n_output):
self.n_input = n_input
self.n_hidden = n_hidden
self.n_output = n_output
# 随机初始化权重
self.W1 = np.random.randn(n_hidden, n_input)
self.b1 = np.random.randn(n_hidden, 1)
self.W2 = np.random.randn(n_output, n_hidden)
self.b2 = np.random.randn(n_output, 1)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return self.sigmoid(x) * (1 - self.sigmoid(x))
def forward(self, X):
# 输入层标准化
X = (X - np.mean(X)) / np.std(X)
# 隐层输入
self.z1 = np.dot(self.W1, X) + self.b1
# 隐层输出
self.a1 = self.sigmoid(self.z1)
# 输出层标准化
output_mean = np.mean(self.a1)
output_std = np.std(self.a1)
self.a1 = (self.a1 - output_mean) / output_std
# 输出层输入
self.z2 = np.dot(self.W2, self.a1) + self.b2
# 输出层输出
self.a2 = self.sigmoid(self.z2)
return self.a2
def backward(self, X, y, learning_rate):
# 计算输出误差
delta2 = (self.a2 - y) * self.sigmoid_derivative(self.z2)
# 计算隐层误差
delta1 = np.dot(self.W2.T, delta2) * self.sigmoid_derivative(self.z1)
# 更新输出层权重和偏置
self.W2 -= learning_rate * np.dot(delta2, self.a1.T)
self.b2 -= learning_rate * delta2
# 更新隐层权重和偏置
self.W1 -= learning_rate * np.dot(delta1, X.T)
self.b1 -= learning_rate * delta1
def train(self, X, y, learning_rate, epochs):
for i in range(epochs):
for j in range(len(X)):
# 前向传播
output = self.forward(X[j])
# 反向传播
self.backward(X[j], y[j], learning_rate)
def predict(self, X):
# 预测结果
prediction = []
for i in range(len(X)):
output = self.forward(X[i])
prediction.append(output[0])
return prediction
```
下面是使用测试数据进行预测的示例代码:
```python
# 生成随机测试数据
X = np.random.rand(100, 10)
y = np.random.rand(100, 1)
# 创建 MLP 对象
mlp = MLP(10, 5, 1)
# 训练模型
mlp.train(X, y, learning_rate=0.1, epochs=100)
# 预测结果
prediction = mlp.predict(X)
print(prediction)
```
以上就是使用Python实现BP神经网络,并对输入层和输出层进行标准化的完整代码,可以根据需要进行调整和修改。