【Python机器学习时间指南】一、Python机器学习的生态系统
本文主要記錄《Python機器學習時間指南》第一章中1.2Python庫和功能中的內容。學習機器學習的工作流程。
一、數據的獲取和檢查
?
requests獲取數據
pandans處理數據
1 import os 2 import pandas as pd 3 import requests 4 5 PATH = r'E:/Python Machine Learning Blueprints/Chap1/1.2/' 6 r = requests.get('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data') 7 with open(PATH + 'iris.data', 'w') as f: 8 f.write(r.text) 9 os.chdir(PATH) 10 df = pd.read_csv(PATH + 'iris.data', names=['sepal length','sepal width','petal length','petal width','class']) 11 df.head()注意:1、requests庫為訪問數據的API交互借口,?pandas是數據分析工具,兩者可以專門拿出來后續研究
? ? ? ? ? ?2、read_csv后的路徑名不能含有中文,否則會報OSError: Initializing from file failed。
上述程序運行結果:
sepal length sepal width petal length petal width class
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
5 5.4 3.9 1.7 0.4 Iris-setosa
6 4.6 3.4 1.4 0.3 Iris-setosa
7 5.0 3.4 1.5 0.2 Iris-setosa...
書中對于df的處理中值得注意的操作:
(1)過濾:
df[(df['class'] == 'Iris-setosa')&(df['petal width']>2.2)]
sepal length sepal width petal length petal width class
100 6.3 3.3 6.0 2.5 Iris-virginica
109 7.2 3.6 6.1 2.5 Iris-virginica
114 5.8 2.8 5.1 2.4 Iris-virginica
115 6.4 3.2 5.3 2.3 Iris-virginica
118 7.7 2.6 6.9 2.3 Iris-virginica
120 6.9 3.2 5.7 2.3 Iris-virginica
135 7.7 3.0 6.1 2.3 Iris-virginica
136 6.3 3.4 5.6 2.4 Iris-virginica
140 6.7 3.1 5.6 2.4 Iris-virginica
141 6.9 3.1 5.1 2.3 Iris-virginica
143 6.8 3.2 5.9 2.3 Iris-virginica
144 6.7 3.3 5.7 2.5 Iris-virginica
145 6.7 3.0 5.2 2.3 Iris-virginica
148 6.2 3.4 5.4 2.3 Iris-virginica
(2)過濾出的數據重新保存并重置索引
virginicadf = df[(df['class'] == 'Iris-virginica')&(df['petal width']>2.2)].reset_index(drop=True)
(3)獲得各列統計信息
df.describe()
(4)每行-列相關系數
df.corr()
matplotlib繪制數據
(1)條形圖(hist)
1 import matplotlib.pyplot as plt 2 plt.style.use('ggplot') 3 #%matplotlib inline 4 import numpy as np 5 6 fig,ax = plt.subplots(figsize=(6,4)) 7 ax.hist(df['petal width'], color='black') 8 ax.set_ylabel('Count',fontsize=12) 9 ax.set_xlabel('Width',fontsize=12) 10 plt.title('Iris Petal Width',fontsize=14, y=1.01) 11 plt.show()?
注意:%matplotlib inline為ipython中語句,先暫時封掉;figsize=(6,4)不要漏掉=。為了顯示,在最后加了show()函數
(2)散點圖(scatter)
1 fig,ax = plt.subplots(figsize=(6,6)) 2 ax.scatter(df['petal width'],df['petal length'], color='green') 3 ax.set_ylabel('Petal width',fontsize=12) 4 ax.set_xlabel('petal length',fontsize=12) 5 plt.title('Petal Scatterplot') 6 plt.show()?
(3)直接繪制折線圖(plot)
1 fig,ax = plt.subplots(figsize=(6,6)) 2 ax.scatter(df['petal width'],df['petal length'], color='green') 3 ax.set_ylabel('Petal width',fontsize=12) 4 ax.set_xlabel('petal length',fontsize=12) 5 plt.title('Petal Scatterplot') 6 plt.show()?
(4)堆積條形圖
1 fig,ax = plt.subplots(figsize=(6,6)) 2 bar_width = .8 3 labels = [x for x in df.columns if 'length' in x or 'width' in x] 4 ver_y = [df[df['class']=='Iris-versicolor'][x].mean() for x in labels] 5 vir_y = [df[df['class']=='Iris-virginica'][x].mean() for x in labels] 6 set_y = [df[df['class']=='Iris-setosa'][x].mean() for x in labels] 7 x = np.arange(len(labels)) 8 ax.bar(x,vir_y,bar_width,bottom=set_y,color='darkgrey') 9 ax.bar(x,set_y,bar_width,bottom=ver_y,color='white') 10 ax.bar(x,ver_y,bar_width,color='black') 11 ax.set_xticks(x+(bar_width/2)) 12 ax.set_xticklabels(labels,rotation=-70,fontsize=12) 13 ax.set_title('Mean Feature Measurement By Class',y=1.01) 14 ax.legend(['Virginica','Setosa','Versicolor'])?
注意:8-10行的代碼是按照三種類型從高到低排的,如果調換了順序結果錯誤。
Seaborn庫統計可視化
利用Seaborn庫可以簡單獲取數據的相關性和特征。
二、準備
1、Map
df['class'] = df['class'].map({'Iris-setosa':'SET','Iris-virginica':'VIR','Iris-versicolor':'VER'})
sepal length sepal width petal length petal width class
0 5.1 3.5 1.4 0.2 SET
1 4.9 3.0 1.4 0.2 SET
2 4.7 3.2 1.3 0.2 SET
3 4.6 3.1 1.5 0.2 SET
4 5.0 3.6 1.4 0.2 SET
5 5.4 3.9 1.7 0.4 SET
6 4.6 3.4 1.4 0.3 SET
?2、Apply對行或列操作
應用在某一列:df['width petal'] = df['petal width'].apply(lambda v: 1 if v >=1.3 else 0)
在df中添加一列width petal ?如果petal width超過1.3則為1,否則為0。注意lambda v是df['petal width']的返回值
應用在數據框:df['width area']=df.apply[lambda r: r['petal length'] * r['petal width'], axis=1]
注:axis=1表示對行運用函數,axis=0表示對列應用函數。所以上面的lambda r返回的是每一行
3、ApplyMap對所有單元執行操作
df.applymap(lambda v: np.log(v) if isinstance(v,float) else v)
4、Groupby 基于某些選擇的列別對數據進行分組
df.groupby('class').mean()
?
數據按class分類并分別給出平均值
? ? ? ? ? ? ? sepal length sepal width petal length petal width
class
Iris-setosa 5.006 3.418 1.464 0.244
Iris-versicolor 5.936 2.770 4.260 1.326
Iris-virginica 6.588 2.974 5.552 2.026
df.groupby('class').describe()
數據按class分裂并分別給出描述統計信息
petal length \
count mean std min 25% 50% 75% max
class
Iris-setosa 50.0 1.464 0.173511 1.0 1.4 1.50 1.575 1.9
Iris-versicolor 50.0 4.260 0.469911 3.0 4.0 4.35 4.600 5.1
Iris-virginica 50.0 5.552 0.551895 4.5 5.1 5.55 5.875 6.9
petal width ... sepal length sepal width \
count mean ... 75% max count mean
class ...
Iris-setosa 50.0 0.244 ... 5.2 5.8 50.0 3.418
Iris-versicolor 50.0 1.326 ... 6.3 7.0 50.0 2.770
Iris-virginica 50.0 2.026 ... 6.9 7.9 50.0 2.974
std min 25% 50% 75% max
class
Iris-setosa 0.381024 2.3 3.125 3.4 3.675 4.4
Iris-versicolor 0.313798 2.0 2.525 2.8 3.000 3.4
Iris-virginica 0.322497 2.2 2.800 3.0 3.175 3.8
?
df.groupby('class')['petal width'].agg({'delta':lambda x:x.max()-x.min(), 'max':np.max, 'min':np.min})
delta max min
class
Iris-setosa 0.5 0.6 0.1
Iris-versicolor 0.8 1.8 1.0
Iris-virginica 1.1 2.5 1.4
三、建模和評估
這里只是簡單運用兩個函數,詳細的內容見后面的內容
注:本章涉及到的可以詳細了解的庫:
requests、pandans、matplotlib、seaborn、statsmodels、scikit-learn
?
轉載于:https://www.cnblogs.com/daixianqiang414/p/7353973.html
總結
以上是生活随笔為你收集整理的【Python机器学习时间指南】一、Python机器学习的生态系统的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于对象、构造函数、原型、原型链、继承
- 下一篇: python之发送HTML内容的邮件