Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

perceptron python

作者:木の兮   发布日期:2026-05-25   浏览:49

# Perceptron Implementation in Python

import numpy as np

class Perceptron:
    def __init__(self, learning_rate=0.01, n_iterations=1000):
        self.learning_rate = learning_rate
        self.n_iterations = n_iterations
        self.weights = None
        self.bias = None

    def fit(self, X, y):
        n_samples, n_features = X.shape

        # Initialize weights and bias
        self.weights = np.zeros(n_features)
        self.bias = 0

        # Convert labels to 1 and -1 for binary classification
        y_ = np.where(y <= 0, -1, 1)

        # Training loop
        for _ in range(self.n_iterations):
            for idx, x_i in enumerate(X):
                linear_output = np.dot(x_i, self.weights) + self.bias
                prediction = np.sign(linear_output)

                # Update rule
                update = self.learning_rate * (y_[idx] - prediction)
                self.weights += update * x_i
                self.bias += update

    def predict(self, X):
        linear_output = np.dot(X, self.weights) + self.bias
        return np.sign(linear_output)

# Example usage:
if __name__ == "__main__":
    # Sample data
    X = np.array([[2.7810836, 2.550537003],
                  [1.465489372, 2.362125076],
                  [3.396561688, 4.400293529],
                  [1.38807019, 1.850220317]])
    y = np.array([0, 0, 1, 1])

    # Create and train the perceptron
    perceptron = Perceptron(learning_rate=0.01, n_iterations=1000)
    perceptron.fit(X, y)

    # Make predictions
    predictions = perceptron.predict(X)
    print("Predictions:", predictions)

解释说明:

  1. Perceptron 类:实现了感知机算法。它有两个主要方法:fitpredict
  2. 初始化:在 __init__ 方法中,我们设置了学习率 (learning_rate) 和迭代次数 (n_iterations)。同时,权重 (weights) 和偏置 (bias) 被初始化为 None
  3. 训练过程 (fit)
    • 初始化权重和偏置。
    • 将标签转换为 1 和 -1(用于二分类)。
    • 使用更新规则调整权重和偏置,直到达到最大迭代次数或模型收敛。
  4. 预测过程 (predict):根据输入数据计算线性输出,并使用符号函数 (np.sign) 得到最终预测结果。
  5. 示例用法:创建一个感知机实例,使用样本数据进行训练,并输出预测结果。

希望这段代码和解释对你有帮助!

上一篇:python卸载第三方库

下一篇:python串口发送16进制数据

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站