一、学习任务
熟悉Jupyter环境下的python编程,在Jupyter下完成一个鸢尾花数据集的线性多分类、可视化显示与测试精度实验。
二、学习内容
1.LogisticRegression(逻辑回归)
LogisticRegression回归模型在Sklearn.linear_model子类下,调用sklearn逻辑回归算法步骤比较简单,即:
(1) 导入模型。调用逻辑回归LogisticRegression()函数。
(2) fit()训练。调用fit(x,y)的方法来训练模型,其中x为数据的属性,y为所属类型。
(3) predict()预测。利用训练得到的模型对数据集进行预测,返回预测结果。
代码如下:
from sklearn.linear_model import LogisticRegression #导入逻辑回归模型
clf = LogisticRegression()
print clf
clf.fit(train_feature,label)
predict['label'] = clf.predict(predict_feature)
2.实现线性多分类
2.1.萼片的长宽作为特征进行分类
2.1.1.导入相关包
import numpy as np
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import datasets
from sklearn import preprocessing
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
2.1.2.获取数据并处理
# 获取数据集
iris=datasets.load_iris()
#每行的数据,一共四列,每一列映射为feature_names中对应的值
X=iris.data
print(X)
#每行数据对应的分类结果值(也就是每行数据的label值),取值为[0,1,2]
Y=iris.target
print(Y)
#归一化处理
X = StandardScaler().fit_transform(X)
print(X)
lr = LogisticRegression() # Logistic回归模型
lr.fit(X, Y) # 根据数据[x,y],计算回归参数
2.1.3.绘制图像
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.show()
图像如下:

2.1.4.模型预测
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))
2.1.5.预测结果

2.2.取花瓣的长宽作为特征进行分类
步骤同上 特征值:X=X[:,2:]
图像绘制如下:

预测结果如下:

本文通过Jupyter环境,使用Python的Scikit-Learn库实现了鸢尾花数据集的线性多分类,详细介绍了如何运用LogisticRegression进行训练和预测。首先,对数据进行预处理,包括数据加载、归一化处理。接着,以萼片的长宽作为特征,训练逻辑回归模型,并绘制二维决策边界。最后,展示了模型的预测结果及精度评估,整个过程清晰易懂。
4114

被折叠的 条评论
为什么被折叠?



