python神经网络算法实例
时间: 2023-07-27 22:18:38 浏览: 55
以下是一个简单的Python神经网络算法实例:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义神经网络类
class NeuralNetwork:
def __init__(self):
# 随机初始化权重
self.weights = np.random.randn(2, 1)
self.bias = np.random.randn(1)
def feedforward(self, x):
# 前向传播
output = sigmoid(np.dot(x, self.weights) + self.bias)
return output
def train(self, x, y, epochs):
# 训练神经网络
for epoch in range(epochs):
# 前向传播
output = self.feedforward(x)
# 计算损失函数
error = y - output
# 计算梯度
d_weights = np.dot(x.T, error * output * (1 - output))
d_bias = np.sum(error * output * (1 - output))
# 更新权重和偏置
self.weights += d_weights
self.bias += d_bias
# 打印训练进度
if (epoch+1) % 100 == 0:
print("Epoch:", epoch+1, "Loss:", np.mean(np.abs(error)))
# 创建数据集
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
# 创建神经网络
nn = NeuralNetwork()
# 训练神经网络
nn.train(X, y, epochs=1000)
# 打印预测结果
print(nn.feedforward(X))
```
这个例子实现了一个简单的多层感知器(MLP),它包含一个输入层、一个隐藏层和一个输出层。它使用sigmoid函数作为激活函数,使用随机梯度下降算法进行训练。这个神经网络可以用来解决XOR问题。