python中scikit-learn机器代码实例


Posted in Python onAugust 05, 2018

我们给大家带来了关于学习python中scikit-learn机器代码的相关具体实例,以下就是全部代码内容:

# -*- coding: utf-8 -*-
 
import numpy
from sklearn import metrics
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import MultinomialNB
from sklearn import linear_model
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn import cross_validation
from sklearn import preprocessing
#import iris_data
 
def load_data():
  iris = load_iris()
  x, y = iris.data, iris.target
  x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=42)
  return x_train,y_train,x_test,y_test
 
def train_clf3(train_data, train_tags):
  clf = LinearSVC(C=1100.0)#default with 'rbf' 
  clf.fit(train_data,train_tags)
  return clf
 
def train_clf(train_data, train_tags):
  clf = MultinomialNB(alpha=0.01)
  print numpy.asarray(train_tags)
  clf.fit(train_data, numpy.asarray(train_tags))
  return clf
 
def evaluate(actual, pred):
  m_precision = metrics.precision_score(actual, pred)
  m_recall = metrics.recall_score(actual, pred)
  print 'precision:{0:.3f}'.format(m_precision)
  print 'recall:{0:0.3f}'.format(m_recall)
  print 'f1-score:{0:.8f}'.format(metrics.f1_score(actual,pred));
 
x_train,y_train,x_test,y_test = load_data()
 
clf = train_clf(x_train, y_train)
 
pred = clf.predict(x_test)
evaluate(numpy.asarray(y_test), pred)
print metrics.classification_report(y_test, pred)
 
 
使用自定义数据
# coding: utf-8
 
import numpy
from sklearn import metrics
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
import codecs
from sklearn.ensemble import RandomForestClassifier
from sklearn import cross_validation
from sklearn import linear_model
 
train_corpus = [
   '我们 我们 好孩子 认证 。 就是',
   '我们 好孩子 认证 。 中国',
   '我们 好孩子 认证 。 孤独',
   '我们 好孩子 认证 。',
 ]
 
test_corpus = [
   '我 菲律宾 韩国',
   '我们 好孩子 认证 。 中国',
 ]
 
def input_data(train_file, test_file):
  train_words = []
  train_tags = []
  test_words = []
  test_tags = []
  f1 = codecs.open(train_file,'r','utf-8','ignore')
  for line in f1:
    tks = line.split(':', 1)
    word_list = tks[1]
    word_array = word_list[1:(len(word_list)-3)].split(", ")
    train_words.append(" ".join(word_array))
    train_tags.append(tks[0])
  f2 = codecs.open(test_file,'r','utf-8','ignore')
  for line in f2:
    tks = line.split(':', 1)
    word_list = tks[1]
    word_array = word_list[1:(len(word_list)-3)].split(", ")
    test_words.append(" ".join(word_array))
    test_tags.append(tks[0])
  return train_words, train_tags, test_words, test_tags
 
 
def vectorize(train_words, test_words):
  #v = HashingVectorizer(n_features=25000, non_negative=True)
  v = HashingVectorizer(non_negative=True)
  #v = CountVectorizer(min_df=1)
  train_data = v.fit_transform(train_words)
  test_data = v.fit_transform(test_words)
  return train_data, test_data
 
def vectorize1(train_words, test_words):
  tv = TfidfVectorizer(sublinear_tf = False,use_idf=True);
  train_data = tv.fit_transform(train_words);
  tv2 = TfidfVectorizer(vocabulary = tv.vocabulary_);
  test_data = tv2.fit_transform(test_words);
  return train_data, test_data
  
def vectorize2(train_words, test_words):
  count_v1= CountVectorizer(stop_words = 'english', max_df = 0.5); 
  counts_train = count_v1.fit_transform(train_words); 
   
  count_v2 = CountVectorizer(vocabulary=count_v1.vocabulary_);
  counts_test = count_v2.fit_transform(test_words);
   
  tfidftransformer = TfidfTransformer();
   
  train_data = tfidftransformer.fit(counts_train).transform(counts_train); 
  test_data = tfidftransformer.fit(counts_test).transform(counts_test);
  return train_data, test_data
 
def evaluate(actual, pred):
  m_precision = metrics.precision_score(actual, pred)
  m_recall = metrics.recall_score(actual, pred)
  print 'precision:{0:.3f}'.format(m_precision)
  print 'recall:{0:0.3f}'.format(m_recall)
  print 'f1-score:{0:.8f}'.format(metrics.f1_score(actual,pred));
 
 
def train_clf(train_data, train_tags):
  clf = MultinomialNB(alpha=0.01)
  clf.fit(train_data, numpy.asarray(train_tags))
  return clf
 
 
def train_clf1(train_data, train_tags):
  #KNN Classifier
  clf = KNeighborsClassifier()#default with k=5 
  clf.fit(train_data, numpy.asarray(train_tags)) 
  return clf
 
def train_clf2(train_data, train_tags):
  clf = linear_model.LogisticRegression(C=1e5) 
  clf.fit(train_data,train_tags)
  return clf
 
def train_clf3(train_data, train_tags):
  clf = LinearSVC(C=1100.0)#default with 'rbf' 
  clf.fit(train_data,train_tags)
  return clf
 
def train_clf4(train_data, train_tags):
  """
  随机森林,不可使用稀疏矩阵
  """
  clf = RandomForestClassifier(n_estimators=10)
  clf.fit(train_data.todense(),train_tags)
  return clf
 
#使用codecs逐行读取
def codecs_read_label_line(filename):
  label_list=[]
  f = codecs.open(filename,'r','utf-8','ignore')
  line = f.readline()
  while line:
    #label_list.append(line[0:len(line)-2])
    label_list.append(line[0:len(line)-1])
    line = f.readline()
  f.close()
  return label_list
 
def save_test_features(test_url, test_label):
  test_feature_list = codecs_read_label_line('test.dat')
  fw = open('test_labeded.dat',"w+")
  
  for (url,label) in zip(test_feature_list,test_label):
    fw.write(url+'\t'+label)
    fw.write('\n')
  fw.close()
 
def main():
  train_file = u'..\\file\\py_train.txt'
  test_file = u'..\\file\\py_test.txt'
  train_words, train_tags, test_words, test_tags = input_data(train_file, test_file)
  #print len(train_words), len(train_tags), len(test_words), len(test_words), 
  
  train_data, test_data = vectorize1(train_words, test_words)
  print type(train_data)
  print train_data.shape
  print test_data.shape
  print test_data[0].shape
  print numpy.asarray(test_data[0])
  
  clf = train_clf3(train_data, train_tags)
  
  scores = cross_validation.cross_val_score(
  clf, train_data, train_tags, cv=5, scoring="f1_weighted")
  print scores
 
  #predicted = cross_validation.cross_val_predict(clf, train_data,train_tags, cv=5)  
  '''
  
  '''
  pred = clf.predict(test_data)
  error_list=[]
  for (true_tag,predict_tag) in zip(test_tags,pred):
    if true_tag != predict_tag:
      print true_tag,predict_tag
      error_list.append(true_tag+' '+predict_tag)
  print len(error_list)
  evaluate(numpy.asarray(test_tags), pred)
  '''
  #输出打标签结果
  test_feature_list = codecs_read_label_line('test.dat')
  save_test_features(test_feature_list, pred)
  '''
  
 
if __name__ == '__main__':
  main()
Python 相关文章推荐
详解Python中的装饰器、闭包和functools的教程
Apr 02 Python
Python环境下安装使用异步任务队列包Celery的基础教程
May 07 Python
全面了解Python环境配置及项目建立
Jun 30 Python
Scrapy-redis爬虫分布式爬取的分析和实现
Feb 07 Python
python3.4用函数操作mysql5.7数据库
Jun 23 Python
pandas Dataframe行列读取的实例
Jun 08 Python
Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题
Jul 15 Python
Numpy的简单用法小结
Aug 28 Python
python实现LRU热点缓存及原理
Oct 29 Python
Python OpenCV去除字母后面的杂线操作
Jul 05 Python
使用pandas模块实现数据的标准化操作
May 14 Python
Python中OpenCV实现查找轮廓的实例
Jun 08 Python
解决使用pycharm提交代码时冲突之后文件丢失找回的方法
Aug 05 #Python
Python字符串、整数、和浮点型数相互转换实例
Aug 04 #Python
python与caffe改变通道顺序的方法
Aug 04 #Python
Python爬虫PyQuery库基本用法入门教程
Aug 04 #Python
python list转矩阵的实例讲解
Aug 04 #Python
Python 生成 -1~1 之间的随机数矩阵方法
Aug 04 #Python
Python爬虫框架scrapy实现downloader_middleware设置proxy代理功能示例
Aug 04 #Python
You might like
PHP 动态随机生成验证码类代码
2010/04/09 PHP
php可生成缩略图的文件上传类实例
2014/12/17 PHP
PHP中的traits实现代码复用使用实例
2015/05/13 PHP
php的常量和变量实例详解
2017/06/27 PHP
深入分析js中的constructor和prototype
2012/04/07 Javascript
从jquery的过滤器.filter()方法想到的
2013/09/29 Javascript
使用javascript获取页面名称
2014/12/23 Javascript
JQuery选择器、过滤器大整理
2015/05/26 Javascript
js实现字符串和数组之间相互转换操作
2016/01/12 Javascript
JavaScript之Date_动力节点Java学院整理
2017/06/28 Javascript
微信小程序tabBar底部导航中文注解api详解
2017/08/16 Javascript
React教程之Props验证的具体用法(Props Validation)
2017/09/04 Javascript
jQuery实现简单复制json对象和json对象集合操作示例
2018/07/09 jQuery
vue 使用高德地图vue-amap组件过程解析
2019/09/07 Javascript
小程序两种滚动公告栏的实现方法
2019/09/17 Javascript
Vue实现开心消消乐游戏算法
2019/10/22 Javascript
es6函数之严格模式用法实例分析
2020/03/17 Javascript
[01:14]3.19DOTA2发布会 三代刀塔人第二代
2014/03/25 DOTA
[56:35]DOTA2上海特级锦标赛主赛事日 - 5 总决赛Liquid VS Secret第一局
2016/03/06 DOTA
[56:13]DOTA2-DPC中国联赛定级赛 LBZS vs Phoenix BO3第一场 1月10日
2021/03/11 DOTA
python实现可将字符转换成大写的tcp服务器实例
2015/04/29 Python
python使用tcp实现局域网内文件传输
2020/03/20 Python
Python 中Django验证码功能的实现代码
2019/06/20 Python
Python 实现黑客帝国中的字符雨的示例代码
2020/02/20 Python
python 中的命名空间,你真的了解吗?
2020/08/19 Python
利用CSS3实现毛玻璃效果示例源码
2016/09/25 HTML / CSS
使用css3和jquery实现可伸缩搜索框
2014/02/12 HTML / CSS
本科生求职简历的自我评价
2013/10/21 职场文书
汽车4S店销售经理岗位职责
2015/04/02 职场文书
裁员通知
2015/04/25 职场文书
道歉短信大全
2015/05/12 职场文书
开发一个封装iframe的vue组件
2021/03/29 Vue.js
带你学习MySQL执行计划
2021/05/31 MySQL
在 SQL 语句中处理 NULL 值的方法
2021/06/07 SQL Server
golang 实用库gotable的具体使用
2021/07/01 Golang
彩虹社八名人气艺人全新周边限时推出,性转女装男装一次拥有!
2022/04/01 日漫