【深度之眼七——(2)】Python:Sklearn库

目录

本章导读

鸢尾花数据集

下载数据集

数据集的查看

标签清洗

 标签编码

 数据的标准化(本数据特征比较接近,实际处理过程中未标准化)

 构建训练集和测试集

K近邻算法

 sklearn的实现

 可视化

 朴素贝叶斯算法

 决策树算法

 逻辑回归算法

 支持向量积算法

 集成方法-随机森林

 集成方法-adaboost

  集成方法-梯度提升树GBDT

 大杀器

 知识回顾


本章导读

 

鸢尾花数据集

下载数据集

from sklearn import datasets
import seaborn as sns
iris = sns.load_dataset("iris")

数据集的查看

type(iris)

 

 

 

 具体图片在上一章

通过分析可以知道,花萼的长度和花萼的宽度之间相关性不大,并且不容易分辨,所以我们希望简化问题,筛除这两个作用不大的数据,保留其他的数据,这就需要使用到

标签清洗

iris_simple = iris.drop(["sepal_length","sepal_width"],axis=1)
iris_simple.head()

 

 但是在机器学习中,在训练的过程中要用到这个标签值,但有的情况下会对标签值数据类型有要求,比如要求为数值类型,我们就需要把标签设置为1,2……所以使用

 标签编码

from sklearn.preprocessing import LabelEncoder

encoder = LabelEncoder()
iris_simple["species"] = encoder.fit_transform(iris_simple["species"]) #进行一个学习fit,转换transform的过程,将转换的结果重新赋值给那一列
iris_simple.head()

这3类依次被编码成了0,1,2

 数据的标准化(本数据特征比较接近,实际处理过程中未标准化)

                 x=(x-x̅)/x

from sklearn.preprocessing import StandardScaler
import pandas as pd 

trans = StandardScaler()
_iris_simple = trans.fit_transform(iris_simple[["petal_length","petal_width"]])
_iris_simple = pd.DataFrame(_iris_simple, columns = ["petal_length","petal_width"])
_iris_simple.describe()

 构建训练集和测试集

(暂不考虑验证集)

from sklearn.model_selection import train_test_split

train_set, test_set = train_test_split(iris_simple,test_size= 0.2) #前者为待分割的数据集,后面0.2的含义是将其中20%的数据作为测试test使用
                                                                    #也就是有80%的数据用来进行“学习”
test_set.head()

iris_x_train = train_set[["petal_length","petal_width"]]
iris_x_train.head()

        

iris_y_train = train_set["species".copy()
iris_y_train.head()

iris_x_test = test_set[["petal_length","petal_width"]]
iris_x_test.head()

iris_y_test = test_set["species"].copy()
iris_y_test.head()

K近邻算法

 

 不懂的话自己看第7章的2节第11分钟

 sklearn的实现

from sklearn.neighbors import KNeighborsClassifier

       ·构建分类器对象

clf = KNeighborsClassifier()
clf

         ·训练

clf.fit(iris_x_train, iris_y_train)

        ·预测

res = clf.predict(iris_x_test)
print(res)
print(iris_y_test.values)

         ·翻转

encoder.inverse_transform(res)

         ·评估

accuracy = clf.score(iris_x_test,iris_y_test)
print("预估概率为{:.0%}".format(accuracy))

        ·存储数据

out = iris_x_test.copy()
out["y"] = iris_y_test
out["pre"]= res
out
out.to_csv("irie_pridict.csv")

 

 可视化

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

def draw(clf):
    
#     网格化
    M, N = 500, 500
    x1_min,x2_min = iris_simple[["petal_length","petal_width"]].min(axis=0)
    x1_max,x2_max = iris_simple[["petal_length","petal_width"]].max(axis=0)
    t1 = np.linspace(x1_min,x1_max,M)
    t2 = np.linspace(x2_min,x2_max,N)
    x1,x2 = np.meshgrid(t1,t2)
    print('x1=',x1)   
    print('x2=',x2)
    print('x1.flat=',x1.flat)  
    
#     预测
    x_show = np.stack((x1.flat,x2.flat),axis=1)
    y_predict = clf.predict(x_show)
    #print('x_show=',x_show)
    
#     颜色
    cm_light = mpl.colors.ListedColormap(['#A0FFA0','#FFA0A0','#A0A0FF'])
    cm_dark = mpl.colors.ListedColormap(['g','r','b'])
    
#     绘制预测图
    plt.figure(figsize=(10,6))
    plt.pcolormesh(t1,t2, y_predict.reshape(x1.shape),cmap=cm_light)
 
#     绘制原始数据点
    plt.scatter(iris_simple["petal_length"],iris_simple["petal_width"],label=None,
               c=iris_simple["species"],cmap=cm_dark,marker="o",edgecolor="k")
    plt.xlabel("petal_length")
    plt.ylabel("petal_width")
    
#     绘制图例
    color = ["g","r","b"]
    species = ["setoa","virginica","versicolor"]
    for i in range(3):
        plt.scatter([],[],c=color[i],s=40,label=species[i]) #空点绘制图列
    plt.legend(loc="best")
    plt.title("iris_classfier")

 

给注释举个栗子

 

 

 朴素贝叶斯算法

 

 

 

 

 

 决策树算法

 

 

 逻辑回归算法

 

 

 支持向量积算法

 

 

 集成方法-随机森林

 

 其他的步骤都是一样的

 

 集成方法-adaboost

 

  集成方法-梯度提升树GBDT

 

 

 大杀器

 

 

 知识回顾

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值