其中w为权值(weight),b为偏置(bias) 这就是感知机模型
能将正实例和负实例完全正确的分离嫂超平面两侧.则称为线性可分.
# -*- coding:utf-8 -*-
# /usr/bin/python
'''
-------------------------------------------------------------------------
@File Name : perception.py
@Description : 感知机numpy实现版本
@Run Script : python perception.py
@Envs : pip install
@Change Activity:
1. 2021/12/1 下午4:18 : build
-------------------------------------------------------------------------
@CodeStyle : standard, simple, readable, maintainable, and portable!
@Author : Yan Errol 13075851954
@Email : 260187357@qq.com
@Copyright : "Copyright 2021, Yan Errol"
-------------------------------------------------------------------------
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 类封装
class perception_model():
def __init__(self,XTrain):
'''参数定义'''
self.learning_rate = 0.5
self.b = 0
self.w = np.ones(len(XTrain[0]),dtype=np.float32)
def sign(self,x,w,b):
'''误点判段'''
y = np.dot(x, w) + b
return y
def fit(self,xTrain,yTrain):
'''训练'''
isWrong = False
while not isWrong:
wrongNums = 0
# 错误点判段
ytest = self.sign(xTrain,self.w,self.b)
wrongPointIndex = np.where(yTrain*ytest <= 3)
xWrong,yWrong = xTrain[wrongPointIndex],yTrain[wrongPointIndex]
wrongNums = len(yWrong)
if wrongNums == 0: #终止条件判段
break
else:
i = np.random.randint(0,wrongNums)
x,y = xWrong[i],yWrong[i]
self.w = self.w + self.learning_rate * np.dot(y, x)
self.b = self.b + self.learning_rate * y
return 'Perception train is Done!'
def predict(self,x):
'''预测'''
y = np.dot(x, self.w) + self.b
print("y",y)
if y > 0:
y = 1
else:
y = 0
return y
# 数据加载
data = pd.read_csv("dataset.csv")
print(data.label.value_counts())
print("data\n",data)
# 数据可视化 验证线性可分性
plt.scatter(data[:50]['sepal length'], data[:50]['sepal width'], label='0')
plt.scatter(data[50:100]['sepal length'], data[50:100]['sepal width'], label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()
plt.savefig("show.png")
# 数据集拆分
data = np.array(data.iloc[:100,[0,1,-1]])
XTrain,Ytrain = data[:-1,:-1],data[:-1,-1]
Xtest,Ytest = data[-1, : -1], data[-1, -1]
# 训练
perception = perception_model(XTrain)
perception.fit(XTrain,Ytrain)
yPredict = perception.predict(Xtest)
print(yPredict,Ytest)