python实现感知器

该博客通过Python实现了一个简单的神经网络,用于模拟逻辑运算中的AND和OR操作。通过迭代更新权重,最终得到能正确执行这两种逻辑运算的权重值。在AND运算中,网络成功学习到了权重[-0.59448, 0.59488, 0.59482],而在OR运算中,权重为[-0.00083, 0.70753, 0.70791]。这些权重可以用于预测输入的逻辑结果。
摘要由CSDN通过智能技术生成

import numpy as np
x1 = np.array([0, 0, 1, 1])
x2 = np.array([0, 1, 0, 1])
# and运算
y = np.array([0, 0, 0, 1])
# or运算
y1 = np.array([0, 1, 1, 1])
# 设初始值
w0 = -0.8
w1 = 0.5
w2 = 0.5
alpha = 0.001


# 阶跃函数
def fx(x1, x2):
    return w1*x1+w2*x2+w0


# 激活函数
def hy(xx1, xx2):
    if(fx(xx1,xx2)>0.5):
        return 1
    else:
        return 0


# and运算循环5000次
for i in range(5000):
    w0 = w0 - (fx(x1[i % 4], x2[i % 4]) - y[i % 4]) * alpha
    w1 = w1 - (fx(x1[i % 4], x2[i % 4]) - y[i % 4]) * x1[i % 4] * alpha
    w2 = w2 - (fx(x1[i % 4], x2[i % 4]) - y[i % 4]) * x2[i % 4] * alpha
    # 如果偏导小于0.001,输出此时权重及偏导
    if (abs(fx(x1[i % 4], x2[i % 4]) - y[i % 4]) < 0.001 and abs(
            (fx(x1[i % 4], x2[i % 4]) - y[i % 4]) * x1[i % 4]) < 0.001 and abs(
            (fx
感知器算法是一种二元线性分类算法,可以用于解决二元分类问题。基于Python实现感知器算法的步骤如下: 1. 导入必要的库和数据集 ```python import numpy as np import pandas as pd from sklearn.datasets import load_iris ``` 2. 加载数据集并预处理 ```python iris = load_iris() X = iris.data[:, (2, 3)] # 取花瓣长度和宽度作为特征 y = (iris.target == 0).astype(np.int) # 仅分类是否是山鸢尾 ``` 3. 定义感知器类 ```python class Perceptron: def __init__(self, eta=0.1, n_iter=50): self.eta = eta # 学习率 self.n_iter = n_iter # 迭代次数 def fit(self, X, y): self.w_ = np.zeros(1 + X.shape[1]) # 初始化权重 self.errors_ = [] # 记录每次迭代的误分类数 for _ in range(self.n_iter): errors = 0 for xi, target in zip(X, y): update = self.eta * (target - self.predict(xi)) self.w_[1:] += update * xi self.w_[0] += update errors += int(update != 0.0) # 统计误分类数 self.errors_.append(errors) return self def net_input(self, X): return np.dot(X, self.w_[1:]) + self.w_[0] def predict(self, X): return np.where(self.net_input(X) >= 0.0, 1, -1) ``` 4. 训练模型 ```python ppn = Perceptron(eta=0.1, n_iter=10) ppn.fit(X, y) ``` 5. 可视化结果 ```python import matplotlib.pyplot as plt plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o') plt.xlabel('Epochs') plt.ylabel('Number of misclassifications') plt.show() ``` 这样就可以基于Python实现感知器算法了。需要注意的是,感知器算法只能解决线性可分的问题,对于非线性可分的问题需要使用更高级的算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值