MLP的两种实现(不同在于forward)

该博客介绍了如何实现一个多层感知机(MLP)分类器,包括激活函数(Sigmoid和Tanh)、反向传播算法以及小批量梯度下降的优化。代码展示了MLP在二维数据集上的决策边界绘制,并通过调整超参数(如层数、迭代次数和学习率)来适应数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def dsigmoid(y):
    return y * (1 - y)

def tanh(x):
    return np.tanh(x)

def dtanh(y):
    return 1.0 - y ** 2

class MLPClassifier:
    def __init__(self, layers, activation='tanh', epochs=20, learning_rate=0.01):
        # 第一层为输入层, 层数应等于样本特征数
        # 最后一层为输出层
        # 再算上中间层, 所以len(layers)最小为3
        self.epochs = epochs
        self.eta = learning_rate
        self.layers = [np.zeros(layers[0])]
        self.weights = []
        self.biases = []
        for i in range(len(layers) - 1):
            # 这三个者的初始值是随意的
            weight = np.random.random((layers[i + 1], layers[i]))
            layer = np.ones(layers[i + 1])
            bias = np.random.random(layers[i + 1])
            self.weights.append(weight)
            self.layers.append(layer)
            self.biases.append(bias)
        if activation == 'tanh':
            self.activation = tanh
            self.dactivation = dtanh
        elif activation == 'sigmoid':
            self.activation = sigmoid
            self.dactivation = dsigmoid
    def fit(self, X, y):
        for _ in range(self.epochs):
            # 随机梯度下降
            indexes = np.random.permutation(X.shape[0])
            for i in range(X.shape[0]):
                self.forward(X[indexes[i]])
                self.backward(y[indexes[i]])
        return self
    # 方便二维图像的可视化, 实际预测的结果可能不止有一个维度, 不一定能和数值进行比较
    def predict(self, X):
        return np.where(self.predict_prob(X) >= 0.5, 1, 0)
    def predict_prob(self, X):
        y = np.empty((X.shape[0], len(self.layers[-1])))
        for i in range(X.shape[0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青灯有味是儿时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值