您好,欢迎来到99网。
搜索
您的当前位置:首页Anaconda中对鸢尾花数据集进行SVM线性分类

Anaconda中对鸢尾花数据集进行SVM线性分类

来源:99网

一、前期

  • 线性分类
    所谓线性分类,就是透过特征的线性组合来作出分类决策。对象的特征通常描述为特征值,在向量空间中则是特征向量。如果两类数据可以通过一个线性平面划分,则其分类属于线性分类问题。
  • 更改Jupyter默认位置

先打开Anaconda的终端,输入命令:

jupyter notebook --generate-config

一般会出现下面这句话:

Overwrite C:\Users\saus\.jupyter\jupyter_notebook_config.py with default config? [y/N]y

然后文件资源管理器夹中找到这个文件并打开,找到下面这句话并修改

# 找到这个,进行修改
## The directory to use for notebooks and kernels.
#  Default: ''
#c.NotebookApp.notebook_dir = ''
修改成下面这样
## The directory to use for notebooks and kernels.
#  Default: ''
c.NotebookApp.notebook_dir = r'E:\xi-teacher\jupyter'

最后找到Jupyter Notebook的程序图标,右键打开它的属性,删除 目标中 末尾的 “%USERPROFILE%/” ,然后保存。

二、练习

import numpy as np
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import preprocessing
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

df = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=0)
x = df.values[:, :-1]
y = df.values[:, -1]
print('x = \n', x)
print('y = \n', y)
le = preprocessing.LabelEncoder()
le.fit(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])
print(le.classes_)
y = le.transform(y)
print('Last Version, y = \n', y)

jupyter会自动运行出结果:
输出数据集里全部的数据

x = x[:, :2] 
print(x)
print(y)
x = StandardScaler().fit_transform(x)
lr = LogisticRegression()   # Logistic回归模型
lr.fit(x, y.ravel())        # 根据数据[x,y],计算回归参数

通过索引输出x的前两个元素:

N, M = 500, 500     # 横纵各采样多少个值
x1_min, x1_max = x[:, 0].min(), x[:, 0].max()   # 第0列的范围
x2_min, x2_max = x[:, 1].min(), x[:, 1].max()   # 第1列的范围
t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, M)
x1, x2 = np.meshgrid(t1, t2)                    # 生成网格采样点
x_test = np.stack((x1.flat, x2.flat), axis=1)   # 测试点

cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
y_hat = lr.predict(x_test)       # 预测值
y_hat = y_hat.reshape(x1.shape)                 # 使之与输入的形状相同
plt.pcolormesh(x1, x2, y_hat, cmap=cm_light)     # 预测值的显示
plt.scatter(x[:, 0], x[:, 1], c=y.ravel(), edgecolors='k', s=50, cmap=cm_dark)    
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.grid()
plt.savefig('2.png')
plt.show()

输出数据集分类图像:

y_hat = lr.predict(x)
y = y.reshape(-1)
result = y_hat == y
print(y_hat)
print(result)
acc = np.mean(result)
print('准确度: %.2f%%' % (100 * acc))

用新的数据集,输出分类模型准确率:

三、参考

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 99spj.com 版权所有 湘ICP备2022005869号-5

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务