多层感知机(MLP)代码
时间: 2024-03-25 07:34:24 浏览: 171
MLP.rar_MLP matlab_MLP 多层感知器matlab代码_clothinga3k_多层感知器_机器学习
5星 · 资源好评率100%
多层感知机(Multilayer Perceptron,简称MLP)是一种常见的人工神经网络模型,它由多个神经元层组成,每个神经元层与下一层之间都有连接。以下是一个简单的MLP代码示例:
```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.weights2 = np.random.randn(self.hidden_size, self.output_size)
# 初始化偏置
self.bias1 = np.zeros((1, self.hidden_size))
self.bias2 = np.zeros((1, self.output_size))
def forward(self, X):
# 前向传播
self.hidden_layer = np.dot(X, self.weights1) + self.bias1
self.hidden_activation = self.sigmoid(self.hidden_layer)
self.output_layer = np.dot(self.hidden_activation, self.weights2) + self.bias2
self.output_activation = self.sigmoid(self.output_layer)
return self.output_activation
def backward(self, X, y, learning_rate):
# 反向传播
error = y - self.output_activation
delta_output = error * self.sigmoid_derivative(self.output_activation)
error_hidden = delta_output.dot(self.weights2.T)
delta_hidden = error_hidden * self.sigmoid_derivative(self.hidden_activation)
# 更新权重和偏置
self.weights2 += self.hidden_activation.T.dot(delta_output) * learning_rate
self.bias2 += np.sum(delta_output, axis=0, keepdims=True) * learning_rate
self.weights1 += X.T.dot(delta_hidden) * learning_rate
self.bias1 += np.sum(delta_hidden, axis=0, keepdims=True) * learning_rate
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):
output = self.forward(X)
predictions = np.round(output)
return predictions
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
```
这段代码实现了一个简单的MLP模型,包括初始化权重和偏置、前向传播、反向传播、训练和预测等功能。你可以根据自己的需求进行修改和扩展。
阅读全文