前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >笔记一python代码

笔记一python代码

作者头像
用户1733462
发布2018-06-01 17:24:18
5480
发布2018-06-01 17:24:18
举报
文章被收录于专栏:数据处理数据处理数据处理
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
y = df.iloc[0:100, 4].values
y = np.where(y=='Iris-setosa',1,-1)
x = df.iloc[0:100, [0,2]].values

class Perceptron():
    def __init__(self, eta, X, Y, N):
        self.eta = eta
        self.X = X
        self.Y = Y
        self.N = N
        self.w = [0]*len(X[0])
        self.w0 = 0
        self.m = len(X)
        self.n = len(X[0])
    def output_y(self, x):
        z = np.dot(x,self.w)+self.w0
        if z > 0:
            return 1
        else:
            return -1
    def training(self):
        self.errors = []
        for times in xrange(self.N):
            error = 0
            for i in xrange(self.m):
                delta_y = self.Y[i]-self.output_y(self.X[i])
                if delta_y != 0:
                    error += 1
                self.w0 += self.eta*delta_y
                self.w += self.eta*delta_y*self.X[i]
            self.errors.append(error)
per = Perceptron(0.1, x, y, 10)
per.training()
print per.w0,per.w
print per.errors

w 0.4 [ 0.68 -1.82] errors [2, 2, 3, 2, 1, 0, 0, 0, 0, 0]

fig, axes = plt.subplots(1,2)
axes0, axes1 = axes.flatten()
axes0.plot(per.errors, marker='o')
axes0.set_title('errors')
axes1.scatter(x[:,0][0:50], x[:, 1][0:50], c = 'none', marker='o', color='r')
axes1.scatter(x[:,0][50:100], x[:, 1][50:100], marker='x', color='g')
axes1.annotate(r'versicolor',xy=(5.5,4.5),xytext=(4.5,5.5),arrowprops=dict(arrowstyle='->', facecolor='blue'))
axes1.annotate(r'setosa',xy=(5.8,2),xytext=(6.5,3),arrowprops=dict(arrowstyle='->', facecolor='blue'))
plt.subplots_adjust(left=0.1, right= 0.9, bottom=0.1, top=0.6)
plt.show()
# 使用训练得到w(0.4  0.68 -1.82),借助等高线contourf将区域分开,一部分数据大于0,一部分小于0
# 高度函数
def f(x, y):
    z = 0.4+0.68*x-1.82*y
    z = np.where(z>0,1,-1)
    return z
    
fig, axes = plt.subplots()
n = 200

mx = np.linspace(4, 7.5, n)
my = np.linspace(0, 6, n)
# 生成网格数据
X, Y = np.meshgrid(mx, my)
plt.contourf(X, Y, f(X, Y), 2, alpha = 0.75, cmap = plt.cm.RdBu)
axes.scatter(x[:,0][0:50], x[:, 1][0:50], c = 'none', marker='o', color='r')
axes.scatter(x[:,0][50:100], x[:, 1][50:100], marker='x', color='g')
axes.annotate(r'versicolor',xy=(5.5,4.5),xytext=(4.5,5.5),arrowprops=dict(arrowstyle='->', facecolor='blue'))
axes.annotate(r'setosa',xy=(5.8,2),xytext=(6.5,3),arrowprops=dict(arrowstyle='->', facecolor='blue'))
#plt.subplots_adjust(left=0.1, right= 0.9, bottom=0.1, top=0.6)
plt.show()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.06.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档