当前位置:   article > 正文

python机器学习及实践 第三章3.2

python机器学习及实践 第三章3.2
  • 自然语言处理包NLTK:进行语言学分析,进行分词以及词性标注
  1. #使用词袋法对文本进行向量化
  2. sent1='The cat is walking in the bedroom.'
  3. sent2='A dog was running across the kitchen.'
  4. from sklearn.feature_extraction.text import CountVectorizer
  5. count_vec=CountVectorizer()
  6. sentences=[sent1,sent2]
  7. print count_vec.fit_transform(sentences).toarray()
  8. print count_vec.get_feature_names()
  9. #首先统计都出现了哪些词(少了‘A’)然后再建立与词数等长的向量 对应sent根据词频填入相应向量
  10. #CountVectorizer的fit会过滤长度为1的停用词 例如 A
  11. #对于一个由字符串构成的数组,每个元素可能是一个以空格分割的句子(sentence),
  12. #CountVectorizer.fit的功能是将它们分割,为每一个单词(word)编码,
  13. #在这个过程中会自动滤除停止词(stop words),例如英文句子中的”a”,”.”之类的长度为1的字符串。
  14. #CountVectorizer.transform的功能则是将输入的数组中每个元素进行分割,然后使用fit中生成的编码字典,将原单词转化成编码,
  15. ##使用NLTK进行语言学分析
  16. import nltk
  17. nltk.download('punkt')
  18. #对句子进行分割
  19. tokens_1=nltk.word_tokenize(sent1)
  20. print(tokens_1)
  21. tokens_2=nltk.word_tokenize(sent2)
  22. print(tokens_2)
  23. #将词表按照Ascii排列
  24. vocab_1=sorted(set(tokens_1))
  25. vocab_2=sorted(set(tokens_2))
  26. print(vocab_1)
  27. print(vocab_2)
  28. #找到词汇原始的词根
  29. stemmer=nltk.stem.PorterStemmer()
  30. stem_1=[stemmer.stem(t) for t in tokens_1]
  31. stem_2=[stemmer.stem(t) for t in tokens_2]
  32. print(stem_1)
  33. print(stem_2)
  34. nltk.download('averaged_perceptron_tagger')
  35. #对词性进行标注
  36. pos_tag_1=nltk.tag.pos_tag(tokens_1)
  37. pos_tag_2=nltk.tag.pos_tag(tokens_2)
  38. print(pos_tag_1)
  39. print(pos_tag_2)

  • 词向量分析word2vec:每个连续词汇片段的最后一个单词都受前面单词的制约。
  1. #词向量训练
  2. from sklearn.datasets import fetch_20newsgroups
  3. news=fetch_20newsgroups(subset='all')
  4. X,y=news.data,news.target
  5. from bs4 import BeautifulSoup
  6. import nltk,re
  7. #把新闻中的句子剥离出来 并且形成列表
  8. def news_to_sentences(news):
  9. news_text=BeautifulSoup(news).get_next()
  10. tokenizer=nltk.data.load('tokenizers/punk/english.pickle')
  11. raw_sentences=tokenizer.tokenize(news_text)
  12. sentences=[]
  13. for sent in raw_sentences:
  14. sentences.append(re.sun('[^a-zA-Z]',' ',sent.lower().strip()).split())
  15. return sentences
  16. sentences=[]
  17. #将长篇新闻中的句子剥离出来
  18. #import news_to_sentences
  19. for x in X:
  20. sentences=sentences+news_to_sentences(x)
  21. from gensim.models import word2vec
  22. num_features=300
  23. min_word_count=20
  24. num_workers=2
  25. context=5
  26. downsampling=le-3
  27. model=word2vec.Word2Vec(sentences,workers=num_workers,size=num_features,min_count=min_word_count,window=context,sample=downsampling)
  28. model.init_sims(replaces=True)
  29. model.most_similar('morning')
  • 没有跑出结果,也没有理解问题(先放着,后面会专门写一篇填坑。)

xgboost:自动利用cpu的多线程进行并行,全称是eXtreme Gradient Boosting.

  1. #Xgboost模型
  2. import pandas as pd
  3. titanic=pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
  4. y=titanic['survived']
  5. X=titanic.drop(['row.names','name','survived'],axis=1)
  6. X['age'].fillna(X['age'].mean(),inplace=True)
  7. X.fillna('UNKNOWN',inplace=True)
  8. from sklearn.model_selection import train_test_split
  9. X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=33)
  10. from sklearn.feature_extraction import DictVectorizer
  11. vec=DictVectorizer()
  12. X_train=vec.fit_transform(X_train.to_dict(orient='record'))
  13. X_test=vec.transform(X_test.to_dict(orient='record'))
  14. print( len(vec.feature_names_))
  15. #使用随机森林进行预测
  16. from sklearn.ensemble import RandomForestClassifier
  17. rfc=RandomForestClassifier()
  18. rfc.fit(X_train,y_train)
  19. print('RandomForestClassifier:',rfc.score(X_test,y_test))
  20. #使用Xgboost进行预测
  21. from xgboost import XGBClassifier
  22. xgbc=XGBClassifier()
  23. xgbc.fit(X_train,y_train)
  24. print('XGBClassifier:',xgbc.score(X_test,y_test))
  • Tensorflow:利用会话来执行计算任务,初步进行了使用以及逐步进行了一个机器学习的基本任务。
  1. #tensorflow会话执行
  2. import tensorflow as tf
  3. import numpy as np
  4. greeting=tf.constant("Hello FangFang")
  5. #启动一个会话
  6. sess=tf.Session()
  7. #使用会话执行计算模块
  8. result=sess.run(greeting)
  9. print(result)
  10. sess.close()
  11. #使用tensorflow完成一次线性计算
  12. #matrix11*2的行向量
  13. matrix1=tf.constant([[3.,3.]])
  14. #matrix22*1的列向量
  15. matrix2=tf.constant([[2.],[2.]])
  16. #两个向量相乘
  17. product=tf.matmul(matrix1,matrix2)
  18. #将乘积结果和一个标量拼接
  19. linear=tf.add(product,tf.constant(2.0))
  20. #直接在会话中执行linear
  21. with tf.Session () as sess:
  22. result=sess.run(linear)
  23. print(result)
  24. import tensorflow as tf
  25. import pandas as pd
  26. import numpy as np
  27. train = pd.read_csv('../python/Datasets/Breast-Cancer/breast-cancer-train.csv')
  28. test = pd.read_csv('../python/Datasets/Breast-Cancer/breast-cancer-test.csv')
  29. X_train=np.float32(train[['Clump Thickness','Cell Size']].T)
  30. y_train=np.float32(train['Type'].T)
  31. X_test=np.float32(test[['Clump Thickness','Cell Size']].T)
  32. y_test=np.float32(test['Type'].T)
  33. #定义一个tensorflow的变量b作为截距
  34. b=tf.Variable(tf.zeros([1]))
  35. #定义一个变量w作为线性模型的系数(-1.01.0之间的均匀分布)
  36. w=tf.Variable(tf.random_uniform([1,2],-1.0,1.0))
  37. #显示定义线性函数
  38. y=tf.matmul(w,X_train)+b
  39. #使用reduce_mean获得均方误差
  40. loss=tf.reduce_mean(tf.square(y-y_train))
  41. #使用梯队下降估计w,b,并设计迭代步长
  42. optimizer=tf.train.GradientDescentOptimizer(0.01)
  43. #以最小二乘为优化目标
  44. train=optimizer.minimize(loss)
  45. #初始化所有变量
  46. init=tf.initialize_all_variables()
  47. #开启会话
  48. sess=tf.Session()
  49. #执行初始化变量操作
  50. sess.run(init)
  51. #迭代1000次 训练参数
  52. for step in range(0,1000):
  53. sess.run(train)
  54. if step%200==0:
  55. print(step,sess.run(w),sess.run(b))
  56. test_negative=test.loc[test['Type']==0][['Clump Thickness','Cell Size']]
  57. test_postive=test.loc[test['Type']==0][['Clump Thickness','Cell Size']]
  58. import matplotlib.pyplot as plt
  59. plt.scatter(test_negative['Clump Thickness'],test_negative['Cell Size'],marker='o',s=200,c='red')
  60. plt.scatter(test_postive['Clump Thickness'],test_postive['Cell Size'],marker='x',s=150,c='black')
  61. plt.xlabel('Clump Thickness')
  62. plt.ylabel('Cell Size')
  63. lx=np.arange(0,12)
  64. #以0.5为界 1为恶 0为良
  65. ly=(0.5-sess.run(b)-lx*sess.run(w)[0][0])/sess.run(w)[0][1]
  66. plt.plot(lx,ly,color='blue')
  67. plt.show()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/781174
推荐阅读
相关标签
  

闽ICP备14008679号