最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python中scikit-learn機(jī)器代碼實(shí)例

 更新時(shí)間:2018年08月05日 11:25:21   作者:yan456jie  
這篇文章給大家分享了關(guān)于python中scikit-learn機(jī)器的代碼實(shí)例內(nèi)容,有興趣的朋友跟著小編測(cè)試下。

我們給大家?guī)砹岁P(guān)于學(xué)習(xí)python中scikit-learn機(jī)器代碼的相關(guān)具體實(shí)例,以下就是全部代碼內(nèi)容:

# -*- 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)
 
 
使用自定義數(shù)據(jù)
# 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 = [
   '我們 我們 好孩子 認(rèn)證 。 就是',
   '我們 好孩子 認(rèn)證 。 中國',
   '我們 好孩子 認(rèn)證 。 孤獨(dú)',
   '我們 好孩子 認(rèn)證 。',
 ]
 
test_corpus = [
   '我 菲律賓 韓國',
   '我們 好孩子 認(rèn)證 。 中國',
 ]
 
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):
  """
  隨機(jī)森林,不可使用稀疏矩陣
  """
  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)
  '''
  #輸出打標(biāo)簽結(jié)果
  test_feature_list = codecs_read_label_line('test.dat')
  save_test_features(test_feature_list, pred)
  '''
  
 
if __name__ == '__main__':
  main()
 

相關(guān)文章

  • Python基于locals返回作用域字典

    Python基于locals返回作用域字典

    這篇文章主要介紹了Python基于locals返回作用域字典,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • Python爬蟲獲取基金列表

    Python爬蟲獲取基金列表

    這篇文章主要介紹了Python爬蟲獲取基金列表,python爬蟲用來收集數(shù)據(jù)是最直接和常用的方法,可以使用python爬蟲程序獲得大量的數(shù)據(jù),下文更多相關(guān)內(nèi)容介紹,需要的小伙伴可以參考一下
    2022-05-05
  • Python刪除空文件和空文件夾的方法

    Python刪除空文件和空文件夾的方法

    這篇文章主要介紹了Python刪除空文件和空文件夾的方法,涉及Python針對(duì)文件與文件夾的遍歷、判斷與刪除等技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-07-07
  • OpenCV實(shí)現(xiàn)手勢(shì)虛擬拖拽的使用示例(附demo)

    OpenCV實(shí)現(xiàn)手勢(shì)虛擬拖拽的使用示例(附demo)

    本文主要介紹了OpenCV實(shí)現(xiàn)手勢(shì)虛擬拖拽的使用示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-11-11
  • pytest框架之fixture詳細(xì)使用詳解

    pytest框架之fixture詳細(xì)使用詳解

    這篇文章主要介紹了pytest框架之fixture詳細(xì)使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • Python畫圖工具M(jìn)atplotlib庫常用命令簡(jiǎn)述

    Python畫圖工具M(jìn)atplotlib庫常用命令簡(jiǎn)述

    這篇文章主要介紹了Python畫圖Matplotlib庫常用命令簡(jiǎn)述總結(jié),文中包含詳細(xì)的圖文示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-09-09
  • PyTorch中self.layers的使用小結(jié)

    PyTorch中self.layers的使用小結(jié)

    self.layers?是一個(gè)用于存儲(chǔ)網(wǎng)絡(luò)層的屬性,本文主要介紹了PyTorch中self.layers的使用小結(jié),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-01-01
  • Python根據(jù)輸入?yún)?shù)計(jì)算結(jié)果的實(shí)例方法

    Python根據(jù)輸入?yún)?shù)計(jì)算結(jié)果的實(shí)例方法

    在本篇文章里小編個(gè)大家整理了一篇關(guān)于Python根據(jù)輸入?yún)?shù)計(jì)算結(jié)果的實(shí)例方法,有興趣的朋友們可以跟著學(xué)習(xí)參考下。
    2021-08-08
  • 利用python控制Autocad:pyautocad方式

    利用python控制Autocad:pyautocad方式

    這篇文章主要介紹了利用python控制Autocad:pyautocad方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python實(shí)現(xiàn)決策樹并且使用Graphviz可視化的例子

    Python實(shí)現(xiàn)決策樹并且使用Graphviz可視化的例子

    今天小編就為大家分享一篇Python實(shí)現(xiàn)決策樹并且使用Graphviz可視化的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08

最新評(píng)論

虎林市| 琼海市| 凤凰县| 栖霞市| 瓮安县| 通辽市| 安化县| 桐庐县| 章丘市| 阳信县| 亳州市| 阿拉尔市| 郓城县| 连城县| 大兴区| 深水埗区| 漳浦县| 福建省| 贵定县| 北票市| 封开县| 多伦县| 习水县| 星座| 大田县| 三原县| 兰西县| 会昌县| 泽库县| 木里| 孝昌县| 山东省| 古田县| 潍坊市| 固阳县| 大竹县| 桃源县| 日喀则市| 康乐县| 广平县| 甘南县|