加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

必备!人工智能和数据科学的七大 Python 库

发布时间:2019-01-18 05:42:27 所属栏目:教程 来源:AI应用前沿
导读:【导读】作者汇总了2018年针对数据科学家/AI的最佳库、repos、包和器材。本文对其举办了梳理,罗列了人工智能和数据科学的七大Python库。 本文作者Favio Vzquez从2018年开始宣布《数据科学和人工智能每周文摘:Python R》系列文章,为数据科学家先容最好的
副问题[/!--empirenews.page--]

 必备!人工智能和数据科学的七大 Python 库

【导读】作者汇总了2018年针对数据科学家/AI的最佳库、repos、包和器材。本文对其举办了梳理,罗列了人工智能和数据科学的七大Python库。

本文作者Favio Vázquez从2018年开始宣布《数据科学和人工智能每周文摘:Python & R》系列文章,为数据科学家先容最好的库、repos、packages以及器材。

一年竣事,作者列出了2018年的7大最好的Python库,这些库确实地改造了研究职员的事变方法。

必备!人工智能和数据科学的七大 Python 库

7. AdaNet ———快速机动的AutoML框架

必备!人工智能和数据科学的七大 Python 库

https://github.com/tensorflow/adanet

AdaNet是一个轻量级的、可扩展的TensorFlow AutoML框架,用于行使AdaNet算法实习和陈设自顺应神经收集[Cortes et al. ICML 2017]。AdaNet团结了多个进修子收集,以减轻计划有用的神经收集所固有的伟大性。

这个软件包将辅佐你选择最优的神经收集架构,实现一种自顺应算法,用于进修作为子收集荟萃的神经架构。

你必要相识TensorFlow才气行使这个包,由于它实现了TensorFlow Estimator,但这将通过封装实习、评估、猜测和导出处事来辅佐你简化呆板进修编程。

你可以构建一个神经收集的荟萃,这个库将辅佐你优化一个方针,以均衡荟萃在实习集上的机能和将其泛化到未见过数据的手段之间的衡量。

安装

安装adanet之前需将TensorFlow进级到1.7或以上:

$ pip install "tensorflow>=1.7.0"

从源代码安装

要从源代码举办安装,起首必要安装bazel。

下一步,复制adanet和cd到它的根目次:

$ git clone https://github.com/tensorflow/adanet && cd adanet

从adanet根目次运行测试:

$ cd adanet
$ bazel test -c opt //...

确认统统正常后,将adanet安装为pip包。

此刻,可以对adanet举办试验了。

import adanet

用法

必备!人工智能和数据科学的七大 Python 库

有关AdaNet的具体用法,请阅读官方教程:

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——一个自动化的Python呆板进修器材

必备!人工智能和数据科学的七大 Python 库

https://github.com/EpistasisLab/tpot

之前我先容过Auto-Keras,这是一个很棒的AutoML库。此刻我们有另一个很是风趣的器材——TPOT。

TPOT全称是基于树的pipeline优化器材(Tree-based Pipeline Optimization Tool),这是一个很是棒Python自动呆板进修器材,行使遗传编程优化呆板进修pipeline。

必备!人工智能和数据科学的七大 Python 库

TPOT可以自动化很多对象,包罗生命特征选择、模子选择、特征构建等等。假如你是Python呆板进修者,很荣幸,TPOT是构建在Scikit-learn之上的,以是它天生的全部代码看起来应该很认识。

它的浸染是通过智能地试探数千种也许的pipeline来自动化呆板进修中最繁琐的部门,找到最得当你的数据的pipeline,然后为你提供最佳的 Python 代码。

它的事变道理如下:

必备!人工智能和数据科学的七大 Python 库

安装

安装TPOT之前,请先阅读教程:

http://epistasislab.github.io/tpot/installing/

然后,运行以下代码:

  1. pip install tpot 

例子:

起首让我们从根基的Iris数据集开始:

  1.  1from tpot import TPOTClassifier 
  2.  2from sklearn.datasets import load_iris 
  3.  3from sklearn.model_selection import train_test_split 
  4.  4 
  5.  5# Load iris dataset 
  6.  6iris = load_iris() 
  7.  7 
  8.  8# Split the data 
  9.  9 
  10. 10X_trainX_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, 
  11. 11 train_size=0.75, test_size=0.25) 
  12. 12 
  13. 13# Fit the TPOT classifier  
  14. 14 
  15. 15tpot = TPOTClassifier(verbosity=2, max_time_mins=2) 
  16. 16tpot.fit(X_train, y_train) 
  17. 17 
  18. 18# Export the pipeline 
  19. 19tpot.export('tpot_iris_pipeline.py') 

我们在这里构建了一个很是根基的TPOT pipeline,它将实行探求最佳ML pipeline来猜测iris.target。然后生涯这个pipeline。之后,我们要做的就很是简朴了——加载天生的.py文件,你将看到:

  1.  1import numpy as np 
  2.  2from sklearn.kernel_approximation import RBFSampler 
  3.  3from sklearn.model_selection import train_test_split 
  4.  4from sklearn.pipeline import make_pipeline 
  5.  5from sklearn.tree import DecisionTreeClassifier 
  6.  6# NOTE: Make sure that the class is labeled 'class' in the data file 
  7.  7tpot_data = np.recfromcsv('PATH/TO/DATA/FILE', delimiter='COLUMN_SEPARATOR', dtype=np.float64) 
  8.  8features = np.delete(tpot_data.view(np.float64).reshape(tpot_data.size, -1), tpot_data.dtype.names.index('class'), axis=1) 
  9.  9training_features, testing_features, training_classes, testing_classes =  
  10. 10 train_test_split(features, tpot_data['class'], random_state=42) 
  11. 11exported_pipeline = make_pipeline( 
  12. 12 RBFSampler(gamma=0.8500000000000001), 
  13. 13 DecisionTreeClassifier(criterion="entropy", max_depth=3, min_samples_leaf=4, min_samples_split=9) 
  14. 14) 
  15. 15exported_pipeline.fit(training_features, training_classes) 
  16. 16results = exported_pipeline.predict(testing_features) 

就是这样。你已经以一种简朴但强盛的方法为Iris数据集构建一个分类器。

此刻我们来看看MNIST的数据集:

  1. 1from tpot import TPOTClassifier 
  2.  2from sklearn.datasets import load_digits 
  3.  3from sklearn.model_selection import train_test_split 
  4.  4 
  5.  5# load and split dataset  
  6.  6digitsdigits == load_digitsload_di () 
  7.  7X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, 
  8.  8 train_size=0.75, test_size=0.25) 
  9.  9 
  10. 10# Fit the TPOT classifier  
  11. 11tpot = TPOTClassifier(verbosity=2, max_time_mins=5, population_size=40) 
  12. 12tpot.fit(X_train, y_train) 
  13. 13 
  14. 14# Export pipeline 
  15. 15tpot.export('tpot_mnist_pipeline.py') 

接下来我们再次加载天生的 .py文件,你将看到:

  1.  1import numpy as np 
  2.  2from sklearn.model_selection import train_test_split 
  3.  3from sklearn.neighbors import KNeighborsClassifier 
  4.  4# NOTE: Make sure that the class is labeled 'class' in the data file 
  5.  5tpot_data = np.recfromcsv('PATH/TO/DATA/FILE', delimiter='COLUMN_SEPARATOR', dtype=np.float64) 
  6.  6features = np.delete(tpot_data.view(np.float64).reshape(tpot_data.size, -1), tpot_data.dtype.names.index('class'), axis=1) 
  7.  7training_features, testing_features, training_classes, testing_classes =  
  8.  8 train_test_split(features, tpot_data['class'], random_state=42) 
  9.  9exported_pipeline = KNeighborsClassifier(n_neighbors=4, p=2, weights="distance") 
  10. 10exported_pipeline.fit(training_features, training_classes) 
  11. 11results = exported_pipeline.predict(testing_features) 

5. SHAP ——一个表明任何呆板模子输出的同一要领

必备!人工智能和数据科学的七大 Python 库

https://github.com/slundberg/shap

表明呆板进修模子并不轻易。然而,它对很多贸易应用措施来说很是重要。荣幸的是,有一些很棒的库可以辅佐我们完成这项使命。在很多应用措施中,我们必要知道、领略或证明输入变量在模子中的运作方法,以及它们怎样影响最终的模子猜测。

SHAP (SHapley Additive exPlanations)是一种表明任何呆板进修模子输出的同一要领。SHAP将博弈论与局部表明接洽起来,并团结了之前的几种要领。

安装

SHAP可以从PyPI安装

  1. pip install shap 

或conda -forge

  1. conda install -c conda-forge shap 

用法

有许多差异的模子和要领可以行使这个包。在这里,我将以DeepExplainer中的一个例子为例。

Deep SHAP是深度进修模子中SHAP值的一种高速近似算法,它基于与DeepLIFT的毗连,如SHAP的NIPS论文所述(https://arxiv.org/abs/1802.03888)。

下面这个例子可以看到SHAP怎样被用来表明MNIST数据集的Keras模子功效:

  1. # this is the code from https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py 
  2. from __future__ import print_function 
  3. import keras 
  4. from keras.datasets import mnist 
  5. from keras.models import Sequential 
  6. from keras.layers import Dense, Dropout, Flatten 
  7. from keras.layers import Conv2D, MaxPooling2D 
  8. from keras import backend as K 
  9. batch_size = 128 
  10. num_classes = 10 
  11. epochs = 12 
  12. # input image dimensions 
  13. img_rows, img_cols = 28, 28 
  14. # the data, split between train and test sets 
  15. (x_train, y_train), (x_test, y_test) = mnist.load_data() 
  16. if K.image_data_format() == 'channels_first': 
  17.  x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) 
  18.  x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) 
  19.  input_shape = (1, img_rows, img_cols) 
  20. else: 
  21.  x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) 
  22.  x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) 
  23.  input_shape = (img_rows, img_cols, 1) 
  24. x_train = x_train.astype('float32') 
  25. x_test = x_test.astype('float32') 
  26. x_train /= 255 
  27. x_test /= 255 
  28. print('x_train shape:', x_train.shape) 
  29. print(x_train.shape[0], 'train samples') 
  30. print(x_test.shape[0], 'test samples') 
  31. # convert class vectors to binary class matrices 
  32. y_train = keras.utils.to_categorical(y_train, num_classes) 
  33. y_test = keras.utils.to_categorical(y_test, num_classes) 
  34. model = Sequential() 
  35. model.add(Conv2D(32, kernel_size=(3, 3), 
  36.  activation='relu', 
  37.  input_shape=input_shape)) 
  38. model.add(Conv2D(64, (3, 3), activation='relu')) 
  39. model.add(MaxPooling2D(pool_size=(2, 2))) 
  40. model.add(Dropout(0.25)) 
  41. model.add(Flatten()) 
  42. model.add(Dense(128, activation='relu')) 
  43. model.add(Dropout(0.5)) 
  44. model.add(Dense(num_classes, activation='softmax')) 
  45. model.compile(loss=keras.losses.categorical_crossentropy, 
  46.  optimizer=keras.optimizers.Adadelta(), 
  47.  metrics=['accuracy']) 
  48. model.fit(x_train, y_train, 
  49.  batch_size=batch_size, 
  50.  epochs=epochs, 
  51.  verbose=1, 
  52.  validation_data=(x_test, y_test)) 
  53. score = model.evaluate(x_test, y_test, verbose=0) 
  54. print('Test loss:', score[0]) 
  55. print('Test accuracy:', score[1]) 

更多示例:

https://github.com/slundberg/shap#sample-notebooks

4. Optimus——行使 Python 和 Spark 轻松实现火速数据科学事变流

必备!人工智能和数据科学的七大 Python 库

https://github.com/ironmussa/Optimus

Optimus V2旨在让数据整理更轻易。这个API的计划对新手来说超等简朴,对行使pandas的人来说也很是认识。Optimus扩展了Spark DataFrame成果,添加了.rows和.cols属性。

行使Optimus,你可以以漫衍式的方法整理数据、筹备数据、说明数据、建设说明器和图表,并执行呆板进修和深度进修,由于它的后端有Spark、TensorFlow和Keras。

Optimus是数据科学火速要领的美满器材,由于它险些可以辅佐你完成整个进程的全部步调,而且可以轻松地毗连到其他库和器材。

Installation (pip):

  1. pip install optimuspyspark 

用法

在这个示例中,你可以从 URL 加载数据,对其举办转换,并应用一些预界说的整理成果:

  1. from optimus import Optimus 
  2. op = Optimus() 
  3. # This is a custom function 
  4. def func(value, arg): 
  5.  return "this was a number" 
  6. df =op.load.url("https://raw.githubusercontent.com/ironmussa/Optimus/master/examples/foo.csv") 
  7. df 
  8.  .rows.sort("product","desc") 
  9.  .cols.lower(["firstName","lastName"]) 
  10.  .cols.date_transform("birth", "new_date", "yyyy/MM/dd", "dd-MM-YYYY") 
  11.  .cols.years_between("birth", "years_between", "yyyy/MM/dd") 
  12.  .cols.remove_accents("lastName") 
  13.  .cols.remove_special_chars("lastName") 
  14.  .cols.replace("product","taaaccoo","taco") 
  15.  .cols.replace("product",["piza","pizzza"],"pizza") 
  16.  .rows.drop(df["id"]<7) 
  17.  .cols.drop("dummyCol") 
  18.  .cols.rename(str.lower) 
  19.  .cols.apply_by_dtypes("product",func,"string", data_type="integer") 
  20.  .cols.trim("*") 
  21.  .show() 

你可以将这个表格

必备!人工智能和数据科学的七大 Python 库

转换为这样:

必备!人工智能和数据科学的七大 Python 库

是不是很酷?这个库还可以做更多工作,详细请阅读:

https://www.hioptimus.com/

3. spacy——行使Python和Cython的家产级天然说话处理赏罚

必备!人工智能和数据科学的七大 Python 库

https://spacy.io/

spaCy旨在辅佐你完成现实的事变——构建真实的产物,或网络真实的看法。这个库尊重你的时刻,只管停止挥霍。它易于安装,并且它的API简朴而高效。spaCy被视为天然说话处理赏罚的Ruby on Rails。

spaCy是为深度进修筹备文本的最佳要领。它与TensorFlow、PyTorch、Scikit-learn、Gensim以及Python强盛的AI生态体系的其他部门无缝交互。行使spaCy,你可以很轻易地为各类NLP题目构建说话伟大的统计模子。

安装

  1. pip3 install spacy 
  2. $ python3 -m spacy download en 

这里,我们还下载了英语说话模子。你可以在这里找到德语,西班牙语,意大利语,葡萄牙语,法国语等版本的模子:

https://spacy.io/models/

下面是主页面的一个示例:

  1. # python -m spacy download en_core_web_sm 
  2. import spacy 
  3. # Load English tokenizer, tagger, parser, NER and word vectors 
  4. nlp = spacy.load('en_core_web_sm') 
  5. # Process whole documents 
  6. text = (u"When Sebastian Thrun started working on self-driving cars at " 
  7.  u"Google in 2007, few people outside of the company took him " 
  8.  u"seriously. “I can tell you very senior CEOs of major American " 
  9.  u"car companies would shake my hand and turn away because I wasn’t " 
  10.  u"worth talking to,” said Thrun, now the co-founder and CEO of " 
  11.  u"online higher education startup Udacity, in an interview with " 
  12.  u"Recode earlier this week.") 
  13. doc = nlp(text) 
  14. # Find named entities, phrases and concepts 
  15. for entity in doc.ents: 
  16.  print(entity.text, entity.label_) 
  17. # Determine semantic similarities 
  18. doc1 = nlp(u"my fries were super gross") 
  19. doc2 = nlp(u"such disgusting fries") 
  20. similarity = doc1.similarity(doc2) 
  21. print(doc1.text, doc2.text, similarity) 

在这个示例中,我们起首下载English tokenizer, tagger, parser, NER和word vectors。然后建设一些文本,打印找到的实体、短语和观念,最后确定两个短语的语义相似性。运行这段代码,你会获得:

  1. Sebastian Thrun PERSON 
  2. Google ORG 
  3. 2007 DATE 
  4. American NORP 
  5. Thrun PERSON 
  6. Recode ORG 
  7. earlier this week DATE 
  8. my fries were super gross such disgusting fries 0.7139701635071919 

2. jupytext

必备!人工智能和数据科学的七大 Python 库

对我来说,jupytext是年度最佳。险些全部人都在像Jupyter这样的条记本上事变,可是我们也在项目标更焦点部门行使像PyCharm这样的IDE。

好动静是,你可以在本身喜好的IDE中草拟和测试平凡剧本,在行使Jupytext时可以将IDE作为notebook在Jupyter中打开。在Jupyter中运行notebook以天生输出,关联.ipynb暗示,并作为平凡剧本或传统Jupyter notebook 举办生涯和分享。

下图展示了这个包的浸染:

可点击下方链接查察原文中的GIF展示:

https://heartbeat.fritz.ai/top-7-libraries-and-packages-of-the-year-for-data-science-and-ai-python-r-6b7cca2bf000

安装

  1. pip install jupytext --upgrade 

然后,设置Jupyter行使Jupytext:

行使jupyter notebook --generate-config天生Jupyter设置

编辑.jupyter/jupyter_notebook_config.py,并附加以下代码:

  1. c.NotebookApp.contents_manager_class = "jupytext.TextFileContentsManager" 

重启Jupyter,即运行:

  1. jupyter notebook 

你可以在这里试试:

https://mybinder.org/v2/gh/mwouts/jupytext/master?filepath=demo

1.Chartify ——让数据科学家很轻易建设图表的Python库

必备!人工智能和数据科学的七大 Python 库

https://xkcd.com/1945/

Chartify是Python的年度最佳库。

在Python天下中建设一个像样的图很费时刻。荣幸的是,我们有像Seaborn之类的库,但题目是他们的plots不是动态的。

然后就呈现了Bokeh——这是一个超棒的库,但用它来缔造互动情节仍很疾苦。

Chartify成立在Bokeh之上,但它简朴得多。

Chartify的特征:

  • 同等的输入数据名目:转换数据所需的时刻更少。全部画图函数都行使同等、整洁的输入数据名目。
  • 智能默认样式:建设大度的图表,险些不必要自界说。
  • 简朴API:API尽也许直观和轻易进修。
  • 机动性:Chartify是成立在Bokeh之上的,,以是假如你必要更多的节制,你可以行使Bokeh的API。

安装

Chartify可以通过pip安装:

  1. pip3 install chartify 

用法

假设我们想要建设这个图表:

必备!人工智能和数据科学的七大 Python 库

  1. import pandas as pd 
  2. import chartify 
  3. # Generate example data 
  4. data = chartify.examples.example_data() 

此刻,我们已经加载了一些示例数据,让我们来做一些转换:

  1. total_quantity_by_month_and_fruit = (data.groupby( 
  2.  [data['date'] + pd.offsets.MonthBegin(-1), 'fruit'])['quantity'].sum() 
  3.  .reset_index().rename(columns={'date': 'month'}) 
  4.  .sort_values('month')) 
  5. print(total_quantity_by_month_and_fruit.head()) 
  6. month fruit quantity 
  7. 0 2017-01-01 Apple 7 
  8. 1 2017-01-01 Banana 6 
  9. 2 2017-01-01 Grape 1 
  10. 3 2017-01-01 Orange 2 
  11. 4 2017-02-01 Apple 8 

此刻我们可以把它画出来:

  1. # Plot the data 
  2. ch = chartify.Chart(blank_labels=True, x_axis_type='datetime') 
  3. ch.set_title("Stacked area") 
  4. ch.set_subtitle("Represent changes in distribution.") 
  5. ch.plot.area( 
  6.  data_frame=total_quantity_by_month_and_fruit, 
  7.  x_column='month', 
  8.  y_column='quantity', 
  9.  color_column='fruit', 
  10.  stacked=True) 
  11. ch.show('png') 

超等轻易建设一个互动的plot。

更多示例:

必备!人工智能和数据科学的七大 Python 库

必备!人工智能和数据科学的七大 Python 库

必备!人工智能和数据科学的七大 Python 库

https://github.com/spotify/chartify

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读