码迷,mamicode.com
首页 > 编程语言 > 详细

python库使用整理

时间:2017-05-16 21:37:07      阅读:2346      评论:0      收藏:1      [点我收藏+]

标签:字母   pac   http   二进制   感知   迭代   get   3.1   square   

1. 环境搭建

l  Python安装包:www.python.org

l  Microsoft Visual C++ Compiler for Python

l  pip(get-pip.py):pip.pypa.io/en/latest/installing.html

n  pip install + 安装包          --安装包(.whl,.tar.gz,.zip)

n  pip uninstall + 安装包        --卸载包

n  pip show --files + 安装包     --查看已安装包信息

n  pip list outdated             --查看待更新包信息

n  pip install -U + 安装包          --升级包

n  pip search + 安装包            --搜索包

n  pip help                       --显示帮助信息

l  Anaconda:continuum.io/downloads

n  conda install + 安装包

n  conda uninstall + 安装包

l  一些常用包:www.lfd.uci.edu/~gohlke/pythonlibs/

n  re:正则匹配;os:文件操作;random:随机数;time:时间戳

n  requests:网页交互(get & post)

n  beautifulsoup4:用于规范化的静态网页的分析

mysqlclient、PyMySQL:Mysql数据库操作接口

n  numpy+mkl:矩阵运算

n  scipy:科学计算(插值,积分,优化,图像处理,特殊函数)

n  matplotlib:图形绘制

scikit-learn:机器学习库

n  jieba、smallseg:中文分词  https://pypi.python.org/pypi/jieba/

n  pandas:大型数据处理

n  nltk:提供50多个语料库和词典资源(分类、分词、词干提取、解析、语义推理)

n  Pattern:拥有一系列的自然语言处理工具,词性标注工具(Part-Of-Speech Tagger),N元搜索(n-gram search),情感分析(sentiment analysis),WordNet,也支持机器学习的向量空间模型,聚类,向量机。

n  TextBlob:处理文本数据(词性标注、名词短语抽取、情感分析、分类、翻译)

n  Gensim:用于对大型语料库进行主题建模、文件索引、相似度检索等,可以处理大于内存的输入数据

n  PyNLPI

n  spaCy:一个商业的开源软件,结合了Python和Cython的NLP工具

n  Polyglot:支持大规模多语言应用程序的处理(165种语言的分词,196种语言的辨识,40种语言的专有名词识别,16种语言的词性标注,136种语言的情感分析,137种语言的嵌入,135种语言的形态分析,以及69种语言的翻译)

n  MontyLingua:免费的、功能强大的、端到端的英文处理工具,适用于信息检索和提取,请求处理,问答系统,能词性标注和实体识别一些语义信息。

n  BLLIP Parser:集成了生成成分分析器和最大熵排序的统计自然语言分析器

n  Quepy:提供了将自然语言问题转换成为数据库查询语言中的查询

n  PIL:图像处理

n  xgboost(eXtreme Gradient Boosting):梯度上升算法

2. 常用命令

l  python XXX.py                --运行程序

l  python setup.py build        --编译,须在setup.py所在目录下

l  python setup.py install       --安装,同上

l  python setup.py sdist         --制作分发包,同上

l  python setup.py bdist_wininst --制作windows下的分发包,同上

3. 标准定义

#!usr/bin/python

# -*- coding: utf-8 -*-

# encoding=utf-8

from distutils.core import setup

import sys 

 

reload(sys) 

sys.setdefaultencoding(‘utf8‘)

 

# 安装包打包

setup(name="example", version="v1.0.0", description="setup_examples", author="SweetYu", py_modules=[‘文件夹1.文档1‘,‘文件夹1.文档2‘,‘文件夹2.文档3‘])

#类的定义

class A:

__count = 0             # 私有类变量

def __init__(self, name):

     self.name = name   # 公有成员变量

     A.__count += 1

@classmethod

def getCount(cls):     # 类函数

return cls.__count

def getName(self):     # 成员函数

return self.name

 

if __name__ == ‘__main__‘:

main()

4. json、string、random、re

正则表达式(Res,regex pattens)

l  元符号

.表示任意字符

[]用来匹配一个指定的字符类别

^ 取非

* 前一个字符重复0到无穷次

$ 前一个字符重复1到无穷次

?前一个字符重复0到1次

{m}前一个字符重复m次

l  特殊匹配

\d 匹配任何十进制数,相当于类 [0-9]。

\D 匹配任何非数字字符,相当于类 [^0-9]

\s 匹配任何空白字符,相当于类 [ fv]

\S 匹配任何非空白字符,相当于类 [^ fv]

\w 匹配任何字母数字字符,相当于类 [a-zA-Z0-9_]

\W 匹配任何非字母数字字符,相当于类 [^a-zA-Z0-9_]

 

import json, os, re, time

import string, random

 

obj = [[1,2,3],123,123.123,‘abc‘,{‘key1‘:(1,2,3),‘key2‘:(4,5,6)}]

encode_obj = json.dumps(obj, skipkeys=True, sort_keys=True)    #将对象转换成字符串

decode_obj = json.loads(encode_obj)             #将字符串转换成对象

 

random.randint(0,255)       #获取0~255范围内的整数

field = string.letters + string.digits #大小写字母+数字

random.sample(field,5)     #获取长度为5的field范围内的随机字符串

 

#文件处理

fp = open(filename,"w", encoding=‘utf-8-sig‘)  # ‘w‘, ‘w+‘, ‘r‘, ‘r+‘, ‘a‘, ‘a+‘

fp.write(unicode("\xEF\xBB\xBF", "utf-8"))       #写到文件开头,指示文件为UTF-8编码

fp.close()

 

m = re.search("^ab+","asdfabbbb")    # m.group() à ‘abbbb‘

re.findall("^a\w+","abcdfa\na1b2c3",re.MULTILINE)

re.findall("a{2,4}","aaaaaaaa")      # [‘aaaa‘, ‘aaaa‘]

re.findall("a{2,4}?","aaaaaaaa")     # [‘aa‘, ‘aa‘, ‘aa‘, ‘aa‘]

re.split("[a-zA-Z]+","0A3b9z")      # [‘0‘, ‘3‘, ‘9‘, ‘‘]

m = re.match("(?P<first_name>\w+) (?P<last_name>\w+)","sam lee")

> m.group("first_name")  # ‘sam‘

> m.group("last_name")   # ‘lee‘

re.sub(‘[abc]‘, ‘o‘, ‘caps rock‘)   # ‘cops rook‘

5. os、time

在Python中,通常有这几种方式来表示时间:

1)时间戳 :从1970年1月1日00:00:00开始按秒计算的偏移量,如:time(),clock(),mktime()

2)格式化的时间字符串,如:strftime ()

3)struct_time元组:如:gmtime()【UTC时区】,localtime()【当前时区】,strptime()

 

import os, time

 

time.strptime(‘2011-05-05 16:37:06‘, ‘%Y-%m-%d %X‘)

time.strftime("%Y-%m-%d %X", time.localtime())

time.localtime(1304575584.1361799)       #(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=14, tm_min=6, tm_sec=24, tm_wday=3, tm_yday=125, tm_isdst=0)

time.sleep(s)           #线程休眠s秒

 

#获取文件创建时间      例:1483882912.37   Sun Jan 08 21:41:52 2017

time.ctime(os.path.getctime(fileName))

 

os.path.exists(fileName)     #是否存在某一文件

os.chdir(dir)                 #修改当前目录

os.getcwd()                   #获取当前目录

os.listdir(dir)               #返回指定目录下的所有文件和目录名

os.remove(fileName)          #删除一个文件

os.makedirs(dir/fileName)    #生成多层递规目录

os.rmdir(dir)                 #删除单级目录

os.rename(oldName, newName)  #重命名文件

> os.sep        #当前平台下路径分隔符

> os.linesep    #给出当前平台使用的行终止符

> os.environ    #获取系统环境变量

os.path.abspath(path)         #显示该路径的绝对路径

os.path.dirname(path)         #返回该路径的父目录

os.path.isfile(path)          #如果path是一个文件,则返回True

os.path.isdir(path)           #如果path是一个目录,则返回True

os.path.splitext(fileName)   #获得(文件名,文件名后缀)

os.stat()      #获取文件或者目录信息

os.path.join(dir,fileName)   #连接目录与文件名或目录 结果为path/name

6. requests

import requests
 

session = requests.session()

 

url = ‘https://api.github.com/some/endpoint‘

params = {‘some‘: ‘data‘}

headers = {‘content-type‘: ‘application/json‘}

files = {‘file‘: open(‘report.xls‘, ‘rb‘)}

cookies = dict(cookies_are=‘working‘)

r = session.post(url, data = json.dumps(params), headers = headers, files = files, cookies = cookies, allow_redirects = False, timeout = 0.001)

# get、put、delete、options、head

 

> r.status_code   # requests.codes.ok

> r.url

> r.encoding

> r.text

> r.content

> r.headers       # r.headers[‘Content-Type‘]或 r.headers.get(‘content-type‘)

> r.history

7. beautifulsoup4

BeautifulSoup将HTML文档转换成一个树形结构,每个节点都是Python对象,所有对象可以归纳为4种:Tag、NavigableString、BeautifulSoup、Comment。

  • 当前结点:

.name:标签名

.attr:标签的属性集合(json)

.string:标签内容

.strings:标签对象包含的多个内容列表(list)

.stripped_strings:去除多余空白内容后的多个内容列表(list)

  • 直接/所有子节点:

.contents

.children     .descendants

  • (所有)父节点:

.parent        .parents

  • 兄弟节点:

.next_sibling

.previous_sibling

  • 前后节点【不分层次】:

.next_element         .next_elements

.previous_element    .previous_elements

搜索文档树

  • find_all、find
  • find_parents、find_parent
  • find_next_siblings、find_next_sibling
  • find_previous_siblings、find_previous_sibling
  • find_all_next、find_next
  • find_all_previous、find_previous
  • select

  name参数:标签名、正则表达式、列表、True(匹配任何值)、方法

  keyword参数:class、id、href等标签属性

  text 参数:标签内容

  limit参数:返回列表的大小

  recursive 参数,是否仅包含直接子结点(True/False)

  标签名不加任何修饰,类名前加点,id名前加 #

 

import re

from bs4 import BeautifulSoup

 

def has_class_but_no_id(tag):

return tag.has_attr(‘class‘) and not tag.has_attr(‘id‘)

 

soup = BeautifulSoup(html)

> soup.prettify()

> soup.find_all(has_class_but_no_id)

> soup.find(re.compile("^b"))

> soup.select(‘a[class="sister"]‘)

 

if type(soup.a.string)==bs4.element.Comment:

print(soup.a.string)         #遍历某一对象的非注释字符串

for str in soup.stripped_strings:

print(repr(str))

8. numpy

  • 常用属性:Itemsize(单个元素字节数)、size(元素个数)、shape、ndim(维数)、dtype、axis=0(列)/1(行)
  • 常用函数:max、min、sum、sin、floor(向下取整)、dot(矩阵相乘)、exp、.vstack(纵向合并)、hstack(横向合并)
  • 矩阵运算:transpose(转置)、trace(迹)、eig(特征值和特征向量)、inner(内积)、outer(外积)

 

import numpy as np

import numpy.linalg as nplg

 

a = np.array([[1,2],[3,4]] , dtype=np.int32)      #[[1 2][3 4]]

nplg.eig(a)       #矩阵A的特征向量和特征值

b = np.arange(6).reshape(2,3)   #[[0 1][2 3][4 5]]

c = np.linspace(1,3,9)           #[1. 1.25  1.5  1.75 2. 2.25 2.5  2.75 3.]

d = np.zeros((1,3))              # ones全1矩阵;eyes 单位矩阵;zeros 全0矩阵

e = d.repeat(2,axis=0)           #[[0 0 0][0 0 0]]

np.merage(a,b)    #合并数据

 

a.tofile("a.bin")

f = np.fromfile("a.bin", dtype= a.dtype)

f.shape = a.shape

 

np.save("a.npy", a)

g = np.load("a.npy")

9. scipy

 

10. sklearn

1)   Scikit-learn本身不支持深度学习和加强学习,也不支持GPU加速,不支持图模型和序列预测;

2)   Scikit-learn从来不做除机器学习领域之外的其他扩展;

3)   Scikit-learn从来不采用未经广泛验证的算法;

  1. 数据预处理

  特征提取:将输入数据转换为具有零均值和单位权方差的新变量

  归一化:将文本或图像数据转换为可用于机器学习的数字变量

from sklearn.preprocessing import *

 

# z-score标准化:减去均值,除以标准

X = StandardScaler().fit_transform(X)

# 最小-最大规范化:缩放至特定范围

X = MinMaxScaler().fit_transform(X)

X = MaxAbsScaler().fit_transform(X)

# 数据归一化/规范化

X = Normalizer(X, norm=‘l2‘).fit_transform(X)    # norm可取值l1,l2,max

# 数值特征二值化

X = Binarizer(threshold=1.1).fit_transform(X)    # threshold为阈值

# 类别数据编码,OneHot编码:OneHotEncoder

# 标签二值化:将类别特征转换为多维二元特征,并将每个特征扩展成用一维表示

label_binarize([1, 6], classes=[1, 2, 4, 6])     # 输出[1, 0, 0, 0],[0, 0, 0, 1]

# 类别编码

LabelEncoder().fit_transform([‘A‘,‘A‘,‘b‘,‘c‘])  # 输出[0, 0, 1, 2]

# 缺失值填补

imp = Imputer(missing_values=‘NaN‘, strategy=‘mean‘, axis=0)

imp.fit_transform([[1, 2], [np.nan, 3], [7, 6]]))      #[[1, 2], [4, 3], [7, 6]]

# 生成多项式特征  例:[a,b] -> [1,a,b,a^2,ab,b^2]

PolynomialFeatures(2).fit_transform(X)

# 增加伪特征

FunctionTransformer(np.log1p).fit_transform([[0, 1], [2, 3]])

  1. 分类算法

  线性:朴素贝叶斯(NB)、K-最近邻(KNN)、逻辑回归(LR)

n  训练和预测的效率较高,但对特征的依赖程度也高

n  需在特征工程上尽量对特征进行选择、变换或者组合,使得特征具有线性可分性

  非线性:随机森林(RF)、决策树(DT)、梯度提升(GBDT)、支持向量机-交叉验证(SVM-CV)、多层感知机(MLP)神经网络

n  可建模复杂的分类面,能更好的拟合数据。

# NB(Multinomial Naive Bayes) Classifier

from sklearn.naive_bayes import MultinomialNB 

model = MultinomialNB(alpha=0.01)  

# KNN Classifier

from sklearn.neighbors import KNeighborsClassifier 

model = KNeighborsClassifier() 

# LR(Logistic Regression) Classifier

from sklearn.linear_model import LogisticRegression 

model = LogisticRegression(penalty=‘l2‘) 

# RF(Random Forest) Classifier

from sklearn.ensemble import RandomForestClassifier 

model = RandomForestClassifier(n_estimators=8) 

# DT(Decision Tree) Classifier

from sklearn import tree 

model = tree.DecisionTreeClassifier() 

# GBDT(Gradient Boosting Decision Tree) Classifier 

from sklearn.ensemble import GradientBoostingClassifier 

model = GradientBoostingClassifier(n_estimators=200) 

# SVM Classifier 

from sklearn.svm import SVC 

model = SVC(kernel=‘rbf‘, probability=True) 

# SVM Classifier using CV(Cross Validation) 

from sklearn.grid_search import GridSearchCV 

from sklearn.svm import SVC 

model = SVC(kernel=‘rbf‘, probability=True) 

param_grid = {‘C‘: [1e-3, 1e-2, 1e-1, 1, 10, 100, 1000], ‘gamma‘: [0.001, 0.0001]} 

grid_search = GridSearchCV(model, param_grid, n_jobs = 1, verbose=1) 

grid_search.fit(train_x, train_y) 

best_parameters = grid_search.best_estimator_.get_params() 

for para, val in best_parameters.items(): 

    print para, val 

model=SVC(kernel=‘rbf‘,C=best_parameters[‘C‘],gamma=best_parameters[‘gamma‘],probability=True) 

# MLP Classifier 

from sklearn.neural_network import MLPClassifier 

clf=MLPClassifier(solver=‘lbfgs‘,alpha=1e-5,hidden_layer_sizes=(5,2),random_state=1)

#建立模型

model.fit(train_x, train_y) 

#预测与评价

from sklearn import metrics

predict = model.predict(test_x)   

precision = metrics.precision_score(test_y, predict) 

recall = metrics.recall_score(test_y, predict) 

accuracy = metrics.accuracy_score(test_y, predict)

  1. 回归分析

  支持向量回归(SVR)

  贝叶斯回归、内核岭回归(KR)、高斯回归

  岭回归:通过增加惩罚函数来判断、消除特征间的共线性

  Lasso回归(least absolute shrinkage and selection operator,最小绝对值收缩和选择算子)

  弹性网络(Elastic Net):使用L1和L2先验作为正则化矩阵的线性回归模型

  最小角回归(LARS,least angle regression),可用作参数选择,得到一个相关系数的稀疏向量

# 产生200个样本,500个特征(维)的回归样本空间

from sklearn.datasets import make_regression

reg_data, reg_target = make_regression(n_samples=200, n_features=500, n_informative=5, noise=5)

# 线性回归、贝叶斯回归、Lasso回归以及特征提取、岭回归、LARS回归

from sklearn import linear_model

regr_model = linear_model.LinearRegression()

bys_model = linear_model.BayesianRidge(compute_score=True)

lasso_model = linear_model.Lasso()

r_model = linear_model.Ridge(alpha=.5)

lars_model = linear_model.Lars(n_nonzero_coefs=10)

# 交叉验证

lasso_cv = linear_model.LassoCV(alphas=None, copy_X=True, cv=None, eps=0.001,

fit_intercept=True, max_iter=1000, n_alphas=100, n_jobs=1,

normalize=False, positive=False, precompute=‘auto‘,

random_state=None, selection=‘cyclic‘, tol=0.0001,verbose=False)     

lasso_cv.fit(reg_data, reg_target)

> lasso_cv.alpha_        # 正则化项L1的系数

> lasso_cv.intercept_    # 截距

new_reg_data = reg_data[:,lasso_cv.coef_!=0]  #相关系数!=0的特征,被提取得到

# 高斯回归

from sklearn import gaussian_process

gp_model = gaussian_process.GaussianProcess(theta0 = 1e-2, thetaL = 1e-4, thetaU= 1e-1)

# SVR回归、KR回归

from sklearn.svm import SVR 

from sklearn.grid_search import GridSearchCV 

from sklearn.kernel_ridge import KernelRidge  

svr_model = GridSearchCV(SVR(kernel = ‘rbf‘, gamma = 0.1), cv = 5,  

                    param_grid = {"C": [1e0,1e1,1e2,1e3], "gamma": np.logspace(-2, 2, 5)}) 

kr_model = GridSearchCV(KernelRidge(kernel = ‘rbf‘, gamma = 0.1), cv = 5, 

 param_grid = {"alpha": [1e0,0.1,1e-2,1e-3], "gamma": np.logspace(-2,2,5)})  

#训练模型

model.fit (X_train, y_train)

# 打印相关系数

print(‘Coefficients: \n‘, model.coef_)

print("Residual sum of squares: %.2f" % np.mean((model.predict(X_test) - y_test) ** 2))

print(‘Variance score: %.2f‘ % model.score(X_test, y_test))

  1. 聚类算法(无监督)

  K-均值(K-means)聚类,谱聚类,均值偏移,分层聚类,DBSCAN聚类

import numpy as np

from sklearn import datasets

 

# 产生500个样本,6个特征(维),5个簇的聚类样本空间

X, Y = datasets.make_blobs(n_samples=500, n_features=6, centers=5, cluster_std=[0.4, 0.3, 0.4, 0.3, 0.4], random_state=11)

 

# K-means Cluster

from sklearn.cluster import KMeans

clf_model = KMeans(n_clusters=3, max_iter=300, n_init=10)

# 谱聚类

from sklearn.cluster import SpectralClustering

clf_model = SpectralClustering()  #或SpectralClustering(n_clusters=k, gamma=gamma)

# DBSCAN Cluster

from sklearn.cluster import DBSCAN  

clf_model = DBSCAN(eps = 0.3, min_samples = 10) 

#建立模型

clf_model.fit(X)

y_pred = clf_model.fit_predict(X) 

#预测与评价

from sklearn import metrics

y_pred = clf_model.labels_

n_clusters_ = len(set(y_pred)) - (1 if -1 in y_pred else 0) 

print("Estimated number of clusters: %d" % n_clusters_) 

print("Homogeneity: %0.3f" % metrics.homogeneity_score(Y, y_pred))

print("Completeness: %0.3f" % metrics.completeness_score(Y, y_pred))

print("V-measure: %0.3f" % metrics.v_measure_score(Y, y_pred))

print("Adjusted Rand Index: %0.3f" % metrics.adjusted_rand_score(Y, y_pred))

print("Adjusted Mutual Information: %0.3f" % metrics.adjusted_mutual_info_score(Y, y_pred)) 

print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, y_pred))

print("Calinski-Harabasz Score", metrics.calinski_harabaz_score(X, y_pred))

  1. 数据降维

  目的:减少要考虑的随机变量的个数

  应用场景:可视化处理、效率提升

  主成分分析(PCA)、非负矩阵分解(NMF)、文档生成主题模型(LDA)、特征选择

# PCA (Principal Components Analysis)

from sklearn import decomposition

pca = decomposition.PCA()

pca.fit(X)   # 直接对数据进行降维

print(pca.explained_variance_)

pca.n_components = 2

X_reduced = pca.fit_transform(X)

 

# NMF(Nonnegtive Matrix Factorization)

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.decomposition import NMF

tfidf_vector = TfidfVectorizer(max_df=0.95, min_df=2, max_features=n_features,

                          stop_words=‘english‘)

tfidf = tfidf_vector.fit_transform(data_samples)

nmf = NMF(n_components=n_topics, random_state=1, alpha=.1, l1_ratio=.5).fit(tfidf)

 

# LDA(Latent Dirichlet Allocation)

from sklearn.feature_extraction.text import CountVectorizer

from sklearn.decomposition import LatentDirichletAllocation

tf_vector = CountVectorizer(max_df=0.95, min_df=2, max_features=n_features,

                        stop_words=‘english‘)

tf = tf_vector.fit_transform(data_samples)

lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=5, learning_method=‘online‘,

                                   learning_offset=50, random_state=0)

                                   .fit(tf)

# 打印模型结果

feature_names = vector.get_feature_names()

for topic_idx, topic in enumerate(model.components_):

   print("Topic #%d:" % topic_idx)

   print(" ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]))

  1. 模型选择

  对于给定参数和模型的比较、验证和选择

  目的:通过参数调整来提升精度

  格点搜索,交叉验证,各种针对预测误差评估的度量函数

#交叉验证

from sklearn import metrics

from sklearn.svm import SVC

from sklearn.model_selection import cross_val_score

 

clf = SVC(kernel=‘linear‘, C=1)

scores = cross_val_score(clf, iris.data, iris.target, cv=5, scoring=‘f1_macro‘)

print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))

 

# 模型的保存与载入

import pickle

from sklearn.externals import joblib

 

joblib.dump(clf , ‘c:/km.pkl‘)

clf = joblib.load(‘c:/km.pkl‘)

with open(‘save/clf.pickle‘, ‘wb‘) as f: pickle.dump(clf, f)

with open(‘save/clf.pickle‘, ‘rb‘) as f: clf = pickle.load(f)

print(clf.predict(X[0:1]))      #测试读取后的Model

11. matplotlib

from matplotlib.matlab import * 

from pylab import *

 

plot(x, y1, ‘r*‘, linewidth=2, label=‘f(x)=sin(x)‘)     #普通曲线图

plot(x, y2, ‘b-‘, linewidth=2, label=‘f(x)=2^x‘)

xlabel(‘x‘);    ylabel(‘f(x)‘);    title(‘Simple plot‘)

legend(loc=‘upper left‘)            # 添加图例

grid(True)                           # 显示网格

savefig("sin.png" ,dpi=72)          # 保存图表(dpi为分辨率)

show()                               # 显示图表,注:每次显示后刷新画板

 

text(2,4, r‘$ \alpha_i \beta_j \pi \lambda \omega $‘ , size=15)    #  

text(4,4, r‘$ \sin(0) = cost (\frac {\pi} {2}) $‘ , size=15)       #  

text(2,2 , r‘$ lim_{x \rightarrow y} \frac{1} {x^3} $‘, size=15)   #

text(4,2 , r‘$ \sqrt[4] {x} = \sqrt {y} $‘, size=15)                #  

12. jieba            https://github.com/fxsjy/jieba

import jieba

import jieba.posseg as pseg

sentence = "我来到北京清华大学"

#分词

seg_list = jieba.cut(sentence, cut_all=True) # 全模式

seg_list = jieba.cut(sentence, cut_all=False) # 精确模式

seg_list = jieba.cut(sentence)  # 默认是精确模式

seg_list = jieba.cut_for_search(sentence)  # 搜索引擎模式

#加载词典,格式:词语 [词频] [词性]

jieba.load_userdict(file_name) # file_name 为文件类对象或自定义词典的路径

#手动调整使某个词(不)分开

jieba.suggest_freq((‘中‘, ‘将‘), True)

jieba.suggest_freq(‘台中‘, True)

#关键词提取

jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=(‘ns‘, ‘n‘,‘v‘))

jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=(‘ns‘, ‘n‘,‘v‘))

#词性标注

words = pseg.cut(sentence)

for word, flag in words:

print(‘%s %s‘ % (word, flag))

13. pandas

import numpy as np

import pandas as pd

from pandas import Sereis, DataFrame

 

data = DataFrame(np.arange(16).reshape(4,4),index=list(‘abcd‘),columns=list(‘wxyz‘))

    a   b   c   d

w   0   1   2   3

x   4   5   6   7

y   8   9  10  11

z  12  13  14  15

 

data[1:4,0:3]         #第2到4行,第1到3列

data[[‘x‘:‘z‘],[0:2]]

data.iat[1:4,[0:2]]

data.ix[1:4,[‘a’,’b’,’c’]]

data.loc[[‘x‘,’y’,’z’],[‘a’:’c’]]

 

data.irow(0)    #第1行           data.iloc[-1:]  #最后1行

data.icol(0)    #第1列           data.iloc[:-1]  #最后1列

data.ix[data.a>5,3]   # ‘a’列>5的值所在行【’y’,’z’】,第4列的数据

 

data.head()  #返回data的前几行数据,默认为前五行,需要前十行则data.head(10)

data.tail()  #返回data的后几行数据,默认为后五行,需要后十行则data.tail(10)

 

14. nltk

 

l  nps_chat  # 即时消息聊天会话语料库

l  brown    # 布朗语料库

[1]      是第一个百万词级的英语电子语料库

[2]      由布朗大学于 1961年创建,包含500个不同来源的文本

[3]      按照文体分类:[‘adventure‘, ‘belles_lettres‘, ‘editorial‘, ‘fiction‘, ‘government‘, ‘hobbies‘, ‘humor‘, ‘learned‘, ‘lore‘, ‘mystery‘, ‘news‘, ‘religion‘, ‘reviews‘, ‘romance‘, ‘science_fiction‘]

l  reuters    # 路透社语料库

[1]      包含 10,788 个新闻文档,共计 130 万字

[2]      这些文档分成 90 个主题,按照“训练”和“测试”分为两组

[3]      新闻报道往往涉及多个主题,类别往往互相重叠

[4]      可以查找由一个或多个文档涵盖的主题,也可以查找包含在一个或多个类别中的文档     

l  inaugural    # 就职演说语料库

[1]       55个文本,每个文本都是一个总统的演说,具有时间维度

l  udhr        # 标注文本语料库 “世界人权宣言”

[1]      包含多国语言[‘Chickasaw‘, ‘English‘,‘German_Deutsch‘,‘Greenlandic_Inuktikut‘,‘Hungarian_Magyar‘, ‘Ibibio_Efik‘]

 

15. PIL

import zbar

from PIL import Image

 

#识别二维码

scanner = zbar.ImageScanner()       #创建图片扫描对象

scanner.parse_config(‘enable‘)      #设置对象属性

img = Image.open(filename).convert(‘L‘)   #打开一张二维码图片, #默认mode="r"

qrCode = zbar.Image(img.width, img.height,‘Y800‘, img.tobytes())  #转换图片为字节信息并扫描

scanner.scan(qrCode)

data += s.data for s in qrCode

del(img)          # 删除图片对象

print(data)       # 输出解码结果

 

#在图片上添加文字,增加噪音点

draw = ImageDraw.Draw(img)

font = ImageFont.truetype(fontfile, min(img.size)/30)

draw.text((0,img.height - fontsize), data, font=font, fill=(255,0,0))

draw.point((random.randint(0,width), random.randint(0,height)), fill=(0,0,255))

 

#按比例缩放后,模糊处理并保存

rate = max( img.width/p_width, img.height/p_height )

if rate!=0:

    img.thumbnail((img.size[0]/rate , img.size[1]/rate)) #注:此处有两个括号

img = img.filter(ImageFilter.BLUR)

img.show(); img.save(filename, ‘jpeg‘)   # 或者是‘png‘

img.close()

16. goose

17. xgboost

l  优势

1、  正则化,减少过拟合

2、  并行处理,也支持Hadoop实现

3、  高度的灵活性,允许自定义优化目标和评价标准

4、  缺失值处理

5、  剪枝

6、  内置交叉验证,获得最优boosting迭代次数

7、  可在已有模型上继续训练

l  参数

1、  通用参数:宏观函数控制

u  booster:每次迭代的模型,gbtree(默认):基于树的模型,gbliner:线性模型

u  silent:0-默认;1-静默模式,不输出任何信息

u  nthread:默认值为最大可能的线程数

2、  Booster参数:控制每一步的booster(tree/regression)

u  eta [默认0.3]:学习速率,通过减少每一步的权重,可提高模型的鲁棒性。 典型值为0.01-0.2。

u  min_child_weight [默认1]:最小样本权重的和

u  max_depth [默认6]:树的最大深度,典型值:3-10

u  max_leaf_nodes:最大的节点或叶子的数量

u  gamma [默认0]:节点分裂所需的最小损失函数下降值

u  max_delta_step [默认0]:每棵树权重改变的最大步长

u  subsample [默认1]:每棵树随机采样的比例,典型值:0.5-1

u  colsample_bytree [默认1]:每棵随机采样的列数的占比(每一列是一个特征)。 典型值:0.5-1

u  colsample_bylevel [默认1]:树的每一级的每一次分裂,对列数的采样的占比

u  lambda [默认1]:权重的L2正则化项,和Ridge regression类似

u  alpha [默认1]:权重的L1正则化项,和Lasso regression类似,可以应用在很高维度的情况下,使得算法的速度更快

u  scale_pos_weight [默认1]:在样本不平衡时,把这个参数设为一个正值,可以使算法更快收敛

3、  学习目标参数:控制训练目标的表现

u  objective [默认reg:linear]:需要被最小化的损失函数。

l  binary:logistic 二分类的逻辑回归,返回预测的概率(不是类别)

l  multi:softmax 使用softmax多分类器,返回预测的类别(不是概率),还需设一个参数:num_class(类别数目)

l  multi:softprob 和multi:softmax参数一样,但是返回的是每个数据属于各个类别的概率

u  eval_metric [默认值取决于objective参数的取值]:对于有效数据的度量方法。

l  对于回归问题,默认值是rmse,均方根误差

l  对于分类问题,默认值是error,二分类错误率(阈值为0.5)

l  mae 平均绝对误差

l  logloss 负对数似然函数值

l  merror 多分类错误率

l  mlogloss 多分类

l  logloss损失函数

l  auc 曲线下面积

u  seed [默认0]:随机数的种子,设置它可复现随机数据的结果,也可用于调整参数

 

import xgboost as xgb

 

#加载XGBoost的二进制的缓存文件

dtrain = xgb.DMatrix(‘train.svm.txt‘)

deval = xgb.DMatrix(‘test.svm.buffer‘)

 

#加载Numpy的二维数组,并处理 DMatrix中的缺失值,给样本设置权重

data = np.random.rand(5,10)              # 5个训练样本,10个特征

label = np.random.randint(2, size=5)

w = np.random.rand(5,1)

dtrain = xgb.DMatrix( data, label=label, missing = -999.0, weight=w)

 

#将scipy.sparse格式的数据转化为 DMatrix格式

csr = scipy.sparse.csr_matrix((data, (row,col)))

dtrain = xgb.DMatrix(csr)

 

#将DMatrix格式的数据保存成XGBoost的二进制格式,在下次加载时可以提高加载速度

dtrain.save_binary("train.buffer")

 

#参数设置

params = {

    ‘booster‘: ‘gbtree‘,  # gbtree(默认):基于树的模型,gbliner:线性模型

    ‘objective‘: ‘binary:logistic‘,

    ‘eval_metric‘:‘logloss‘,

    ‘scale_pos_weight‘:1,    #样本不平衡时,把这个参数设定为正值,可使算法更快收敛

‘max_depth‘:6,           #通常取[3,10], 树的最大深度

    ‘min_child_weight‘:1,    #默认为1,最小样本权重的和

    ‘gamma‘:0.15,        #通常取[0.1,0.2],节点分裂所需的最小损失函数下降值,默认为0

    ‘subsample‘:0.9,     #通常取[0.5,1],每棵树随机采样的比例

    ‘colsample_bytree‘:0.9, #通常取[0.5,0.9],随机采样的列数的占比(每一列是一个特征),默认为1

‘lambda‘:0.1,        #权重的L2正则化项

‘alpha‘:0.2,         #权重的L1正则化项

    ‘eta‘:0.15             #学习速率,默认为0.3,通常取[0.01,0.2]

}

plst = param.items()

 

#调整参数

res = xgb.cv(params, xgTrain)

 

#定义验证数据集,验证算法的性能

evallist = [(deval,‘eval‘), (dtrain,‘train‘)]

 

#训练模型

num_round = 10

bst = xgb.train( plst, dtrain, num_round, evallist, evals=evals, early_stopping_rounds=5)

#保存模型

bst.save_model(‘model.bin‘)

bst.dump_model(‘dump.raw.txt‘)

bst.dump_model(‘dump.raw.txt‘,‘featmap.txt‘)

 

#加载模型

bst = xgb.Booster({‘nthread‘:4})

model = bst.load_model("model.bin")

 

#预测结果

data = np.random.rand(7,10)           # 7个测试样本,10个特征

dtest = xgb.DMatrix(data, missing = -999.0 )

ypred = bst.predict(model)

ypred = bst.predict(model, ntree_limit=bst.best_iteration)

 

 

python库使用整理

标签:字母   pac   http   二进制   感知   迭代   get   3.1   square   

原文地址:http://www.cnblogs.com/sweetyu/p/6863560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!