前馈神经网络python实现
时间: 2023-07-08 13:51:11 浏览: 94
以下是一个简单的前馈神经网络的Python实现:
```python
import numpy as np
class NeuralNetwork:
def __init__(self, layers):
self.weights = []
self.biases = []
for i in range(1, len(layers)):
self.weights.append(np.random.randn(layers[i], layers[i-1]))
self.biases.append(np.random.randn(layers[i], 1))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def feedforward(self, a):
for w, b in zip(self.weights, self.biases):
a = self.sigmoid(np.dot(w, a) + b)
return a
def train(self, X, y, epochs, lr):
for i in range(epochs):
for x, target in zip(X, y):
x = x.reshape(-1, 1)
target = target.reshape(-1, 1)
activations = [x]
for w, b in zip(self.weights, self.biases):
z = np.dot(w, activations[-1]) + b
a = self.sigmoid(z)
activations.append(a)
error = activations[-1] - target
deltas = [error * activations[-1] * (1 - activations[-1])]
for w, a in zip(reversed(self.weights[1:]), reversed(activations[:-1])):
delta = np.dot(w.T, deltas[-1]) * a * (1 - a)
deltas.append(delta)
deltas.reverse()
for w, b, delta, a in zip(self.weights, self.biases, deltas, activations[:-1] + [x]):
w -= lr * np.dot(delta, a.T)
b -= lr * delta
def predict(self, X):
return np.array([np.argmax(self.feedforward(x)) for x in X])
```
上面的代码实现了一个简单的前馈神经网络,使用sigmoid函数作为激活函数。其中,初始化函数接受一个列表,表示每层神经元的数量;feedforward函数接受一个输入,返回神经网络的输出;train函数接受输入数据、标签、迭代次数和学习率,用于训练神经网络;predict函数接受输入数据,返回预测结果。
阅读全文