标签归档:深度学习

自然语言处理工具包spaCy介绍

spaCy 是一个Python自然语言处理工具包,诞生于2014年年中,号称“Industrial-Strength Natural Language Processing in Python”,是具有工业级强度的Python NLP工具包。spaCy里大量使用了 Cython 来提高相关模块的性能,这个区别于学术性质更浓的Python NLTK,因此具有了业界应用的实际价值。

安装和编译 spaCy 比较方便,在ubuntu环境下,直接用pip安装即可:

sudo apt-get install build-essential python-dev git
sudo pip install -U spacy

不过安装完毕之后,需要下载相关的模型数据,以英文模型数据为例,可以用"all"参数下载所有的数据:

sudo python -m spacy.en.download all

或者可以分别下载相关的模型和用glove训练好的词向量数据:

# 这个过程下载英文tokenizer,词性标注,句法分析,命名实体识别相关的模型
python -m spacy.en.download parser

# 这个过程下载glove训练好的词向量数据
python -m spacy.en.download glove

下载好的数据放在spacy安装目录下的data里,以我的ubuntu为例:

textminer@textminer:/usr/local/lib/python2.7/dist-packages/spacy/data$ du -sh *
776M    en-1.1.0
774M    en_glove_cc_300_1m_vectors-1.0.0

进入到英文数据模型下:

textminer@textminer:/usr/local/lib/python2.7/dist-packages/spacy/data/en-1.1.0$ du -sh *
424M    deps
8.0K    meta.json
35M ner
12M pos
84K tokenizer
300M    vocab
6.3M    wordnet

可以用如下命令检查模型数据是否安装成功:

textminer@textminer:~$ python -c "import spacy; spacy.load('en'); print('OK')"
OK

也可以用pytest进行测试:

# 首先找到spacy的安装路径:
python -c "import os; import spacy; print(os.path.dirname(spacy.__file__))"
/usr/local/lib/python2.7/dist-packages/spacy

# 再安装pytest:
sudo python -m pip install -U pytest

# 最后进行测试:
python -m pytest /usr/local/lib/python2.7/dist-packages/spacy --vectors --model --slow
============================= test session starts ==============================
platform linux2 -- Python 2.7.12, pytest-3.0.4, py-1.4.31, pluggy-0.4.0
rootdir: /usr/local/lib/python2.7/dist-packages/spacy, inifile:
collected 318 items

../../usr/local/lib/python2.7/dist-packages/spacy/tests/test_matcher.py ........
../../usr/local/lib/python2.7/dist-packages/spacy/tests/matcher/test_entity_id.py ....
../../usr/local/lib/python2.7/dist-packages/spacy/tests/matcher/test_matcher_bugfixes.py .....
......
../../usr/local/lib/python2.7/dist-packages/spacy/tests/vocab/test_vocab.py .......Xx
../../usr/local/lib/python2.7/dist-packages/spacy/tests/website/test_api.py x...............
../../usr/local/lib/python2.7/dist-packages/spacy/tests/website/test_home.py ............

============== 310 passed, 5 xfailed, 3 xpassed in 53.95 seconds ===============

现在可以快速测试一下spaCy的相关功能,我们以英文数据为例,spaCy目前主要支持英文和德文,对其他语言的支持正在陆续加入:

textminer@textminer:~$ ipython
Python 2.7.12 (default, Jul  1 2016, 15:12:24)
Type "copyright", "credits" or "license" for more information.

IPython 2.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python'
s own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import spacy          

# 加载英文模型数据,稍许等待
In [2]: nlp = spacy.load('en')

Word tokenize功能,spaCy 1.2版本加了中文tokenize接口,基于Jieba中文分词:

In [3]: test_doc = nlp(u"it's word tokenize test for spacy")            

In [4]: print(test_doc)
it's word tokenize test for spacy

In [5]: for token in test_doc:                                          
    print(token)
   ...:    
it
'
s
word
tokenize
test
for
spacy

英文断句:

In [6]: test_doc = nlp(u'Natural language processing (NLP) deals with the application of computational models to text or speech data. Application areas within NLP include automatic (machine) translation between languages; dialogue systems, which allow a human to interact with a machine using natural language; and information extraction, where the goal is to transform unstructured text into structured (database) representations that can be searched and browsed in flexible ways. NLP technologies are having a dramatic impact on the way people interact with computers, on the way people interact with each other through the use of language, and on the way people access the vast amount of linguistic data now in electronic form. From a scientific viewpoint, NLP involves fundamental questions of how to structure formal models (for example statistical models) of natural language phenomena, and of how to design algorithms that implement these models.')

In [7]: for sent in test_doc.sents:
    print(sent)
   ...:    
Natural language processing (NLP) deals with the application of computational models to text or speech data.
Application areas within NLP include automatic (machine) translation between languages; dialogue systems, which allow a human to interact with a machine using natural language; and information extraction, where the goal is to transform unstructured text into structured (database) representations that can be searched and browsed in flexible ways.
NLP technologies are having a dramatic impact on the way people interact with computers, on the way people interact with each other through the use of language, and on the way people access the vast amount of linguistic data now in electronic form.
From a scientific viewpoint, NLP involves fundamental questions of how to structure formal models (for example statistical models) of natural language phenomena, and of how to design algorithms that implement these models.


词干化(Lemmatize):

In [8]: test_doc = nlp(u"you are best. it is lemmatize test for spacy. I love these books")

In [9]: for token in test_doc:                                                      
    print(token, token.lemma_, token.lemma)
   ...:    
(you, u'you', 472)
(are, u'be', 488)
(best, u'good', 556)
(., u'.', 419)
(it, u'it', 473)
(is, u'be', 488)
(lemmatize, u'lemmatize', 1510296)
(test, u'test', 1351)
(for, u'for', 480)
(spacy, u'spacy', 173783)
(., u'.', 419)
(I, u'i', 570)
(love, u'love', 644)
(these, u'these', 642)
(books, u'book', 1011)

词性标注(POS Tagging):

In [10]: for token in test_doc:                                                    
    print(token, token.pos_, token.pos)
   ....:    
(you, u'PRON', 92)
(are, u'VERB', 97)
(best, u'ADJ', 82)
(., u'PUNCT', 94)
(it, u'PRON', 92)
(is, u'VERB', 97)
(lemmatize, u'ADJ', 82)
(test, u'NOUN', 89)
(for, u'ADP', 83)
(spacy, u'NOUN', 89)
(., u'PUNCT', 94)
(I, u'PRON', 92)
(love, u'VERB', 97)
(these, u'DET', 87)
(books, u'NOUN', 89)

命名实体识别(NER):

In [11]: test_doc = nlp(u"Rami Eid is studying at Stony Brook University in New York")

In [12]: for ent in test_doc.ents:
    print(ent, ent.label_, ent.label)
   ....:    
(Rami Eid, u'PERSON', 346)
(Stony Brook University, u'ORG', 349)
(New York, u'GPE', 350)

名词短语提取:

In [13]: test_doc = nlp(u'Natural language processing (NLP) deals with the application of computational models to text or speech data. Application areas within NLP include automatic (machine) translation between languages; dialogue systems, which allow a human to interact with a machine using natural language; and information extraction, where the goal is to transform unstructured text into structured (database) representations that can be searched and browsed in flexible ways. NLP technologies are having a dramatic impact on the way people interact with computers, on the way people interact with each other through the use of language, and on the way people access the vast amount of linguistic data now in electronic form. From a scientific viewpoint, NLP involves fundamental questions of how to structure formal models (for example statistical models) of natural language phenomena, and of how to design algorithms that implement these models.')


In [14]: for np in test_doc.noun_chunks:
    print(np)
   ....:    
Natural language processing
Natural language processing (NLP) deals
the application
computational models
text
speech
data
Application areas
NLP
automatic (machine) translation
languages
dialogue systems
a human
a machine
natural language
information extraction
the goal
unstructured text
structured (database) representations
flexible ways
NLP technologies
a dramatic impact
the way
people
computers
the way
people
the use
language
the way
people
the vast amount
linguistic data
electronic form
a scientific viewpoint
NLP
fundamental questions
formal models
example
natural language phenomena
algorithms
these models

基于词向量计算两个单词的相似度:

In [15]: test_doc = nlp(u"Apples and oranges are similar. Boots and hippos aren't.")

In [16]: apples = test_doc[0]

In [17]: print(apples)
Apples

In [18]: oranges = test_doc[2]

In [19]: print(oranges)
oranges

In [20]: boots = test_doc[6]

In [21]: print(boots)
Boots

In [22]: hippos = test_doc[8]

In [23]: print(hippos)
hippos

In [24]: apples.similarity(oranges)
Out[24]: 0.77809414836023805

In [25]: boots.similarity(hippos)
Out[25]: 0.038474555379008429

当然,spaCy还包括句法分析的相关功能等。另外值得关注的是 spaCy 从1.0版本起,加入了对深度学习工具的支持,例如 Tensorflow 和 Keras 等,这方面具体可以参考官方文档给出的一个对情感分析(Sentiment Analysis)模型进行分析的例子:Hooking a deep learning model into spaCy.

参考:
spaCy官方文档
Getting Started with spaCy

注:原创文章,转载请注明出处及保留链接“我爱自然语言处理”:http://www.52nlp.cn

本文链接地址:自然语言处理工具包spaCy介绍 http://www.52nlp.cn/?p=9386

反向传播算法入门资源索引

1、一切从维基百科开始,大致了解一个全貌:
反向传播算法 Backpropagation

2、拿起纸和笔,再加上ipython or 计算器,通过一个例子直观感受反向传播算法:
A Step by Step Backpropagation Example

3、再玩一下上篇例子对应的200多行Python代码: Neural Network with Backpropagation

4、有了上述直观的反向传播算法体验,可以从1986年这篇经典的论文入手了:Learning representations by back-propagating errors

5、如果还是觉得晦涩,推荐读一下"Neural Networks and Deep Learning"这本深度学习在线书籍的第二章:How the backpropagation algorithm works

6、或者可以通过油管看一下这个神经网络教程的前几节关于反向传播算法的视频: Neural Network Tutorial

7、hankcs 同学对于上述视频和相关材料有一个解读: 反向传播神经网络极简入门

8、这里还有一个比较简洁的数学推导:Derivation of Backpropagation

9、神牛gogo 同学对反向传播算法原理及代码解读:神经网络反向传播的数学原理

10、关于反向传播算法,更本质一个解释:自动微分反向模式(Reverse-mode differentiation )Calculus on Computational Graphs: Backpropagation

注:原创文章,转载请注明出处及保留链接“我爱自然语言处理”:http://www.52nlp.cn

本文链接地址:反向传播算法入门资源索引 http://www.52nlp.cn/?p=9350

深度学习主机环境配置: Ubuntu16.04+GeForce GTX 1080+TensorFlow

接上文《深度学习主机环境配置: Ubuntu16.04+Nvidia GTX 1080+CUDA8.0》,我们继续来安装 TensorFlow,使其支持GeForce GTX 1080显卡。

1 下载和安装cuDNN

cuDNN全称 CUDA Deep Neural Network library,是NVIDIA专门针对深度神经网络设计的一套GPU计算加速库,被广泛用于各种深度学习框架,例如Caffe, TensorFlow, Theano, Torch, CNTK等。

The NVIDIA CUDA® Deep Neural Network library (cuDNN) is a GPU-accelerated library of primitives for deep neural networks. cuDNN provides highly tuned implementations for standard routines such as forward and backward convolution, pooling, normalization, and activation layers. cuDNN is part of the NVIDIA Deep Learning SDK.

Deep learning researchers and framework developers worldwide rely on cuDNN for high-performance GPU acceleration. It allows them to focus on training neural networks and developing software applications rather than spending time on low-level GPU performance tuning. cuDNN accelerates widely used deep learning frameworks, including Caffe, TensorFlow, Theano, Torch, and CNTK. See supported frameworks for more details.

首先需要下载cuDNN,直接从Nvidia官方下载链接选择一个版本,不过下载cuDNN前同样需要登录甚至填写一个简单的调查问卷: https://developer.nvidia.com/rdp/cudnn-download,这里选择的是支持CUDA8.0的cuDNN v5版本,而支持CUDA8的5.1版本虽然显示在下载选择项里,但是提示:cuDNN 5.1 RC for CUDA 8RC will be available soon - please check back again.

屏幕快照 2016-07-17 上午11.17.39

安装cuDNN比较简单,解压后把相应的文件拷贝到对应的CUDA目录下即可:

tar -zxvf cudnn-8.0-linux-x64-v5.0-ga.tgz

cuda/include/cudnn.h
cuda/lib64/libcudnn.so
cuda/lib64/libcudnn.so.5
cuda/lib64/libcudnn.so.5.0.5
cuda/lib64/libcudnn_static.a

sudo cp cuda/include/cudnn.h /usr/local/cuda/include/
sudo cp cuda/lib64/libcudnn* /usr/local/cuda/lib64/
sudo chmod a+r /usr/local/cuda/include/cudnn.h
sudo chmod a+r /usr/local/cuda/lib64/libcudnn*

继续阅读

深度学习主机环境配置: Ubuntu16.04+Nvidia GTX 1080+CUDA8.0

接上文《深度学习主机攒机小记》,这台GTX1080主机准备好之后,就是配置深度学习环境了,这里选择了比较熟悉Ubuntu系统,不过是最新的16.04版本,另外在Nvidia GTX1080的基础上安装相关GPU驱动,外加CUDA8.0,因为都比较新,所以踩了很多坑。

1. 安装Ubuntu16.04

不考虑双系统,直接安装 Ubuntu16.04,从ubuntu官方下载64位版本: ubuntu-16.04-desktop-amd64.iso 。

在MAC下制作了 Ubuntu USB 安装盘,具体方法可参考: 在MAC下使用ISO制作Linux的安装USB盘,之后通过Bios引导U盘启动安装Ubuntu系统:

1)一开始安装就踩了一个坑,选择"Install Ubuntu"回车后过一会儿屏幕显示“输入不支持”,google了好多方案,最终和ubuntu对显卡的支持有关,需要手动添加显卡选项: nomodeset,使其支持Nvidia系列显卡,参考:安装ubuntu黑屏问题的解决 or How do I set 'nomodeset' after I've already installed Ubuntu?

2) 磁盘分区,全部干掉之前主机自带的Window 10系统,分区为 /boot, /, /home 等几个目录,同时把第二块4T硬盘也挂载了上去,作为数据盘。

3)安装完毕后Ubuntu 16.04的分辨率很低,在显卡驱动未安装之前,可以手动修改一下grub文件:

sudo vim /etc/default/grub

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480
# 这里分辨率自行设置
GRUB_GFXMODE=1024x768

sudo update-grub

4)安装SSH Server,这样可以远程ssh访问这台GTX1080主机:

sudo apt-get install openssh-server

5)更新Ubuntu16.04源,用的是中科大的源

cd /etc/apt/
sudo cp sources.list sources.list.bak
sudo vi sources.list

把下面的这些源添加到source.list文件头部:

deb http://mirrors.ustc.edu.cn/ubuntu/ xenial main restricted universe multiverse
deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-security main restricted universe multiverse
deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-updates main restricted universe multiverse
deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-proposed main restricted universe multiverse
deb http://mirrors.ustc.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse
deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial main restricted universe multiverse
deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-security main restricted universe multiverse
deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-updates main restricted universe multiverse
deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-proposed main restricted universe multiverse
deb-src http://mirrors.ustc.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse

最后更新源和更新已安装的包:

sudo apt-get update
sudo apt-get upgrade
继续阅读

深度学习主机攒机小记

五月中下旬的时候,GTX1080的公布和发售直接刺激了我攒一台深度学习主机的欲望,攒机对于我来说已经相隔十多年,大学时候的第一台PC就是攒出来的,其实也就是在5000元的预算内,去电脑城里找商家组装了一台台式机,美其名曰DIY。

虽然已经锁定显卡,但是对于其他的搭配还是很模糊,只是需要“好CPU”,“大内存", “大硬盘", 于是开始google “深度学习电脑”,“深度学习服务器”,“深度学习PC”, “深度学习主机”,“深度学习机器”,“深度学习工作站”这些关键词,并很快锁定了这篇文章《如何搭建一台深度学习服务器》作为主要参考:

硬件选择:基本思路是单显卡机器,保留升级空间

......

CPU选择:
在深度学习任务中,CPU并不负责主要任务,单显卡计算时只有一个核心达到100%负荷,所以CPU的核心数量和显卡数量一致即可,太多没有必要,但是处理PCIE的带宽要到40。

主板选择:
需要支持X99架构,支持PCIe3.0,还要支持4通道DDR4内存架构。如果要搞四显卡并行,PCIE带宽支持要达到40,并且支持4-Way NVIDA SLI技术。

内存:
达到显存的二倍即可,当然有钱的话越大越好。

电源问题:一个显卡的功率接近300W,四显卡建议电源在1500W以上,为了以后扩展,选择了1600W的电源。

机箱散热:
因为各种部件相当庞大,需要有良好散热功能的大机箱,选择了Tt Thermaltake Core V51机箱,标配3个12cm风扇。未来如果需要还可以加装水冷设备。

......

最后的硬件配置:
CPU: Intel X99平台 i7 5960K
内存: DDR4 2800 32G(8G*4)
主板: GIGABYTE X99-UD4
显卡: GTX Titan X
硬盘: SSD+普通硬盘

继续阅读

斯坦福大学深度学习与自然语言处理第四讲:词窗口分类和神经网络

斯坦福大学在三月份开设了一门“深度学习与自然语言处理”的课程:CS224d: Deep Learning for Natural Language Processing,授课老师是青年才俊 Richard Socher,以下为相关的课程笔记。

第四讲:词窗口分类和神经网络(Word Window Classification and Neural Networks)

推荐阅读材料:

  1. [UFLDL tutorial]
  2. [Learning Representations by Backpropogating Errors]
  3. 第四讲Slides [slides]
  4. 第四讲视频 [video]

以下是第四讲的相关笔记,主要参考自课程的slides,视频和其他相关资料。
继续阅读

斯坦福大学深度学习与自然语言处理第三讲:高级的词向量表示

斯坦福大学在三月份开设了一门“深度学习与自然语言处理”的课程:CS224d: Deep Learning for Natural Language Processing,授课老师是青年才俊 Richard Socher,以下为相关的课程笔记。

第三讲:高级的词向量表示(Advanced word vector representations: language models, softmax, single layer networks)

推荐阅读材料:

  1. Paper1:[GloVe: Global Vectors for Word Representation]
  2. Paper2:[Improving Word Representations via Global Context and Multiple Word Prototypes]
  3. Notes:[Lecture Notes 2]
  4. 第三讲Slides [slides]
  5. 第三讲视频 [video]

以下是第三讲的相关笔记,主要参考自课程的slides,视频和其他相关资料。
继续阅读

斯坦福大学深度学习与自然语言处理第二讲:词向量

斯坦福大学在三月份开设了一门“深度学习与自然语言处理”的课程:CS224d: Deep Learning for Natural Language Processing,授课老师是青年才俊 Richard Socher,以下为相关的课程笔记。

第二讲:简单的词向量表示:word2vec, Glove(Simple Word Vector representations: word2vec, GloVe)

推荐阅读材料:

  1. Paper1:[Distributed Representations of Words and Phrases and their Compositionality]]
  2. Paper2:[Efficient Estimation of Word Representations in Vector Space]
  3. 第二讲Slides [slides]
  4. 第二讲视频 [video]

以下是第二讲的相关笔记,主要参考自课程的slides,视频和其他相关资料。
继续阅读

斯坦福大学深度学习与自然语言处理第一讲:引言

斯坦福大学在三月份开设了一门“深度学习与自然语言处理”的课程:CS224d: Deep Learning for Natural Language Processing,授课老师是青年才俊 Richard Socher,他本人是德国人,大学期间涉足自然语言处理,在德国读研时又专攻计算机视觉,之后在斯坦福大学攻读博士学位,拜师NLP领域的巨牛 Chris ManningDeep Learning 领域的巨牛 Andrew Ng,其博士论文是《Recursive Deep Learning for Natural Language Processing and Computer Vision》,也算是多年求学生涯的完美一击。毕业后以联合创始人及CTO的身份创办了MetaMind,作为AI领域的新星创业公司,MetaMind创办之初就拿了800万美元的风投,值得关注。

回到这们课程CS224d,其实可以翻译为“面向自然语言处理的深度学习(Deep Learning for Natural Language Processing)”,这门课程是面向斯坦福学生的校内课程,不过课程的相关材料都放到了网上,包括课程视频,课件,相关知识,预备知识,作业等等,相当齐备。课程大纲相当有章法和深度,从基础讲起,再讲到深度学习在NLP领域的具体应用,包括命名实体识别,机器翻译,句法分析器,情感分析等。Richard Socher此前在ACL 2012和NAACL 2013 做过一个Tutorial,Deep Learning for NLP (without Magic),感兴趣的同学可以先参考一下: Deep Learning for NLP (without Magic) - ACL 2012 Tutorial - 相关视频及课件 。另外,由于这门课程的视频放在Youtube上,@爱可可-爱生活 老师维护了一个网盘链接:http://pan.baidu.com/s/1pJyrXaF ,同步更新相关资料,可以关注。
继续阅读

中英文维基百科语料上的Word2Vec实验

最近试了一下Word2Vec, GloVe 以及对应的python版本 gensim word2vecpython-glove,就有心在一个更大规模的语料上测试一下,自然而然维基百科的语料进入了视线。维基百科官方提供了一个很好的维基百科数据源:https://dumps.wikimedia.org,可以方便的下载多种语言多种格式的维基百科数据。此前通过gensim的玩过英文的维基百科语料并训练LSI,LDA模型来计算两个文档的相似度,所以想看看gensim有没有提供一种简便的方式来处理维基百科数据,训练word2vec模型,用于计算词语之间的语义相似度。感谢Google,在gensim的google group下,找到了一个很长的讨论帖:training word2vec on full Wikipedia ,这个帖子基本上把如何使用gensim在维基百科语料上训练word2vec模型的问题说清楚了,甚至参与讨论的gensim的作者Radim Řehůřek博士还在新的gensim版本里加了一点修正,而对于我来说,所做的工作就是做一下验证而已。虽然github上有一个wiki2vec的项目也是做得这个事,不过我更喜欢用python gensim的方式解决问题。

关于word2vec,这方面无论中英文的参考资料相当的多,英文方面既可以看官方推荐的论文,也可以看gensim作者Radim Řehůřek博士写得一些文章。而中文方面,推荐 @licstar的《Deep Learning in NLP (一)词向量和语言模型》,有道技术沙龙的《Deep Learning实战之word2vec》,@飞林沙 的《word2vec的学习思路》, falao_beiliu 的《深度学习word2vec笔记之基础篇》和《深度学习word2vec笔记之算法篇》等。
继续阅读