生信机器学习入门3 - Scikit-Learn训练机器学习分类感知器

1. 在线读取iris数据集

import os
import pandas as pd

# 下载
try:
    s = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
    print('From URL:', s)
    df = pd.read_csv(s,header=None,encoding='utf-8')
    
except HTTPError:
    s = 'iris.data'
    # 读取.data文件,不读取列名
    df = pd.read_csv(s,header=None, encoding='utf-8')
    
df.tail()

2. 加载 Iris 数据集

从 scikit-learn 加载 Iris 数据集,第三列代表花瓣的长度,第四列代表花瓣的宽度。物种分类已经转换为整数标签,其中0 = Iris-Setosa,1 = Iris-Versicolor,2 = Iris-Virginia

# jupyter
%matplotlib inline
from sklearn import datasets
import numpy as np

iris = datasets.load_iris()
# 提取dataframe的第3列和第4列数据
X = iris.data[:, [2, 3]]
# 分类标签
y = iris.target

# 打印分类标签
print('Class labels:', np.unique(y))
# Class labels: [0 1 2]

3. 划分 Iris 数据集

将70%数据划分为 的训练集和30% 为测试集。

from sklearn.model_selection import train_test_split
# X_train, y_train为训练集数据和标签
# X_test, y_test为测试集数据和标签
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=1, stratify=y)

# 打印各标签的数据包含的数据数量
print('Labels counts in y:', np.bincount(y))
print('Labels counts in y_train:', np.bincount(y_train))
print('Labels counts in y_test:', np.bincount(y_test))
# Labels counts in y: [50 50 50]
# Labels counts in y_train: [35 35 35]
# Labels counts in y_test: [15 15 15]

4. 标准化特征

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
sc.fit(X_train)
# 标准化训练数据X_train_std , X_test_std 
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

5. 通过scikit-learn训练感知器

学习速率 (learning rate): 在训练模型时用于梯度下降的一个变量。在每次迭代期间,梯度下降法都会将学习速率与梯度相乘,得出的乘积称为梯度步长,设置数据在在0-1之间

from sklearn.linear_model import Perceptron

# eta0为学习率
# random_state随机生成器加权数值
ppn = Perceptron(eta0=0.1, random_state=1)
ppn.fit(X_train_std, y_train)
# Perceptron(eta0=0.1, random_state=1)

# 打印测试数据集分类错误数量
y_pred = ppn.predict(X_test_std)
print('Misclassified examples: %d' % (y_test != y_pred).sum())
# Misclassified examples: 1

# 获取感知器准确度
from sklearn.metrics import accuracy_score
print('Accuracy: %.3f' % accuracy_score(y_test, y_pred))
# Accuracy: 0.978

print('Accuracy: %.3f' % ppn.score(X_test_std, y_test))
# Accuracy: 0.978

6. 训练感知器模型

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
from distutils.version import LooseVersion

def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):

    # 绘图图形和颜色生成
    markers = ('o', 's', '^', '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))
    lab = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    lab = lab.reshape(xx1.shape)
    plt.contourf(xx1, xx2, lab, 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=f'Class {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()

训练的感知器预测标签结果

从下图可以看出,对于class 1和class2 标签,有个别样本分类错误,无颜色的黑色圈为测试数据集样本。预测结果

机器学习文章

生信机器学习入门1 - 数据预处理与线性回归(Linear regression)预测

生信机器学习入门2 - 机器学习基本概念

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生信与基因组学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值