一、前期
- 线性分类
所谓线性分类,就是透过特征的线性组合来作出分类决策。对象的特征通常描述为特征值,在向量空间中则是特征向量。如果两类数据可以通过一个线性平面划分,则其分类属于线性分类问题。
- 更改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()
lr.fit(x, y.ravel())
通过索引输出x的前两个元素:
N, M = 500, 500
x1_min, x1_max = x[:, 0].min(), x[:, 0].max()
x2_min, x2_max = x[:, 1].min(), x[:, 1].max()
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))
用新的数据集,输出分类模型准确率:
三、参考