《Python数据分析与挖掘实战》第五章案例代码总结与修改分析

第五章案例代码总结与修改分析

【有问题或错误,请私信我将及时改正;借鉴文章标明出处,谢谢】

每个案例代码全部为书中源代码,出现错误按照每个案例下面给出的代码错误,原因,及怎样修改进行修改即可解决每个案例错误

5-1

import pandas as pd
filename = 'F:/大二下合集/Python数据分析与挖掘/bankloan.xls'
data = pd.read_excel(filename)
x = data.iloc[:,:8].as_matrix()
y = data.iloc[:,8].as_matrix()
from sklearn.linear_model import LogisticRegression as LR
from sklearn.linear_model import RandomizedLogisticRegression as RLR
rlr = RLR() #建立随机逻辑回归模型,筛选变量
rlr.fit(x, y) #训练模型
rlr.get_support() #获取特征筛选结果,也可以通过.scores_方法获取各个特征的分数
print(u'通过随机逻辑回归模型筛选特征结束。')
print(u'有效特征为:%s' % ','.join(data.columns[rlr.get_support(8)]))
x = data[data.columns[rlr.get_support()]].as_matrix() #筛选好特征
lr = LR() #建立逻辑回归模型
lr.fit(x, y) #用筛选后的特征数据来训练模型
print(u'逻辑回归模型训练结束。')
print(u'模型的平均正确率为:%s' % lr.score(x, y)) #给出模型的平均正确率,本例为81.4%

报错1:

AttributeError: 'DataFrame' object has no attribute 'as_matrix'

报错原因:属性错误:“DataFrame”对象没有属性“reshape”

解决方法:“DataFrame”对象没有,但是DataFrame.values有该方法
将.as_matrix()改为.values

第一次改为了.values() 出错:

TypeError: 'numpy.ndarray' object is not callable

报错原因:.values,它是dataframe类对象的一个属性,不是方法

第二次改为.values没报错了

报错2:

ImportError: cannot import name 'RandomizedLogisticRegression'

问题语句:

from sklearn.linear_model import RandomizedLogisticRegression

查找原因:
一个博客中写道了这个问题RandomizedLogisticRegression ImportError解决办法

查得sklearn(版本0.21.3)的linear_model文件夹下面已经没有randomized_l1.py文件,而RandomizedLogisticRegression就在该文件内。RandomizedLogisticRegression已经被移出sklearn包,移到了 scikit-learn-contrib/stability-selection中,提取的stability-selection安装过程(后两步需要cd到对应文件的路径下面运行):

git clone https://github.com/scikit-learn-contrib/stability-selection.git
pip install -r requirements.txt
python setup.py install

在执行第三个命令有报错:

error: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: 'd:\\python\\miniconda3_py3.6_x64_jb51\\lib\\site-packages\\stability_selection-0.0.1-py3.6.egg'

这个问题找到你的这个目录下的这个文件“tability_selection-0.0.1-py3.6.egg”发现他是一个压缩包,把他解压后删除这个压缩包,一般解压后就没有后缀了即文件名字就是:“tability_selection-0.0.1-py3.6”给他修改名字最后添加上”.egg”,再次运行没有错误了

安装后运行将刚报错的代码改为下面代码:

from stability_selection.randomized_lasso import RandomizedLogisticRegression

没有报错,import正常。

确实按照这个博客写完没报错出现了第三个问题

报错3:

AttributeError: 'RandomizedLogisticRegression' object has no attribute 'get_support'

解决问题到了这里我开始了迷茫,经过几天的百度与版本更替实验还是未能成功解决。那么换个思路,想把例子整体理解吃透,之后慢慢了解了这个各个版本不管是sklearn或是panda、tensorflow等等,它们在升级之后做了什么改动,那么再回过头来看这个例子错误就容易解决了。所以5-1这个例子暂时没有得到解决,等我解决会进行添加解决的步骤。

5-2

#-*- coding: utf-8 -*-
import pandas as pd
inputfile = 'F:/大二下合集/Python数据分析与挖掘/sales_data.xls'
data = pd.read_excel(inputfile, index_col=u'序号')
data[data == u'好'] = 1
data[data == u'是'] = 1
data[data == u'高'] = 1
data[data != 1] = -1
x = data.iloc[:, :3].as_matrix().astype(int)
y = data.iloc[:, 3].as_matrix().astype(int)
from sklearn.tree import DecisionTreeClassifier as DTC
dtc = DTC(criterion='entropy')
dtc.fit(x, y)
from sklearn.tree import export_graphviz
from sklearn.externals.six import StringIO
with open("tree.dot", 'w') as f:
f = export_graphviz(dtc, feature_names=x.columns, out_file=f)

代码报错:

在这里插入图片描述

第一个错误原因:

x = data.iloc[:, :3].as_matrix().astype(int)
y = data.iloc[:, 3].as_matrix().astype(int)

修改为:

x = data.iloc[:, :3].values.astype(int)
y = data.iloc[:, 3].values.astype(int)

第二个错误原因:

f = export_graphviz(dtc, feature_names=x.columns, out_file=f)

修改为:
应该在with open(“tree.dot”, ‘w’) as f:这行之前添加下面这句

x = pd.DataFrame(x)

在目录下会有tree.dot文本文件
我们需要下载Graphviz(跨平台的、基于命令行的绘图工具),然后在命令行进行编译

在这里插入图片描述
在这里插入图片描述

5-3

#-*- coding: utf-8 -*-
#使用神经网络算法预测销量高低
import pandas as pd
#参数初始化
inputfile = 'F:/大二下合集/Python数据分析与挖掘/sales_data.xls'
data = pd.read_excel(inputfile, index_col = u'序号') #导入数据
#数据是类别标签,要将它转换为数据
#用1来表示“好”、“是”、“高”这三个属性,用0来表示“坏”、“否”、“低”
data[data == u'好'] = 1
data[data == u'是'] = 1
data[data == u'高'] = 1
data[data != 1] = 0
x = data.iloc[:,:3].as_matrix().astype(int)
y = data.iloc[:,3].as_matrix().astype(int)
from keras.models import Sequential
from keras.layers.core import Dense, Activation
model = Sequential() #建立模型
model.add(Dense(input_dim = 3, output_dim = 10))
model.add(Activation('relu')) #用relu函数作为激活函数,能够大幅提供准确度
model.add(Dense(input_dim = 10, output_dim = 1))
model.add(Activation('sigmoid')) #由于是0-1输出,用sigmoid函数作为激活函数
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', class_mode = 'binary')
#编译模型。由于我们做的是二元分类,所以我们指定损失函数为binary_crossentropy,以及模式为binary
#另外常见的损失函数还有mean_squared_error、categorical_crossentropy等,请阅读帮助文件。
#求解方法我们指定用adam,还有sgd、rmsprop等可选
model.fit(x, y, nb_epoch = 1000, batch_size = 10) #训练模型,学习一千次
yp = model.predict_classes(x).reshape(len(y)) #分类预测
from cm_plot import * #导入自行编写的混淆矩阵可视化函数
cm_plot(y,yp).show() #显示混淆矩阵可视化结果

代码错误:

在这里插入图片描述

原因:

model.compile(loss = 'binary_crossentropy', optimizer = 'adam', class_mode = 'binary')

解决:
删除这行中的参数class_mode=“binary”
即:

model.compile(loss = 'binary_crossentropy', optimizer = 'adam')

之后还有一个错误这里的错误图没了,听我口述即可,他会报错找不到cm_plot

原因:
cm_plot是个自定义函数,你还没有这个函数

解决:
添加自定义cm_plot函数,函数内容如下:

#-*- coding: utf-8 -*-  
def cm_plot(y, yp):
  from sklearn.metrics import confusion_matrix #导入混淆矩阵函数  
  cm = confusion_matrix(y, yp) #混淆矩阵  
  import matplotlib.pyplot as plt #导入作图库  
  plt.matshow(cm, cmap=plt.cm.Greens) #画混淆矩阵图,配色风格使用cm.Greens,更多风格请参考官网。  
  plt.colorbar() #颜色标签  
  for x in range(len(cm)): #数据标签  
    for y in range(len(cm)):
     plt.annotate(cm[x,y], xy=(x, y), horizontalalignment='center', verticalalignment='center')
  plt.ylabel('True label') #坐标轴标签  
  plt.xlabel('Predicted label') #坐标轴标签  
  return plt

将自定义好的函数放入到你python环境下site-packages中,如下图

在这里插入图片描述

5-4

#-*- coding: utf-8 -*-
#使用K-Means算法聚类消费行为特征数据
import pandas as pd
#参数初始化
inputfile = 'F:/大二下合集/Python数据分析与挖掘/consumption_data.xls' #销量及其他属性数据
outputfile = 'F:/大二下合集/Python数据分析与挖掘/data_type.xls' #保存结果的文件名
k = 3 #聚类的类别
iteration = 500 #聚类最大循环次数
data = pd.read_excel(inputfile, index_col = 'Id') #读取数据
data_zs = 1.0*(data - data.mean())/data.std() #数据标准化
from sklearn.cluster import KMeans
model = KMeans(n_clusters = k, n_jobs = 4, max_iter = iteration) #分为k类,并发数4
model.fit(data_zs) #开始聚类
#简单打印结果
r1 = pd.Series(model.labels_).value_counts() #统计各个类别的数目
r2 = pd.DataFrame(model.cluster_centers_) #找出聚类中心
r = pd.concat([r2, r1], axis = 1) #横向连接(0是纵向),得到聚类中心对应的类别下的数目
r.columns = list(data.columns) + [u'类别数目'] #重命名表头
print(r)
#详细输出原始数据及其类别
r = pd.concat([data, pd.Series(model.labels_, index = data.index)], axis = 1)  #详细输出每个样本对应的类别
r.columns = list(data.columns) + [u'聚类类别'] #重命名表头
r.to_excel(outputfile) #保存结果
def density_plot(data): #自定义作图函数
  import matplotlib.pyplot as plt
  plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
  plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
  p = data.plot(kind='kde', linewidth = 2, subplots = True, sharex = False)
  [p[i].set_ylabel(u'密度') for i in range(k)]
  plt.legend()
  return plt
pic_output = 'F:/大二下合集/Python数据分析与挖掘/pd_' #概率密度图文件名前缀
for i in range(k):
  density_plot(data[r[u'聚类类别']==i]).savefig(u'%s%s.png' %(pic_output, i))

运行结果:

在这里插入图片描述

在你所输出的目录下会有图片:

在这里插入图片描述

这个案例代码没问题

5-5

#-*- coding: utf-8 -*-
#接k_means.py
from sklearn.manifold import TSNE
tsne = TSNE()
tsne.fit_transform(data_zs) #进行数据降维
tsne = pd.DataFrame(tsne.embedding_, index = data_zs.index) #转换数据格式
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
#不同类别用不同颜色和样式绘图
d = tsne[r[u'聚类类别'] == 0]
plt.plot(d[0], d[1], 'r.')
d = tsne[r[u'聚类类别'] == 1]
plt.plot(d[0], d[1], 'go')
d = tsne[r[u'聚类类别'] == 2]
plt.plot(d[0], d[1], 'b*')
plt.show()

代码错误:

在这里插入图片描述

原因:
需要与5-4案例结合

解决:
在5-5代码之前添加,如下代码

#-*- coding: utf-8 -*-
#接k_means.py
import pandas as pd
inputfile = 'F:/大二下合集/Python数据分析与挖掘/consumption_data.xls'
outputfile = 'F:/大二下合集/Python数据分析与挖掘/data_type.xls'
k = 3
iteration = 500
data = pd.read_excel(inputfile, index_col = 'Id')
data_zs = 1.0*(data - data.mean())/data.std()
from sklearn.cluster import KMeans
model = KMeans(n_clusters = k, n_jobs = 4, max_iter = iteration)
model.fit(data_zs)
r1 = pd.Series(model.labels_).value_counts()
r2 = pd.DataFrame(model.cluster_centers_)
r = pd.concat([r2, r1], axis = 1)
r.columns = list(data.columns) + [u'类别数目']
print(r)
r = pd.concat([data, pd.Series(model.labels_, index = data.index)], axis = 1)
r.columns = list(data.columns) + [u'聚类类别']
r.to_excel(outputfile)

5-6

import pandas as pd
from apriori import * #导入自行编写的apriori函数
inputfile = 'F:/大二下合集/Python数据分析与挖掘/menu_orders.xls'
outputfile = 'F:/大二下合集/Python数据分析与挖掘/apriori_rules.xls' #结果文件
data = pd.read_excel(inputfile, header = None)
print(u'\n转换原始数据至0-1矩阵...')
ct = lambda x : pd.Series(1, index = x[pd.notnull(x)]) #转换0-1矩阵的过渡函数,非空值转换成‘1’
b = map(ct, data.values) #用map方式执行
data = pd.DataFrame(list(b)).fillna(0) #实现矩阵转换,空值用0填充
print(u'\n转换完毕。')
del b #删除中间变量b,节省内存
support = 0.2 #最小支持度
confidence = 0.5 #最小置信度
ms = '---' #连接符,默认'--',用来区分不同元素,如A--B。需要保证原始表格中不含有该字符
find_rule(data, support, confidence, ms).to_excel(outputfile) #保存结果

代码错误:
这里错误图片没了,我来口述这个错误,就是会报错找不到apriori

原因:
cm_plot是个自定义函数,你还没有这个函数

解决:
添加自定义apriori函数,函数内容如下:

#-*- coding: utf-8 -*-
from __future__ import print_function
import pandas as pd
#自定义连接函数,用于实现L_{k-1}到C_k的连接
def connect_string(x, ms):
  x = list(map(lambda i:sorted(i.split(ms)), x))
  l = len(x[0])
  r = []
  for i in range(len(x)):
    for j in range(i,len(x)):
      if x[i][:l-1] == x[j][:l-1] and x[i][l-1] != x[j][l-1]:
        r.append(x[i][:l-1]+sorted([x[j][l-1],x[i][l-1]]))
  return r
#寻找关联规则的函数
def find_rule(d, support, confidence, ms = u'--'):
  result = pd.DataFrame(index=['support', 'confidence']) #定义输出结果
  support_series = 1.0*d.sum()/len(d) #支持度序列
  column = list(support_series[support_series > support].index) #初步根据支持度筛选
  k = 0
  while len(column) > 1:
    k = k+1
    print(u'\n正在进行第%s次搜索...' %k)
    column = connect_string(column, ms)
    print(u'数目:%s...' %len(column))
    sf = lambda i: d[i].prod(axis=1, numeric_only = True) #新一批支持度的计算函数
    #创建连接数据,这一步耗时、耗内存最严重。当数据集较大时,可以考虑并行运算优化。
    d_2 = pd.DataFrame(list(map(sf,column)), index = [ms.join(i) for i in column]).T
    support_series_2 = 1.0*d_2[[ms.join(i) for i in column]].sum()/len(d) #计算连接后的支持度
    column = list(support_series_2[support_series_2 > support].index) #新一轮支持度筛选
    support_series = support_series.append(support_series_2)
    column2 = []
    for i in column: #遍历可能的推理,如{A,B,C}究竟是A+B-->C还是B+C-->A还是C+A-->B?
      i = i.split(ms)
      for j in range(len(i)):
        column2.append(i[:j]+i[j+1:]+i[j:j+1])
    cofidence_series = pd.Series(index=[ms.join(i) for i in column2]) #定义置信度序列
    for i in column2: #计算置信度序列
      cofidence_series[ms.join(i)] = support_series[ms.join(sorted(i))]/support_series[ms.join(i[:len(i)-1])]
    for i in cofidence_series[cofidence_series > confidence].index: #置信度筛选
      result[i] = 0.0
      result[i]['confidence'] = cofidence_series[i]
      result[i]['support'] = support_series[ms.join(sorted(i.split(ms)))]
  result = result.T.sort_values(['confidence','support'], ascending = False) #结果整理,输出
  print(u'\n结果为:')
  print(result)
  return result

将自定义好的函数放入到你python环境下site-packages中,如下图

在这里插入图片描述

5-7

#-*- coding: utf-8 -*-
#arima时序模型
import pandas as pd
#参数初始化
discfile = 'F:/大二下合集/Python数据分析与挖掘/arima_data.xls'
forecastnum = 5
#读取数据,指定日期列为指标,Pandas自动将“日期”列识别为Datetime格式
data = pd.read_excel(discfile, index_col = u'日期')
#时序图
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
data.plot()
plt.show()
#自相关图
from statsmodels.graphics.tsaplots import plot_acf
plot_acf(data).show()
#平稳性检测
from statsmodels.tsa.stattools import adfuller as ADF
print(u'原始序列的ADF检验结果为:', ADF(data[u'销量']))
#返回值依次为adf、pvalue、usedlag、nobs、critical values、icbest、regresults、resstore
#差分后的结果
D_data = data.diff().dropna()
D_data.columns = [u'销量差分']
D_data.plot() #时序图
plt.show()
plot_acf(D_data).show() #自相关图
from statsmodels.graphics.tsaplots import plot_pacf
plot_pacf(D_data).show() #偏自相关图
print(u'差分序列的ADF检验结果为:', ADF(D_data[u'销量差分'])) #平稳性检测
#白噪声检验
from statsmodels.stats.diagnostic import acorr_ljungbox
print(u'差分序列的白噪声检验结果为:', acorr_ljungbox(D_data, lags=1)) #返回统计量和p值
from statsmodels.tsa.arima_model import ARIMA
data[u'销量'] = data[u'销量'].astype(float)
#定阶
pmax = int(len(D_data)/10) #一般阶数不超过length/10
qmax = int(len(D_data)/10) #一般阶数不超过length/10
bic_matrix = [] #bic矩阵
for p in range(pmax+1):
  tmp = []
  for q in range(qmax+1):
    try: #存在部分报错,所以用try来跳过报错。
      tmp.append(ARIMA(data, (p,1,q)).fit().bic)
    except:
      tmp.append(None)
  bic_matrix.append(tmp)
bic_matrix = pd.DataFrame(bic_matrix) #从中可以找出最小值
p,q = bic_matrix.stack().idxmin() #先用stack展平,然后用idxmin找出最小值位置。
print(u'BIC最小的p值和q值为:%s、%s' %(p,q)) 
model = ARIMA(data, (p,1,q)).fit() #建立ARIMA(0, 1, 1)模型
model.summary2() #给出一份模型报告
model.forecast(5) #作为期5天的预测,返回预测结果、标准误差、置信区间。

代码错误:
没有报错,但是在idea中运行出模型报告、5天的预测,返回预测结果、标准误差、置信区间结果

原因:

model.summary2() #给出一份模型报告
model.forecast(5) #作为期5天的预测,返回预测结果、标准误差、置信区间。

修改为:(即添加print)

print(model.summary2()) #给出一份模型报告
print(model.forecast(5)) #作为期5天的预测,返回预测结果、标准误差、置信区间。

5-8

#-*- coding: utf-8 -*-
#使用K-Means算法聚类消费行为特征数据
import numpy as np
import pandas as pd
#参数初始化
inputfile = 'F:/大二下合集/Python数据分析与挖掘/consumption_data.xls' #销量及其他属性数据
k = 3 #聚类的类别
threshold = 2 #离散点阈值
iteration = 500 #聚类最大循环次数
data = pd.read_excel(inputfile, index_col = 'Id') #读取数据
data_zs = 1.0*(data - data.mean())/data.std() #数据标准化
from sklearn.cluster import KMeans
model = KMeans(n_clusters = k, n_jobs = 4, max_iter = iteration) #分为k类,并发数4
model.fit(data_zs) #开始聚类
#标准化数据及其类别
r = pd.concat([data_zs, pd.Series(model.labels_, index = data.index)], axis = 1)  #每个样本对应的类别
r.columns = list(data.columns) + [u'聚类类别'] #重命名表头
norm = []
for i in range(k): #逐一处理
  norm_tmp = r[['R', 'F', 'M']][r[u'聚类类别'] == i]-model.cluster_centers_[i]
  norm_tmp = norm_tmp.apply(np.linalg.norm, axis = 1) #求出绝对距离
  norm.append(norm_tmp/norm_tmp.median()) #求相对距离并添加
norm = pd.concat(norm) #合并
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
norm[norm <= threshold].plot(style = 'go') #正常点
discrete_points = norm[norm > threshold] #离群点
discrete_points.plot(style = 'ro')
for i in range(len(discrete_points)): #离群点做标记
  id = discrete_points.index[i]
  n = discrete_points.iloc[i]
  plt.annotate('(%s, %0.2f)'%(id, n), xy = (id, n), xytext = (id, n))
plt.xlabel(u'编号')
plt.ylabel(u'相对距离')
plt.show()

这个案例代码没问题

【有问题或错误,请私信我将及时改正;借鉴文章标明出处,谢谢】

  • 12
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fy_1852003327

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值