必備!人工智能和數(shù)據(jù)科學(xué)的七大 Python 庫
【導(dǎo)讀】作者匯總了2018年針對(duì)數(shù)據(jù)科學(xué)家/AI的***庫、repos、包和工具。本文對(duì)其進(jìn)行了梳理,列舉了人工智能和數(shù)據(jù)科學(xué)的七大Python庫。
本文作者Favio Vázquez從2018年開始發(fā)布《數(shù)據(jù)科學(xué)和人工智能每周文摘:Python & R》系列文章,為數(shù)據(jù)科學(xué)家介紹***的庫、repos、packages以及工具。
一年結(jié)束,作者列出了2018年的7大***的Python庫,這些庫確實(shí)地改進(jìn)了研究人員的工作方式。
7. AdaNet ———快速靈活的AutoML框架
https://github.com/tensorflow/adanet
AdaNet是一個(gè)輕量級(jí)的、可擴(kuò)展的TensorFlow AutoML框架,用于使用AdaNet算法訓(xùn)練和部署自適應(yīng)神經(jīng)網(wǎng)絡(luò)[Cortes et al. ICML 2017]。AdaNet結(jié)合了多個(gè)學(xué)習(xí)子網(wǎng)絡(luò),以減輕設(shè)計(jì)有效的神經(jīng)網(wǎng)絡(luò)所固有的復(fù)雜性。
這個(gè)軟件包將幫助你選擇***的神經(jīng)網(wǎng)絡(luò)架構(gòu),實(shí)現(xiàn)一種自適應(yīng)算法,用于學(xué)習(xí)作為子網(wǎng)絡(luò)集合的神經(jīng)架構(gòu)。
你需要了解TensorFlow才能使用這個(gè)包,因?yàn)樗鼘?shí)現(xiàn)了TensorFlow Estimator,但這將通過封裝訓(xùn)練、評(píng)估、預(yù)測(cè)和導(dǎo)出服務(wù)來幫助你簡(jiǎn)化機(jī)器學(xué)習(xí)編程。
你可以構(gòu)建一個(gè)神經(jīng)網(wǎng)絡(luò)的集合,這個(gè)庫將幫助你優(yōu)化一個(gè)目標(biāo),以平衡集合在訓(xùn)練集上的性能和將其泛化到未見過數(shù)據(jù)的能力之間的權(quán)衡。
安裝
安裝adanet之前需將TensorFlow升級(jí)到1.7或以上:
$ pip install "tensorflow>=1.7.0"
從源代碼安裝
要從源代碼進(jìn)行安裝,首先需要安裝bazel。
下一步,復(fù)制adanet和cd到它的根目錄:
$ git clone https://github.com/tensorflow/adanet && cd adanet
從adanet根目錄運(yùn)行測(cè)試:
$ cd adanet $ bazel test -c opt //...
確認(rèn)一切正常后,將adanet安裝為pip包。
現(xiàn)在,可以對(duì)adanet進(jìn)行試驗(yàn)了。
import adanet
用法
有關(guān)AdaNet的詳細(xì)用法,請(qǐng)閱讀官方教程:
https://github.com/tensorflow/adanet/tree/master/adanet/examples/tutorials
https://ai.googleblog.com/2018/10/introducing-adanet-fast-and-flexible.html?m=1
6. TPOT——一個(gè)自動(dòng)化的Python機(jī)器學(xué)習(xí)工具
https://github.com/EpistasisLab/tpot
之前我介紹過Auto-Keras,這是一個(gè)很棒的AutoML庫?,F(xiàn)在我們有另一個(gè)非常有趣的工具——TPOT。
TPOT全稱是基于樹的pipeline優(yōu)化工具(Tree-based Pipeline Optimization Tool),這是一個(gè)非常棒Python自動(dòng)機(jī)器學(xué)習(xí)工具,使用遺傳編程優(yōu)化機(jī)器學(xué)習(xí)pipeline。
TPOT可以自動(dòng)化許多東西,包括生命特性選擇、模型選擇、特性構(gòu)建等等。如果你是Python機(jī)器學(xué)習(xí)者,很幸運(yùn),TPOT是構(gòu)建在Scikit-learn之上的,所以它生成的所有代碼看起來應(yīng)該很熟悉。
它的作用是通過智能地探索數(shù)千種可能的pipeline來自動(dòng)化機(jī)器學(xué)習(xí)中最繁瑣的部分,找到最適合你的數(shù)據(jù)的pipeline,然后為你提供***的 Python 代碼。
它的工作原理如下:
安裝
安裝TPOT之前,請(qǐng)先閱讀教程:
http://epistasislab.github.io/tpot/installing/
然后,運(yùn)行以下代碼:
- pip install tpot
例子:
首先讓我們從基本的Iris數(shù)據(jù)集開始:
- 1from tpot import TPOTClassifier
- 2from sklearn.datasets import load_iris
- 3from sklearn.model_selection import train_test_split
- 4
- 5# Load iris dataset
- 6iris = load_iris()
- 7
- 8# Split the data
- 9
- 10X_trainX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target,
- 11 train_size=0.75, test_size=0.25)
- 12
- 13# Fit the TPOT classifier
- 14
- 15tpot = TPOTClassifier(verbosity=2, max_time_mins=2)
- 16tpot.fit(X_train, y_train)
- 17
- 18# Export the pipeline
- 19tpot.export('tpot_iris_pipeline.py')
我們?cè)谶@里構(gòu)建了一個(gè)非?;镜腡POT pipeline,它將嘗試尋找***ML pipeline來預(yù)測(cè)iris.target。然后保存這個(gè)pipeline。之后,我們要做的就非常簡(jiǎn)單了——加載生成的.py文件,你將看到:
- 1import numpy as np
- 2from sklearn.kernel_approximation import RBFSampler
- 3from sklearn.model_selection import train_test_split
- 4from sklearn.pipeline import make_pipeline
- 5from sklearn.tree import DecisionTreeClassifier
- 6# NOTE: Make sure that the class is labeled 'class' in the data file
- 7tpot_data = np.recfromcsv('PATH/TO/DATA/FILE', delimiter='COLUMN_SEPARATOR', dtype=np.float64)
- 8features = np.delete(tpot_data.view(np.float64).reshape(tpot_data.size, -1), tpot_data.dtype.names.index('class'), axis=1)
- 9training_features, testing_features, training_classes, testing_classes =
- 10 train_test_split(features, tpot_data['class'], random_state=42)
- 11exported_pipeline = make_pipeline(
- 12 RBFSampler(gamma=0.8500000000000001),
- 13 DecisionTreeClassifier(criterion="entropy", max_depth=3, min_samples_leaf=4, min_samples_split=9)
- 14)
- 15exported_pipeline.fit(training_features, training_classes)
- 16results = exported_pipeline.predict(testing_features)
就是這樣。你已經(jīng)以一種簡(jiǎn)單但強(qiáng)大的方式為Iris數(shù)據(jù)集構(gòu)建一個(gè)分類器。
現(xiàn)在我們來看看MNIST的數(shù)據(jù)集:
- 1from tpot import TPOTClassifier
- 2from sklearn.datasets import load_digits
- 3from sklearn.model_selection import train_test_split
- 4
- 5# load and split dataset
- 6digitsdigits == load_digitsload_di ()
- 7X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target,
- 8 train_size=0.75, test_size=0.25)
- 9
- 10# Fit the TPOT classifier
- 11tpot = TPOTClassifier(verbosity=2, max_time_mins=5, population_size=40)
- 12tpot.fit(X_train, y_train)
- 13
- 14# Export pipeline
- 15tpot.export('tpot_mnist_pipeline.py')
接下來我們?cè)俅渭虞d生成的 .py文件,你將看到:
- 1import numpy as np
- 2from sklearn.model_selection import train_test_split
- 3from sklearn.neighbors import KNeighborsClassifier
- 4# NOTE: Make sure that the class is labeled 'class' in the data file
- 5tpot_data = np.recfromcsv('PATH/TO/DATA/FILE', delimiter='COLUMN_SEPARATOR', dtype=np.float64)
- 6features = np.delete(tpot_data.view(np.float64).reshape(tpot_data.size, -1), tpot_data.dtype.names.index('class'), axis=1)
- 7training_features, testing_features, training_classes, testing_classes =
- 8 train_test_split(features, tpot_data['class'], random_state=42)
- 9exported_pipeline = KNeighborsClassifier(n_neighbors=4, p=2, weights="distance")
- 10exported_pipeline.fit(training_features, training_classes)
- 11results = exported_pipeline.predict(testing_features)
5. SHAP ——一個(gè)解釋任何機(jī)器模型輸出的統(tǒng)一方法
https://github.com/slundberg/shap
解釋機(jī)器學(xué)習(xí)模型并不容易。然而,它對(duì)許多商業(yè)應(yīng)用程序來說非常重要。幸運(yùn)的是,有一些很棒的庫可以幫助我們完成這項(xiàng)任務(wù)。在許多應(yīng)用程序中,我們需要知道、理解或證明輸入變量在模型中的運(yùn)作方式,以及它們?nèi)绾斡绊懽罱K的模型預(yù)測(cè)。
SHAP (SHapley Additive exPlanations)是一種解釋任何機(jī)器學(xué)習(xí)模型輸出的統(tǒng)一方法。SHAP將博弈論與局部解釋聯(lián)系起來,并結(jié)合了之前的幾種方法。
安裝
SHAP可以從PyPI安裝
- pip install shap
或conda -forge
- conda install -c conda-forge shap
用法
有很多不同的模型和方法可以使用這個(gè)包。在這里,我將以DeepExplainer中的一個(gè)例子為例。
Deep SHAP是深度學(xué)習(xí)模型中SHAP值的一種高速近似算法,它基于與DeepLIFT的連接,如SHAP的NIPS論文所述(https://arxiv.org/abs/1802.03888)。
下面這個(gè)例子可以看到SHAP如何被用來解釋MNIST數(shù)據(jù)集的Keras模型結(jié)果:
- # this is the code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py
- from __future__ import print_function
- import keras
- from keras.datasets import mnist
- from keras.models import Sequential
- from keras.layers import Dense, Dropout, Flatten
- from keras.layers import Conv2D, MaxPooling2D
- from keras import backend as K
- batch_size = 128
- num_classes = 10
- epochs = 12
- # input image dimensions
- img_rows, img_cols = 28, 28
- # the data, split between train and test sets
- (x_train, y_train), (x_test, y_test) = mnist.load_data()
- if K.image_data_format() == 'channels_first':
- x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
- x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
- input_shape = (1, img_rows, img_cols)
- else:
- x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
- x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
- input_shape = (img_rows, img_cols, 1)
- x_train = x_train.astype('float32')
- x_test = x_test.astype('float32')
- x_train /= 255
- x_test /= 255
- print('x_train shape:', x_train.shape)
- print(x_train.shape[0], 'train samples')
- print(x_test.shape[0], 'test samples')
- # convert class vectors to binary class matrices
- y_train = keras.utils.to_categorical(y_train, num_classes)
- y_test = keras.utils.to_categorical(y_test, num_classes)
- model = Sequential()
- model.add(Conv2D(32, kernel_size=(3, 3),
- activation='relu',
- input_shape=input_shape))
- model.add(Conv2D(64, (3, 3), activation='relu'))
- model.add(MaxPooling2D(pool_size=(2, 2)))
- model.add(Dropout(0.25))
- model.add(Flatten())
- model.add(Dense(128, activation='relu'))
- model.add(Dropout(0.5))
- model.add(Dense(num_classes, activation='softmax'))
- model.compile(loss=keras.losses.categorical_crossentropy,
- optimizer=keras.optimizers.Adadelta(),
- metrics=['accuracy'])
- model.fit(x_train, y_train,
- batch_size=batch_size,
- epochs=epochs,
- verbose=1,
- validation_data=(x_test, y_test))
- score = model.evaluate(x_test, y_test, verbose=0)
- print('Test loss:', score[0])
- print('Test accuracy:', score[1])
更多示例:
https://github.com/slundberg/shap#sample-notebooks
4. Optimus——使用 Python 和 Spark 輕松實(shí)現(xiàn)敏捷數(shù)據(jù)科學(xué)工作流
https://github.com/ironmussa/Optimus
Optimus V2旨在讓數(shù)據(jù)清理更容易。這個(gè)API的設(shè)計(jì)對(duì)新手來說超級(jí)簡(jiǎn)單,對(duì)使用pandas的人來說也非常熟悉。Optimus擴(kuò)展了Spark DataFrame功能,添加了.rows和.cols屬性。
使用Optimus,你可以以分布式的方式清理數(shù)據(jù)、準(zhǔn)備數(shù)據(jù)、分析數(shù)據(jù)、創(chuàng)建分析器和圖表,并執(zhí)行機(jī)器學(xué)習(xí)和深度學(xué)習(xí),因?yàn)樗暮蠖擞蠸park、TensorFlow和Keras。
Optimus是數(shù)據(jù)科學(xué)敏捷方法的***工具,因?yàn)樗鼛缀蹩梢詭椭阃瓿烧麄€(gè)過程的所有步驟,并且可以輕松地連接到其他庫和工具。
Installation (pip):
- pip install optimuspyspark
用法
在這個(gè)示例中,你可以從 URL 加載數(shù)據(jù),對(duì)其進(jìn)行轉(zhuǎn)換,并應(yīng)用一些預(yù)定義的清理功能:
- from optimus import Optimus
- op = Optimus()
- # This is a custom function
- def func(value, arg):
- return "this was a number"
- df =op.load.url("https://raw.githubusercontent.com/ironmussa/Optimus/master/examples/foo.csv")
- df
- .rows.sort("product","desc")
- .cols.lower(["firstName","lastName"])
- .cols.date_transform("birth", "new_date", "yyyy/MM/dd", "dd-MM-YYYY")
- .cols.years_between("birth", "years_between", "yyyy/MM/dd")
- .cols.remove_accents("lastName")
- .cols.remove_special_chars("lastName")
- .cols.replace("product","taaaccoo","taco")
- .cols.replace("product",["piza","pizzza"],"pizza")
- .rows.drop(df["id"]<7)
- .cols.drop("dummyCol")
- .cols.rename(str.lower)
- .cols.apply_by_dtypes("product",func,"string", data_type="integer")
- .cols.trim("*")
- .show()
你可以將這個(gè)表格
轉(zhuǎn)換為這樣:
是不是很酷?這個(gè)庫還可以做更多事情,具體請(qǐng)閱讀:
https://www.hioptimus.com/
3. spacy——使用Python和Cython的工業(yè)級(jí)自然語言處理
https://spacy.io/
spaCy旨在幫助你完成實(shí)際的工作——構(gòu)建真實(shí)的產(chǎn)品,或收集真實(shí)的見解。這個(gè)庫尊重你的時(shí)間,盡量避免浪費(fèi)。它易于安裝,而且它的API簡(jiǎn)單而高效。spaCy被視為自然語言處理的Ruby on Rails。
spaCy是為深度學(xué)習(xí)準(zhǔn)備文本的***方法。它與TensorFlow、PyTorch、Scikit-learn、Gensim以及Python強(qiáng)大的AI生態(tài)系統(tǒng)的其他部分無縫交互。使用spaCy,你可以很容易地為各種NLP問題構(gòu)建語言復(fù)雜的統(tǒng)計(jì)模型。
安裝
- pip3 install spacy
- $ python3 -m spacy download en
這里,我們還下載了英語語言模型。你可以在這里找到德語,西班牙語,意大利語,葡萄牙語,法國(guó)語等版本的模型:
https://spacy.io/models/
下面是主頁面的一個(gè)示例:
- # python -m spacy download en_core_web_sm
- import spacy
- # Load English tokenizer, tagger, parser, NER and word vectors
- nlp = spacy.load('en_core_web_sm')
- # Process whole documents
- text = (u"When Sebastian Thrun started working on self-driving cars at "
- u"Google in 2007, few people outside of the company took him "
- u"seriously. “I can tell you very senior CEOs of major American "
- u"car companies would shake my hand and turn away because I wasn’t "
- u"worth talking to,” said Thrun, now the co-founder and CEO of "
- u"online higher education startup Udacity, in an interview with "
- u"Recode earlier this week.")
- doc = nlp(text)
- # Find named entities, phrases and concepts
- for entity in doc.ents:
- print(entity.text, entity.label_)
- # Determine semantic similarities
- doc1 = nlp(u"my fries were super gross")
- doc2 = nlp(u"such disgusting fries")
- similarity = doc1.similarity(doc2)
- print(doc1.text, doc2.text, similarity)
在這個(gè)示例中,我們首先下載English tokenizer, tagger, parser, NER和word vectors。然后創(chuàng)建一些文本,打印找到的實(shí)體、短語和概念,***確定兩個(gè)短語的語義相似性。運(yùn)行這段代碼,你會(huì)得到:
- Sebastian Thrun PERSON
- Google ORG
- 2007 DATE
- American NORP
- Thrun PERSON
- Recode ORG
- earlier this week DATE
- my fries were super gross such disgusting fries 0.7139701635071919
2. jupytext
對(duì)我來說,jupytext是年度***。幾乎所有人都在像Jupyter這樣的筆記本上工作,但是我們也在項(xiàng)目的更核心部分使用像PyCharm這樣的IDE。
好消息是,你可以在自己喜歡的IDE中起草和測(cè)試普通腳本,在使用Jupytext時(shí)可以將IDE作為notebook在Jupyter中打開。在Jupyter中運(yùn)行notebook以生成輸出,關(guān)聯(lián).ipynb表示,并作為普通腳本或傳統(tǒng)Jupyter notebook 進(jìn)行保存和分享。
下圖展示了這個(gè)包的作用:
可點(diǎn)擊下方鏈接查看原文中的GIF展示:
https://heartbeat.fritz.ai/top-7-libraries-and-packages-of-the-year-for-data-science-and-ai-python-r-6b7cca2bf000
安裝
- pip install jupytext --upgrade
然后,配置Jupyter使用Jupytext:
使用jupyter notebook --generate-config生成Jupyter配置
編輯.jupyter/jupyter_notebook_config.py,并附加以下代碼:
- c.NotebookApp.contents_manager_class = "jupytext.TextFileContentsManager"
重啟Jupyter,即運(yùn)行:
- jupyter notebook
你可以在這里試試:
https://mybinder.org/v2/gh/mwouts/jupytext/master?filepath=demo
1.Chartify ——讓數(shù)據(jù)科學(xué)家很容易創(chuàng)建圖表的Python庫
https://xkcd.com/1945/
Chartify是Python的年度***庫。
在Python世界中創(chuàng)建一個(gè)像樣的圖很費(fèi)時(shí)間。幸運(yùn)的是,我們有像Seaborn之類的庫,但問題是他們的plots不是動(dòng)態(tài)的。
然后就出現(xiàn)了Bokeh——這是一個(gè)超棒的庫,但用它來創(chuàng)造互動(dòng)情節(jié)仍很痛苦。
Chartify建立在Bokeh之上,但它簡(jiǎn)單得多。
Chartify的特性:
- 一致的輸入數(shù)據(jù)格式:轉(zhuǎn)換數(shù)據(jù)所需的時(shí)間更少。所有繪圖函數(shù)都使用一致、整潔的輸入數(shù)據(jù)格式。
- 智能默認(rèn)樣式:創(chuàng)建漂亮的圖表,幾乎不需要自定義。
- 簡(jiǎn)單API:API盡可能直觀和容易學(xué)習(xí)。
- 靈活性:Chartify是建立在Bokeh之上的,所以如果你需要更多的控制,你可以使用Bokeh的API。
安裝
Chartify可以通過pip安裝:
- pip3 install chartify
用法
假設(shè)我們想要?jiǎng)?chuàng)建這個(gè)圖表:
- import pandas as pd
- import chartify
- # Generate example data
- data = chartify.examples.example_data()
現(xiàn)在,我們已經(jīng)加載了一些示例數(shù)據(jù),讓我們來做一些轉(zhuǎn)換:
- total_quantity_by_month_and_fruit = (data.groupby(
- [data['date'] + pd.offsets.MonthBegin(-1), 'fruit'])['quantity'].sum()
- .reset_index().rename(columns={'date': 'month'})
- .sort_values('month'))
- print(total_quantity_by_month_and_fruit.head())
- month fruit quantity
- 0 2017-01-01 Apple 7
- 1 2017-01-01 Banana 6
- 2 2017-01-01 Grape 1
- 3 2017-01-01 Orange 2
- 4 2017-02-01 Apple 8
現(xiàn)在我們可以把它畫出來:
- # Plot the data
- ch = chartify.Chart(blank_labels=True, x_axis_type='datetime')
- ch.set_title("Stacked area")
- ch.set_subtitle("Represent changes in distribution.")
- ch.plot.area(
- data_frame=total_quantity_by_month_and_fruit,
- x_column='month',
- y_column='quantity',
- color_column='fruit',
- stacked=True)
- ch.show('png')
超級(jí)容易創(chuàng)建一個(gè)互動(dòng)的plot。
更多示例:
https://github.com/spotify/chartify