MLP模型python源码
时间: 2024-03-13 18:41:53 浏览: 86
当谈到MLP(多层感知机)模型的Python源代码时,以下是一个简单的示例:
```python
import numpy as np
class MLP:
def __init__(self, input_size, hidden_size, output_size):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
# 初始化权重和偏置
self.weights1 = np.random.randn(self.input_size, self.hidden_size)
self.bias1 = np.zeros((1, self.hidden_size))
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
self.bias2 = np.zeros((1, self.output_size))
def forward(self, X):
# 前向传播
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.sigmoid(self.z2)
return self.a2
def backward(self, X, y, learning_rate):
# 反向传播
m = X.shape[0]
# 计算输出层的误差
delta2 = (self.a2 - y) * self.sigmoid_derivative(self.z2)
# 计算隐藏层的误差
delta1 = np.dot(delta2, self.weights2.T) * self.sigmoid_derivative(self.z1)
# 更新权重和偏置
d_weights2 = np.dot(self.a1.T, delta2) / m
d_bias2 = np.sum(delta2, axis=0) / m
d_weights1 = np.dot(X.T, delta1) / m
d_bias1 = np.sum(delta1, axis=0) / m
self.weights2 -= learning_rate * d_weights2
self.bias2 -= learning_rate * d_bias2
self.weights1 -= learning_rate * d_weights1
self.bias1 -= learning_rate * d_bias1
def train(self, X, y, epochs, learning_rate):
for epoch in range(epochs):
output = self.forward(X)
self.backward(X, y, learning_rate)
def predict(self, X):
return np.round(self.forward(X))
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return self.sigmoid(x) * (1 - self.sigmoid(x))
```
这是一个简单的MLP模型的实现,包括初始化权重和偏置、前向传播、反向传播、训练和预测等功能。你可以根据需要进行修改和扩展。
阅读全文