数据挖掘3

 

import numpy as np
import matplotlib.pyplot as plt


# 定义感知器,并使其可以预测输入数据类型,可以训练感知器
class Perceptron:
    def __init__(self, input, lrate=0.1, epochs=100):
        self.weights = np.zeros(input + 1)
        self.lrate = lrate
        self.epochs = epochs

    def activation_fn(self, x):
        return 1 if x >= 0 else 0

    def predict(self, x):
        z = self.weights.T.dot(x)
        a = self.activation_fn(z)
        return a

    def train_fitable(self, X, d):
        for _ in range(self.epochs):
            for i in range(d.shape[0]):
                x = np.insert(X[i], 0, 1)
                y = self.predict(x)
                e = d[i] - y
                self.weights = self.weights + self.lrate * e * x


# 随机生成数据
np.random.seed(0)
num_samples = 200
X = np.random.randn(num_samples, 2)
d = np.zeros(num_samples)
d[X[:, 0] + X[:, 1] >= 0] = 1

# 创建感知器实例并训练
perceptron = Perceptron(input=2)
perceptron.train_fitable(X, d)

# 绘制分类结果
plt.scatter(X[d == 0][:, 0], X[d == 0][:, 1], color='b', marker='o', label='0')
plt.scatter(X[d == 1][:, 0], X[d == 1][:, 1], color='r', marker='o', label='1')
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.1), np.arange(x2_min, x2_max, 0.1))
Z = np.array([perceptron.predict(np.array([1, xx1_, xx2_])) for xx1_, xx2_ in np.c_[xx1.ravel(), xx2.ravel()]])
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.3)
plt.xlabel('X1')
plt.ylabel('X2')
plt.legend(loc='best',edgecolor='blue')
plt.show()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值