博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
COMP7404 Machine Learing——Perceptron
阅读量:2135 次
发布时间:2019-04-30

本文共 5433 字,大约阅读时间需要 18 分钟。

implement by self

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.colors import ListedColormapdf = pd.read_csv('https://www.dropbox.com/s/mqyxvm8z2v1a20g/iris.data?dl=1', header=None)y = df.iloc[0:100, 4]y = np.where(y == 'Iris-setosa', -1, 1)X = df.iloc[0:100, [0, 2]].valuesclass Perceptron(object):    def __init__(self, eta=0.01, n_iter=50, random_state=1):        self.eta = eta        self.n_iter = n_iter        self.random_state = random_state        def fit(self, X, y):         #initiate the weights        rgen = np.random.RandomState(self.random_state)        self.w_ = rgen.normal(loc=0.0, scale=0.01, size=1 + X.shape[1])        self.errors_ = []        for _ in range(self.n_iter):            errors = 0            for xi, target in zip(X, y):                # print(xi,target)                update = self.eta * (target - self.predict(xi))                self.w_[1:] += update * xi                # print(self.w_[1:])                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)ppn = Perceptron(eta=0.1, n_iter=10) #set learning rate and iteration_numberppn.fit(X, y)plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')plt.xlabel('Epochs')plt.ylabel('Number of updates')plt.show()def plot_decision_regions(X, y, classifier, resolution=0.02):    markers = ('s', 'x', 'o', '^', 'v')    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')    cmap = ListedColormap(colors[:len(np.unique(y))])    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, resolution),                            np.arange(x2_min, x2_max, resolution))    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)    Z = Z.reshape(xx1.shape)    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)    plt.xlim(xx1.min(), xx1.max())    plt.ylim(xx2.min(), xx2.max())    for idx, cl in enumerate(np.unique(y)):        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8,                     c=colors[idx],  marker=markers[idx],                    label=cl, edgecolor='black')plot_decision_regions(X, y, classifier=ppn)plt.xlabel('sepal length [cm]')plt.ylabel('petal length [cm]')plt.legend(loc='upper left')plt.show()

 

 

 

use sklearn

from sklearn import datasetsimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import StandardScaleriris = datasets.load_iris() #the Iris dataset is already availale via sklearnX = iris.data[:, [2, 3]]y = iris.target# print('Class labels:', np.unique(y))X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y)#the train_test_split function shuffles the training sets internally and performs stratification before splitting#Otherwise, all class 0 and class 1 samples would have ended up in the training set, and the test set would consist of 45 samples from class 2#use StandardScalar class to do standardization(feature scaling)sc = StandardScaler()#get mean and std of datasetsc.fit(X_train) #different from models'fitX_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)from sklearn.linear_model import Perceptronppn = Perceptron(eta0=0.1, random_state=1)ppn.fit(X_train_std, y_train)y_pred = ppn.predict(X_train_std)print('Misclassified training samples:',(y_train!=y_pred).sum())y_pred = ppn.predict(X_test_std)print('Misclassified samples:', (y_test != y_pred).sum())from sklearn.metrics import accuracy_scoreprint('Accuracy: %.3f' % accuracy_score(y_test, y_pred))#print('Accuracy: %.3f' % ppn.score(X_test_std, y_test))from matplotlib.colors import ListedColormapimport matplotlib.pyplot as pltdef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):    markers = ('s', 'x', 'o', '^', 'v')    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')    cmap = ListedColormap(colors[:len(np.unique(y))])    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, resolution),                           np.arange(x2_min, x2_max, resolution))    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)    Z = Z.reshape(xx1.shape)    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)    plt.xlim(xx1.min(), xx1.max())    plt.ylim(xx2.min(), xx2.max())    for idx, cl in enumerate(np.unique(y)):        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8,                     c=colors[idx], marker=markers[idx],                     label=cl, edgecolor='black')    if test_idx:        X_test, y_test = X[test_idx, :], y[test_idx]        plt.scatter(X_test[:, 0], X_test[:, 1], c='none', edgecolor='black',                     alpha=1.0, linewidth=1,                    marker='o', s=100, label='test set')                  X_combined_std = np.vstack((X_train_std, X_test_std))y_combined = np.hstack((y_train, y_test))plot_decision_regions(X=X_combined_std, y=y_combined,                           classifier=ppn, test_idx=range(105, 150))plt.xlabel('petal length [standardized]')plt.ylabel('petal width [standardized]')plt.legend(loc='upper left')plt.tight_layout()plt.show()

转载地址:http://smygf.baihongyu.com/

你可能感兴趣的文章
【Python】关于Python多线程的一篇文章转载
查看>>
【Pyton】【小甲鱼】文件
查看>>
【Pyton】【小甲鱼】永久存储:腌制一缸美味的泡菜
查看>>
【Pyton】【小甲鱼】异常处理:你不可能总是对的
查看>>
APP性能测试工具
查看>>
【Pyton】【小甲鱼】类和对象
查看>>
压力测试工具JMeter入门教程
查看>>
作为一名软件测试工程师,需要具备哪些能力
查看>>
【Pyton】【小甲鱼】类和对象:一些相关的BIF(内置函数)
查看>>
【Pyton】【小甲鱼】魔法方法
查看>>
单元测试需要具备的技能和4大阶段的学习
查看>>
【Loadrunner】【浙江移动项目手写代码】代码备份
查看>>
Python几种并发实现方案的性能比较
查看>>
[Jmeter]jmeter之脚本录制与回放,优化(windows下的jmeter)
查看>>
Jmeter之正则
查看>>
【JMeter】1.9上考试jmeter测试调试
查看>>
【虫师】【selenium】参数化
查看>>
【Python练习】文件引用用户名密码登录系统
查看>>
学习网站汇总
查看>>
【Python】用Python打开csv和xml文件
查看>>