bp神经网络实现二分类代码
时间: 2023-06-02 12:04:08 浏览: 121
好的,关于这个问题,我可以回答。以下是实现二分类的BP神经网络的代码示例:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BPNeuralNet():
def __init__(self, input_dim, hidden_dim, output_dim):
# 初始化网络参数
self.input_dim = input_dim # 输入层维度
self.hidden_dim = hidden_dim # 隐藏层维度
self.output_dim = output_dim # 输出层维度
self.theta1 = np.random.randn(hidden_dim, input_dim + 1) # 第一层权重参数
self.theta2 = np.random.randn(output_dim, hidden_dim + 1) # 第二层权重参数
# 前向传播
def forward(self, x):
m = x.shape[0]
x = np.hstack((np.ones((m, 1)), x))
z2 = np.dot(x, self.theta1.T)
a2 = sigmoid(z2)
a2 = np.hstack((np.ones((m, 1)), a2))
z3 = np.dot(a2, self.theta2.T)
h = sigmoid(z3)
return h
# 反向传播
def backward(self, x, y, output):
delta3 = output - y
delta2 = np.dot(delta3, self.theta2[:, 1:]) * sigmoid(z2) * (1 - sigmoid(z2))
grad2 = np.dot(delta3.T, a2)
grad1 = np.dot(delta2.T, x)
return grad1, grad2
# 训练网络
def train(self, X, y, epochs, lr):
m = X.shape[0]
for epoch in range(epochs):
total_loss = 0.
for i in range(m):
x = X[i].reshape(1, -1)
output = self.forward(x)
loss = y[i] * np.log(output) + (1 - y[i]) * np.log(1 - output)
total_loss += loss
grad1, grad2 = self.backward(x, y[i], output)
self.theta1 -= lr * grad1
self.theta2 -= lr * grad2
avg_loss = - total_loss / m
print("Epoch %d, Loss %.4f" % (epoch + 1, avg_loss))
# 数据集
X = np.array([[2.7810836,2.550537003],
[1.465489372,2.362125076],
[3.396561688,4.400293529],
[1.38807019,1.850220317],
[3.06407232,3.005305973],
[7.627531214,2.759262235],
[5.332441248,2.088626775],
[6.922596716,1.77106367],
[8.675418651,-0.242068655],
[7.673756466,3.508563011]])
y = np.array([0,0,0,0,0,1,1,1,1,1])
# 训练BP神经网络
nn = BPNeuralNet(2, 5, 1)
nn.train(X, y, 100, 0.1)
# 预测样本输出
x_new = np.array([[2.7810836,2.550537003],
[1.465489372,2.362125076],
[3.396561688,4.400293529]])
output = nn.forward(x_new)
print(output)
```
这段代码实现了一个2维特征下的二分类BP神经网络。神经网络有两层,第一层为5个隐藏单元,第二层为1个输出单元。训练过程中使用交叉熵损失函数,学习率为0.1。最终输出给定样本的两个维度下的分类预测结果。
注意:这段代码只是一个简单的示例,在实际任务中需要根据具体情况调整模型结构、超参数和优化算法等。另外,建议使用深度学习框架,如tensorflow、pytorch等,来更方便地实现神经网络模型。