神经网络算法python程序
时间: 2023-12-01 17:57:14 浏览: 58
以下是一个使用Python实现神经网络算法的示例代码:
```python
import numpy as np
#定义sigmoid函数
def sigmoid(x):
return 1/(1+np.exp(-x))
#定义神经网络类
class NeuralNetwork:
def __init__(self, layers):
self.weights = []
for i in range(1, len(layers)):
w = np.random.randn(layers[i], layers[i-1])
self.weights.append(w)
def forward(self, x):
a = x
for w in self.weights:
z = np.dot(w, a)
a = sigmoid(z)
return a
def backward(self, x, y, lr):
a = x
outputs = [a]
for w in self.weights:
z = np.dot(w, a)
a = sigmoid(z)
outputs.append(a)
error = y - a
deltas = [error * sigmoid(outputs[-1], True)]
for i in range(len(outputs)-2, 0, -1):
delta = np.dot(self.weights[i].T, deltas[-1]) * sigmoid(outputs[i], True)
deltas.append(delta)
deltas.reverse()
for i in range(len(self.weights)):
self.weights[i] += lr * np.dot(deltas[i], outputs[i].T)
#测试神经网络
nn = NeuralNetwork([2, 4, 1])
x = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([[0], [1], [1], [0]])
for i in range(10000):
index = np.random.randint(0, len(x))
nn.backward(x[index], y[index], 0.1)
print(nn.forward([0,0]))
print(nn.forward([0,1]))
print(nn.forward([1,0]))
print(nn.forward([1,1]))
```
此示例实现了一个简单的2层神经网络,用于解决XOR问题。它使用随机梯度下降算法来更新权重,并使用sigmoid函数作为激活函数。
阅读全文