基于鸢尾花(iris,sklearn中自带的数据)数据集的逻辑回归分类实践
实践要求:
导入基础的函数库包括:numpy(Python进行科学计算的基础软件包),
pandas(pandas是一种快速,强大,灵活且易于使用的开源数据分析和处理工具),
matplotlib和seaborn绘图。
解题步骤:
Step1:库函数导入
## 基础函数库
import numpy as np
import pandas as pd
## 绘图函数库
import matplotlib.pyplot as plt
import seaborn as sns
Step2:数据读取/载入
## 我们利用 sklearn 中自带的 iris 数据作为数据载入,并利用Pandas转化为DataFrame格式
from sklearn.datasets import load_iris
data = load_iris() #得到数据特征
iris_target = data.target #得到数据对应的标签
iris_features = pd.DataFrame(data=data.data, columns=data.feature_names) #利用Pandas转化为DataFrame格式
ps.一开始我也不知道这个load_iris里面有啥,就ctrl进去看看
return Bunch(
data=data,#所需数据
target=target,#标签
frame=frame,
target_names=target_names,#标签名
DESCR=fdescr,
feature_names=feature_names,#特征名
filename=data_file_name,
data_module=DATA_MODULE,
)
Step3:数据信息简单查看
## 利用.info()查看数据的整体信息
iris_features.info()
## 进行简单的数据查看,我们可以利用 .head() 头部.tail()尾部
print(iris_features.head()) #return self.iloc[:n] n默认是5
print(iris_features.tail())#默认查看前五/后五个
## 其对应的类别标签为,其中0,1,2分别代表'setosa', 'versicolor', 'virginica'三种不同花的类别。
print(iris_target) # 一开始我以为是运行iris_target就会输出标签array,但是这只是代表了array,要想在终端看到,还得print。
## 利用value_counts函数查看每个类别数量
pd.Series(iris_target).value_counts() '''value_counts()函数return(self,sort=sort,ascending=ascending,normalize=normalize,bins=bins,dropna=dropna, )'''
'''return describe_ndframe(
obj=self,
include=include,
exclude=exclude,
datetime_is_numeric=datetime_is_numeric,
percentiles=percentiles,
)'''
>>>Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 sepal length (cm) 150 non-null float64
1 sepal width (cm) 150 non-null float64
2 petal length (cm) 150 non-null float64
3 petal width (cm) 150 non-null float64
dtypes: float64(4)
memory usage: 4.8 KB
None
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
145 6.7 3.0 5.2 2.3
146 6.3 2.5 5.0 1.9
147 6.5 3.0 5.2 2.0
148 6.2 3.4 5.4 2.3
149 5.9 3.0 5.1 1.8
Step4:可视化描述
sns.pairplot(data=iris_all,diag_kind='hist', hue= 'target') # pairplot用来进行数据分析,画两两特征图。常用参数介绍:data:必不可少的数据 hue: 用一个特征来显示图像上的颜色,类似于打标签 marker: 每个label的显示图像变动,有的是三角,有的是原点 vars:只留几个特征两两比较,diag_kind--矩阵 hist直方图 kde核密度曲线
plt.show() # plt.show():显示所有的 figure(不管是阻塞模式的还是交互模式的)。若一个 figure 下一个 plt.show(),则只有关闭一个 figure,才会出现下一个 figure。若最后设置 plt.show(),则会显示设置的所有 figure。简单来说,看完一张图才能看下一张
for col in iris_features.columns:#四个特征
sns.boxplot(x='target', y=col, saturation=0.5,palette='pastel', data=iris_all)
plt.title(col)# 图表标题
plt.show()
# 选取其前三个特征绘制三维散点图
fig = plt.figure(figsize=(10,