python机器学习使用sklearn模块出错,求解答

> 博客详情
摘要: 用sklearn写一个分类的程序。sklearn是一个python实现的基于scipy的机器学习软件包,觉得还不错,比较简单容易上手。
写了一个简单的多类分类程序,给定一个数据集,在其上做10-fold交叉检验,输出loss,以及分类的结果。
最关键的函数是def do_cross_validation(dict_feature_list, y_list, num_features, num_fold, clf)。各个参数的含义是
dict_feature_list是一个python的dict列表,列表中每一个元素代表一个样本,比如一个文档,dict作为&k,v&,k代表特征,v是特征的值。
y_list是样本的标签
num_features是数据集的维度大小
num_fold是几次交叉检验,10则代表10-fold交叉检验
clf是分类算法
做交叉检验时,关键代码是skf = StratifiedKFold(y, n_folds=num_fold, shuffle=False, random_state=None),这个方法将根据类别的分布情况,对数据集做stratified分隔,尽量使得每个fold里的类别分布与原始数据集相同。毕竟,机器学习train出来的model假设做分类时,所面对的数据和训练数据有同样的分布才好。通过一个for循环,for i, (train_index, test_index) in enumerate(skf):将十次交叉检验的数据展开。代码最后用了metrix计算loss,当然可以偷懒直接用classification_report,我这里根据micro、macro、weighted三种方式,计算了下precision,recall和f1-score。
函数def make_2d_matrix_to_dict_lst(matrix)完全是为了测试代码,作用是将一个dense的矩阵,变成dict的列表。
函数def dict_lst_to_coo_sparse_matrix(dict_lst, num_features):是将一个dict的列表,转成sparse matrix,这样可以很大幅度的节约内存,尤其是在做文本分类的时候。
具体用的时候,偷懒用了one-vs-rest的多分类策略,基础算法使用的逻辑回归clf = OneVsRestClassifier(LogisticRegression())
# -*- coding: utf-8 -*-
from sklearn.cross_validation import StratifiedKFold
from sklearn import metrics
import numpy as np
from sklearn.multiclass import OneVsRestClassifier
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
#transfer a python dict list to scipy COO sparse matrix
#dict_lst: [{a:b},{a:b,c:d}], each dict is the feature set of an instance
#num_features: the total number of features in dataset
def dict_lst_to_coo_sparse_matrix(dict_lst, num_features):
from scipy.sparse import coo_matrix
import numpy as np
n_doc = len(dict_lst)
#find non-zero element
row_vec = []
col_vec = []
data_vec = []
for d_index in range(len(dict_lst)):
for k in dict_lst[d_index]:
row_vec.append(d_index)
col_vec.append(k)
data_vec.append(dict_lst[d_index][k])
row_vec = np.array(row_vec)
col_vec = np.array(col_vec)
data_vec = np.array(data_vec)
return coo_matrix((data_vec, (row_vec, col_vec)), shape=(n_doc, num_features))
#transfer a dense 2d matrix to dict lst
def make_2d_matrix_to_dict_lst(matrix):
for row in matrix:
for j in range(len(row)):
if row[j] != 0:
d[j] = row[j]
lst.append(d)
return lst
#base experimental code
def do_cross_validation(dict_feature_list, y_list, num_features, num_fold, clf):
X = dict_feature_list#instance set
y = np.array(y_list)#label set
ids = np.arange(len(X))#instance id set
id2result = {}
loss_lst = []
predicted_lst = []
#make cross validation set
skf = StratifiedKFold(y, n_folds=num_fold, shuffle=False, random_state=None)
for i, (train_index, test_index) in enumerate(skf):
#split dataset into train and test
y_train = y[train_index]
id_train = ids[train_index]
X_train = []
for t in train_index:
X_train.append(X[t])
y_test = y[test_index]
id_test = ids[test_index]
X_test = []
for t in test_index:
X_test.append(X[t])
#make sparse representation
sparse_X_train = dict_lst_to_coo_sparse_matrix(X_train, num_features)
sparse_X_test = dict_lst_to_coo_sparse_matrix(X_test, num_features)
#train a classifier on the training set
clf.fit(sparse_X_train, y_train)
#do prediction on the test set
predicted_labels = clf.predict(sparse_X_test)
#store results for later comparision
for index in range(len(id_test)):
id2result[id_test[index]] = (y_test[index], predicted_labels[index])
#compute loss
macro_pr = metrics.precision_score(y_test, predicted_labels, pos_label=None, average='macro')
macro_re = metrics.recall_score(y_test, predicted_labels, pos_label=None, average='macro')
macro_f1 = metrics.f1_score(y_test, predicted_labels, pos_label=None, average='macro')
micro_pr = metrics.precision_score(y_test, predicted_labels, pos_label=None, average='micro')
micro_re = metrics.recall_score(y_test, predicted_labels, pos_label=None, average='micro')
micro_f1 = metrics.f1_score(y_test, predicted_labels, pos_label=None, average='micro')
weighted_pr = metrics.precision_score(y_test, predicted_labels, pos_label=None, average='weighted')
weighted_re = metrics.recall_score(y_test, predicted_labels, pos_label=None, average='weighted')
weighted_f1 = metrics.f1_score(y_test, predicted_labels, pos_label=None, average='weighted')
loss_lst.append((macro_pr, macro_re, macro_f1, micro_pr, micro_re, micro_f1, weighted_pr, weighted_re, weighted_f1))
return loss_lst, id2result
#load digital recognition dataset
digits = datasets.load_digits()
X = digits.data
y = digits.target
num_features = len(X[0])
#make dict lst features
feature_lst = make_2d_matrix_to_dict_lst(X)
clf = OneVsRestClassifier(LogisticRegression())
loss_lst, id2result = do_cross_validation(feature_lst, y, num_features, 10, clf)
for loss in loss_lst:
print ['%.3f' % r for r in loss]
人打赏支持
码字总数 13599
支付宝支付
微信扫码支付
打赏金额: ¥
已支付成功
打赏金额: ¥
& 开源中国(OSChina.NET) |
开源中国社区(OSChina.net)是工信部
指定的官方社区扫码下载官方APP
Python机器学习应用
人工智能(AI)如何建立呢?通过逻辑推理,还是通过学习模仿?近年来的发展看,机器学习似乎略胜一筹,机器学习建立智能,应用人工智能去解决问题吧!本课程面向各类编程学习者,讲解当下流行的机器学习相关的技术和方法,帮助学习者利用Python语言掌握机器学习算法解决一般问题的基本能力,一窥前沿机器学习算法的奥秘。本课程介绍计算生态中广受欢迎的机器学习算法库,这些算法在工程、信息、管理、经济等学科领域具有极其广泛的应用潜力,被全世界各大科研院所和国际知名公司广泛采用,包括必修内容和选修内容两部分。必修内容包括:(1)理解机器学习,通过介绍机器学习的基本问题(分类、聚类、回归)介绍经典算法;(2)第三方库(,讲解应用机器学习算法快速解决实际问题的方法。选修内容包括:(1)讲解背后的机器学习原理(增强学习);(2)游戏对战实例展示,通过实例展示自主学习的强大魅力。该课程希望传递“理解和运用计算生态,培养集成创新思维”的理念,重点培养学习者运用当代最优秀第三方专业资源,快速分析和解决问题的能力。“人生苦短,不要刀耕火种”,嵩老师教你直面问题和需求,用最好的工具解决它!2017年度全新上线的Python语言系列专题课,带给你不一样的学习体验!网络爬虫与信息提取数据分析与展示机器学习应用科学计算三维可视化游戏开发入门云端系统开发入门
&&本课程采取百分制,客观题和主观编程题各占分。分分可获得合格证书,分以上可获得优秀证书,满分者将获得嵩老师的额外神秘大礼。
& 本课程需要学习者具备语言编程的基本知识和初步技能,建议零基础学习者先修嵩老师的“”课程。具体地,学习者需要预先掌握数字类型、字符串类型、分支、循环、函数、列表类型、字典类型、文件和第三方库使用等概念和编程方法。& 本课程需要学习者掌握、库的基本使用,建议先修嵩老师的数据分析与展示专题课程。
根据第三方库内容特点,课程共分个内容模块和个实战模块:&&&&模块:机器学习基本思想与原理、基础知识和一般流程&&&&模块:聚类问题及算法、、、&&&&模块:监督算法和无监督算法,分类问题算法、决策树、朴素贝叶斯等&&&&模块(实战):实战项目模块:回归算法、线性回归、最下二乘法等模块(实战):实战项目模块(选修):强化学习方法、深度学习、算法原理模块(选修、实战):实战项目:游戏智能对战
集成开发环境 (推荐)解释器默认工具参考教程零基础入门教程:《语言程序设计基础第版》,嵩天、礼欣、黄天羽著,高等教育出版社,2016.12专题参考资料:《机器学习实战》,著,人民邮电出版社。参考网站
Q1:除了,这个课程需要其他编程语言基础吗?A1:不需要,但本专题建议学习者掌握、库的基本使用,建议先修嵩老师的数据分析与展示专题课程,或者请学习专题内提供的自学资料。Q2:和,这个课程采用哪个版本?A2:已经足够成熟,这是语言的现在和未来,嵩老师所有课程都采用系列版本。Q3:在线开放课程看不到老师,有问题谁来解答?A3:为了更好服务同学们,本课程教师和多名助教会每天在线答疑,尽快解决与课程相关的各类问题。Q4:课程里面除了视频有什么新的形式吗?A4:大学老师都是一本正经的,但你见过大学老师闲扯吗?课间,嵩老师想说说不一样的话...&
由高教社联手网易推出,让每一个有提升愿望的用户能够学到中国知名高校的课程,并获得认证。
| 京ICP备号-2 |
(C) icourse163.org11194人阅读
Python语言(6)
python setup.py install
&&from sklearn import datasets
Traceback (most recent call last):
File &E:\P\plot_ols.py&, line 28, in
from sklearn import datasets, linear_model
File &C:\Python27\lib\site-packages\sklearn\linear_model\__init__.py&, line 12, in
from .base import LinearRegression
File &C:\Python27\lib\site-packages\sklearn\linear_model\base.py&, line 29, in
from ..utils.sparsefuncs import mean_variance_axis0, inplace_column_scale
ImportError: cannot import name inplace_column_scale
python27\Lib\site-packages\sklearn\utils\sparsefuncs.pyd
pip install -U scikit-learn
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:36574次
排名:千里之外
原创:14篇
转载:25篇
(1)(5)(1)(12)(12)(5)(3)

我要回帖

 

随机推荐