其他阅读渠道:
人大经济论坛微信公号
知乎
许许多多的人都非常容易爱上Python这门语言。自从1991年诞生以来,Python现在已经成为最受欢迎的动态编程语言之一,尤其进入21世纪以来,Python在行业应用和学术研究中进行科学计算的势头也越来越迅猛。
——《Python for Data Analysis》(Wes Mckinney)
Python不仅在编程方面有强大的实力,而且由于不断改进的第三方库,Python在数据处理方面也越来越突出;近年来,非常火爆的机器学习(Machine Learning)以及前沿的自然语言处理(Natural Language Processing)也选择Python作为基础工具。所以要想在数据科学领域有所进步的话,了解学习Python看来还是有所必要的。
本文通过简单案例,分享Python在数据处理方面的实际应用,属于基础学习范畴,希望刚刚接触Python学习的新手们能通过应用去解决实际问题从而巩固掌握Python操作,在这里与大家相互学习,也希望大神们轻拍:)
Without further ado,lets get started!
#进入正题#
本文使用Python2.7版本,操作在集成开发坏境Spyder中进行;选择的数据集,是大名鼎鼎的鸢尾花数据集iris.csv,数据集网上公开请自行下载!
1. 数据集截图如下图1:
该数据集包含数据有150行*5列。前4列分别是:花萼的长度、宽度,花瓣的长度、宽度;最后一列是花的分类,总共分3类。
图1.iris数据集截图
2. 读入数据,代码如下:
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
- from sklearn import * #机器学习库
- np.random.seed(123) #设置随机数种子
- iris=pd.read_csv("C:\\Users\\Administrator\\Desktop\\iris.csv",header=False)
- #操作请注意:输入文件实际路径
- print iris.shape #输出数据维度
- print iris.head() #查看前5行
输出结果如下:
- import numpy as np
- import pandas as pd
- import matplotlib.pyplot as plt
- from sklearn import * #机器学习库
- np.random.seed(123) #设置随机数种子
- iris=pd.read_csv("C:\\Users\\Administrator\\Desktop\\iris.csv",header=False)
- #操作请注意:输入文件实际路径
- print iris.shape #输出数据维度
- print iris.head() #查看前5行
- (150, 5)
- SepalLength SepalWidth PetalLength PetalWidth Name
- 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
Python通过pandas库,读入数据,注意读取时文件路径的填写,需用“\\”或者“/”符号。同时,Python面向对象编程,shape及head函数建立在iris数据框对象之上,这与R语言不同,R语言更加“函数化”,dim及head等函数都是内置函数。
3. 描述性统计,代码如下:
- print iris.describe().T #描述性统计
输出结果如下:
- print iris.describe().T #描述性统计
- count mean std min 25% 50% 75% max
- SepalLength 150 5.843333 0.828066 4.3 5.1 5.80 6.4 7.9
- SepalWidth 150 3.054000 0.433594 2.0 2.8 3.00 3.3 4.4
- PetalLength 150 3.758667 1.764420 1.0 1.6 4.35 5.1 6.9
- PetalWidth 150 1.198667 0.763161 0.1 0.3 1.30 1.8 2.5
从输出结果中可以看到每列数据的平均值等统计数值,较简单不多说。
4. 聚类分析,代码如下:
- irisK3=cluster.KMeans(n_clusters=3,random_state=1) #分为3类
- irisFeatures=iris.ix[:,1:4] #去掉Name列
- #print irisFeatures.head()
- irisK3.fit(irisFeatures)
- print irisK3.labels_ #输出聚类结果
输出结果如下:
- irisK3=cluster.KMeans(n_clusters=3,random_state=1) #分为3类
- irisFeatures=iris.ix[:,1:4] #去掉Name列
- #print irisFeatures.head()
- irisK3.fit(irisFeatures)
- print irisK3.labels_ #输出聚类结果
- [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
- 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 2 2 2 0 2 2 2 2
- 2 2 2 2 2 2 2 2 0 2 2 2 0 2 2 0 2 2 2 2 2 2 2 2 2 2 2 0 2 2 2 2 2 2 2 2 2
- 2 2]
在Python中利用sklearn库中的cluster.Kmeans对irisFeatures进行聚类分析,并输出聚类结果。
5.决策树模型,代码如下:
- target=iris["Name"] #目标变量
- data=iris.ix[:,1:4] #自变量
- train_data,test_data,train_target,test_target=cross_validation.train_test_split(data,
- target,test_size=0.24,random_state=0) #分成训练集、测试集(占0.24)
- clf=tree.DecisionTreeClassifier(criterion='gini', max_depth=6,
- min_samples_split=5) #CART算法
- clf_fit=clf.fit(train_data, train_target) #开始fit
- #print clf_fit
- train_est=clf.predict(train_data) #预测训练集
- test_est=clf.predict(test_data) #预测测试集
- sum=0
- for i in range(36):
- if test_est[i]==test_target[i]:
- sum=sum+1
- print 'test_accuracy=',"%.2f%%"%(sum*1.0/36*100) #测试集预测正确率
- sum=0
- for i in range(114):
- if train_est[i]==train_target[i]:
- sum=sum+1
- print 'tarin_accuracy=',"%.2f%%"%(sum*1.0/114*100) #训练集预测正确率
输出结果:
- target=iris["Name"] #目标变量
- data=iris.ix[:,1:4] #自变量
- train_data,test_data,train_target,test_target=cross_validation.train_test_split(data,
- target,test_size=0.24,random_state=0) #分成训练集、测试集(占0.24)
- clf=tree.DecisionTreeClassifier(criterion='gini', max_depth=6,
- min_samples_split=5) #CART算法
- clf_fit=clf.fit(train_data, train_target) #开始fit
- #print clf_fit
- train_est=clf.predict(train_data) #预测训练集
- test_est=clf.predict(test_data) #预测测试集
- sum=0
- for i in range(36):
- if test_est[i]==test_target[i]:
- sum=sum+1
- print 'test_accuracy=',"%.2f%%"%(sum*1.0/36*100) #测试集预测正确率
- sum=0
- for i in range(114):
- if train_est[i]==train_target[i]:
- sum=sum+1
- print 'tarin_accuracy=',"%.2f%%"%(sum*1.0/114*100) #训练集预测正确率
- test_accuracy= 97.22%
- tarin_accuracy= 98.25%
利用CART算法对iris数据集建立模型,并预测结果,同时输出训练集测试集的预测正确率。相关说明及代码含义均在代码中已注释。
最后:以上仅为小例子,实际问题要比这个复杂的多:数据清洗、模型选择、调参等等!因为网上教程给出完整数据、代码及结果的资料不多,所以把自己的浅薄经验分享给大家!