ML实践-万事开头难

相关资料

因为自己学习过相关理论知识,但是从来没有用代码实现过,所以想开一个专题专门锻炼自己实践。
1. 语言:python
2. 代码参考: https://github.com/Hallao0/python-machine-learning-book
3. 书籍参考: machine learning book

配置环境

  • 系统 windows 64-bits
  • python 版本 3.6.0 64-bits
    官网上下载的不知道为什么总是32位的,后来百度“python 64”才能找到64位的
  • Anaconda3 4.4.0 64-bits
    安装成功Anaconda以后,用管理员身份打开“Anaconda Prompt”. 然后依次
conda install packageName

Pakages包括:
* Numpy
* SciPy
* scikit-learn
* matplotlib
* pandas

实现perceptron

原理

如果是线性可分的场景:
这里写图片描述
以预测的y与真实的y的差值 按照learning rate的倍速更新weights的值:
Δwj=η(y(i)y^(i))X(i)j
对于每个training sample X(i) :
1. 计算预测值 y^
2. 更新weights

实现

输入:
* feature数据集: x
* classification 数据集 y
* learning rate eta
* 迭代次数 n_iter

输出 :
* 分类模型
* 预测

import numpy as np
class Perceptron(object):

    def __init__(self, eta=0.01, n_iter=10):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        #X:50x2, shape是(50L,2L),shape[1]=2
        self.w_ = np.zeros(1 + X.shape[1])
        self.errors_ = []
        for _ in range(self.n_iter):
            errors = 0
            #zip:将第i个X与第i个y合并成第i个tuple
            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):
        #where(condition,(yes)A,(no)B)
        return np.where(self.net_input(X) >= 0.0, 1, -1)

测试

读数据

>>> import pandas as pd
>>> df = pd.read_csv('https://archive.ics.uci.edu/ml/'
 'machine-learning-databases/iris/iris.data', header=None)
>>> df.tail()

这里写图片描述
这是一个花的数据集,前四列为花的特征,第五列为花名(种类一共有两种:versicolor和setosa)我们取第一列和第三列为x,第五列为y

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> y = df.iloc[0:100, 4].values
>>>> y = np.where(y == 'Iris-setosa', -1, 1)
>>> X = df.iloc[0:100, [0, 2]].values
>>> plt.scatter(X[:50, 0], X[:50, 1],
... color='red', marker='o', label='setosa')
>>> plt.scatter(X[50:100, 0], X[50:100, 1],
... color='blue', marker='x', label='versicolor')
>>> plt.xlabel('petal length')
>>> plt.ylabel('sepal length')
>>> plt.legend(loc='upper left')
>>> plt.show()

这里写图片描述

建模

先把Perceptron class 保存为Perceptron.py文件,然后在命令行里from Perceptron import Perceptron. 如果Perceptron.py里面有bug, 改完无法重新加载最新版本,所以最简单粗暴的办法就是讲最新修订版的另存为新的文件名再import一遍。

>>> ppn = Perceptron(eta=0.1, n_iter=10)
>>> ppn.fit(X, y)
>>> plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')
>>> plt.xlabel('Epochs')
>>> plt.ylabel('Number of misclassifications')
>>> plt.show()

这里写图片描述

其他材料

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值