python3のfalconでapiをサクッと作成してみる。
環境
CentOS6
python3.5.1
falcon-1.0.0
手順
falconインストール
pip install --upgrade falcon
テスト用コード
vi falcon_test.py
# -*- coding: utf-8 -*- # sample.py import falcon import json class ItemsResource: def on_get(self, req, resp): value = req.params['key'] items = { 'title': 'WebAPIテスト', 'tags': [ { 'name': 'テスト','バージョン':[] }, { 'name': 'request', value:[] } ] } print(req.headers) resp.status = falcon.HTTP_200 resp.content_type = 'text/plain' resp.body = json.dumps(items,ensure_ascii=False) def on_post(self, req, resp): params = req.stream.read().decode('utf-8') items = { 'title': 'WebAPI(POST)', 'tags': [ { 'name': 'テスト','バージョン':[] }, { 'name': 'request', params:[] } ] } resp.status = falcon.HTTP_200 resp.content_type = 'text/plain' resp.body = json.dumps(items,ensure_ascii=False) api = falcon.API() api.add_route('/test_api', ItemsResource()) if __name__ == "__main__": from wsgiref import simple_server httpd = simple_server.make_server("127.0.0.1", 8008, api) httpd.serve_forever()
起動してみる
※BGプロセスで起動
python falcon_test.py &
curlでアクセスしてみる
get
[root@localhost falcon]# curl http://localhost:8008/test_api?key=TEST {'ACCEPT': '*/*', 'CONTENT-TYPE': 'text/plain', 'CONTENT-LENGTH': '', 'HOST': 'localhost:8008', 'USER-AGENT': 'curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.21 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2'} 127.0.0.1 - - [14/Sep/2016 22:32:37] "GET /test_api?key=TEST HTTP/1.1" 200 117 {"tags": [{"バージョン": [], "name": "テスト"}, {"TEST": [], "name": "request"}], "title": "WebAPIテスト"}
post
[root@localhost falcon]# curl -d "kkk=value1" http://localhost:8008/test_api 127.0.0.1 - - [14/Sep/2016 22:57:48] "POST /test_api HTTP/1.1" 200 120 {"tags": [{"name": "テスト", "バージョン": []}, {"name": "request", "kkk=value1": []}], "title": "WebAPI(POST)"}
出来た。
すごい簡単、30分位で出来た。
CentOSでpyenvとはpythonをインストールしてpython環境を構築する
環境
CentOS6
はじめに
勝手な解釈をすると、
pyenv
pyenvとはpythonのバージョンを複数同居させる際にデフォルトのpythonバージョンを自由に切り替える事が出来るもの。
pythonは2系と3系で互換性が無い為、バージョンが異なるpythonを実行する際に切り替えたりする。
virtualenv
virtualenvとはプロジェクト毎に違うバージョンを使い分けたい時などに、ディレクトリ毎にバージョンを切り替える事が出来る。
pyenvと組み合わせて利用する?
手順
pyenvインストール
git clone https://github.com/yyuu/pyenv.git ~/.pyenv
bash_profile編集
vi ~/.bash_profile
追記
export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init -)"
設定反映
source ~/.bash_profile exec $SHELL -l
バージョン確認
pyenv -v pyenv 1.0.0-35-g8305eae
続いてvirtualenvのインストール
git clone https://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv
bash_profile編集
vi ~/.bash_profile
追記
eval "$(pyenv virtualenv-init -)"
設定反映
source ~/.bash_profile exec $SHELL -l
インストール完了
実際にpyenvを使ってみる
インストール可能なディストリビューション、バージョンのリスト確認
pyenv install -l
バージョンを指定してインストール
pyenv install 2.7.10 pyenv install 3.5.0
インストールしたバージョンのリスト確認
pyenv versions * system (set by /root/.pyenv/version) 2.7.10 3.5.0
デフォルトで使用するバージョンの変更
pyenv global 3.5.0
変更後バージョンを確認
python -V Python 3.5.0
続いてvirtualenvを利用してみる
試しに、test_envというpython環境をバージョン3.5.1を指定して作成する
pyenv virtualenv 3.5.0 test_env
何かメッセージ出たけどスルーして良いみたい?
Ignoring indexes: https://pypi.python.org/simple Requirement already satisfied (use --upgrade to upgrade): setuptools in /root/.pyenv/versions/3.5.0/envs/test_env/lib/python3.5/site-packages Requirement already satisfied (use --upgrade to upgrade): pip in /root/.pyenv/versions/3.5.0/envs/test_env/lib/python3.5/site-packages [
作成された事を確認
pyenv versions system 2.7.10 * 3.5.0 (set by /root/.pyenv/version) 3.5.0/envs/test_env 3.5.0/envs/test_hoge test_env
ディレクトリ作成
mkdir -p ~/work/new_project && cd ~/work/new_project/
test_env環境を指定
pyenv local test_env
コンソールはじめに(test_env)って文字列が表示される
(test_env) [root@localhost new_project]#
環境を指定したディレクトリには.python-versionってファイルが作成される
ls -a .python-version .python-version
バージョン確認
python -V Python 3.5.0
環境削除
pyenv uninstall test_env pyenv-virtualenv: remove /root/.pyenv/versions/3.5.0/envs/test_env? y
削除された事を確認
[root@localhost work]# pyenv versions system 2.7.10 * 3.5.0 (set by /root/.pyenv/version) 3.5.0/envs/test_hoge
ちなみにpython_pathは以下らしい
~/.pyenv/versions/3.5.0/lib/python3.5/
CentOSでpython3からgensimのdoc2vecを使ってみる(カスタマイズ無し)
環境
CentOS6
Python3.5
手順
toriaezu-engineer.hatenablog.com
前回の記事のdoc2vecではデフォルトのdoc2vec,word2vecをカスタマイズするものであり、色々ハマったりWarningログが解決出来なかったのでカスタマイズ無しで使用する方法を調査。
doc2vec利用にあたり依存ライブラリ等のインストールは上記記事参照。
ここにチュートリアルっぽいコードあったのでこれを参考にしてみる。
gensim doc2vec tutorial · GitHub
以下のコードならデフォルトのdoc2vecを修正しなくても動いた。
(よくわかってない)
from gensim import models sentence = models.doc2vec.LabeledSentence( words=[u'犬', u'今日', u'吠えた'], tags=["SENT_0"]) sentence1 = models.doc2vec.LabeledSentence( words=[u'猫', u'明日', u'吠えた'], tags=["SENT_1"]) sentence2 = models.doc2vec.LabeledSentence( words=[u'今', u'猫', u'魚'], tags=["SENT_2"]) sentence3 = models.doc2vec.LabeledSentence( words=[u'魚', u'泳ぐ', u'海'], tags=["SENT_3"]) sentences = [sentence, sentence1, sentence2, sentence3] class LabeledLineSentence(object): def __init__(self, filename): self.filename = filename def __iter__(self): for uid, line in enumerate(open(filename)): yield LabeledSentence(words=line.split(), labels=['SENT_%s' % uid]) model = models.Doc2Vec(alpha=.025, min_alpha=.025, min_count=1) model.build_vocab(sentences) for epoch in range(10): model.train(sentences) model.alpha -= 0.002 # decrease the learning rate` model.min_alpha = model.alpha # fix the learning rate, no decay model.save("my_model.doc2vec") model_loaded = models.Doc2Vec.load('my_model.doc2vec') # ある文書に似ている文書を表示 print ("SENT_0") print (model.docvecs.most_similar(["SENT_0"]) ) print ("SENT_3") print (model.docvecs.most_similar(["SENT_3"]) ) print ("SENT_1") print (model_loaded.docvecs.most_similar(["SENT_1"]) ) # ある単語に類似した単語を取得 print (model.similar_by_word(u"魚"))
CentOSでpython3からgensimのdoc2vecを使ってみる
環境
VMware Player(CentOS6)
python3.5
手順
こちらのsatomacotoさんの記事を参考に進めます。
satomacoto: doc2vecに類似ラベル・ワードを探すメソッドの追加
gensimのdoc2vecを利用します。
ライブラリをインストール
[root@localhost ~]# pip3.5 install scipy [root@localhost ~]# pip3.5 install gensim
編集
[root@localhost doc2vec]# vi /usr/local/python/lib/python3.5/site-packages/gensim/models/doc2vec.py [root@localhost doc2vec]# vi /usr/local/python/lib/python3.5/site-packages/gensim/models/word2vec.py
https://github.com/satomacoto/gensim/blob/develop/gensim/models/doc2vec.py
https://github.com/satomacoto/gensim/blob/develop/gensim/models/word2vec.py
をコピー上書き
https://github.com/satomacoto/gensim/archive/doc2vec-mostSimilarWordsAndLabels.zip
から取得
こんなコードで実行
import gensim sentences = [ ['human', 'interface', 'computer'], #0 ['survey', 'user', 'computer', 'system', 'response', 'time'], #1 ['eps', 'user', 'interface', 'system'], #2 ['system', 'human', 'system', 'eps'], #3 ['user', 'response', 'time'], #4 ['trees'], #5 ['graph', 'trees'], #6 ['graph', 'minors', 'trees'], #7 ['graph', 'minors', 'survey'] #8 ] labeledSentences = gensim.models.doc2vec.LabeledListSentence(sentences) model = gensim.models.doc2vec.Doc2Vec(labeledSentences, min_count=0) # ラベル一覧を取得 print("-------------------------------------") print (model.labels) # ある文書に似ている文書を表示 print("-------------------------------------") print( model.most_similar_labels('SENT_0') ) #print( model.most_similar_labels('SENT_doc1')) # ある文書に似ている単語を表示 print("-------------------------------------") print( model.most_similar_words('human')) #print( model.most_similar_words('SENT_doc1')) # 複数の文書を加算減算した上で、似ているユーザーを表示 print("-------------------------------------") print( model.most_similar_labels(positive=['SENT_1', 'SENT_2'], negative=['SENT_3'], topn=5)) # 複数の文書を加算減算した上で、似ている単語を表示 print("-------------------------------------") print( model.most_similar_words(positive=['SENT_1', 'SENT_2'], negative=['SENT_3'], topn=5))
実行できた
[root@localhost doc2vec]# python3.5 doc2vec_test.py /usr/local/python/lib/python3.5/site-packages/gensim/models/word2vec.py:406: UserWarning: C extension compilation failed, training will be slow. Install a C compiler and reinstall gensim for fast training. warnings.warn("C extension compilation failed, training will be slow. Install a C compiler and reinstall gensim for fast training.") ------------------------------------- {'SENT_6', 'SENT_2', 'SENT_3', 'SENT_0', 'SENT_8', 'SENT_4', 'SENT_7', 'SENT_5', 'SENT_1'} ------------------------------------- [('SENT_4', 0.08399386703968048), ('SENT_8', 0.037913162261247635), ('SENT_3', 0.005189023911952972), ('SENT_6', 0.0002727136015892029), ('SENT_1', -0.011086158454418182), ('SENT_7', -0.03499444201588631), ('SENT_5', -0.09205912053585052), ('SENT_2', -0.14769448339939117)] ------------------------------------- [('minors', 0.15428760647773743), ('time', 0.059314027428627014), ('user', 0.05201921612024307), ('eps', 0.047635387629270554), ('survey', 0.04624335467815399), ('computer', 0.04234649986028671), ('trees', 0.038701750338077545), ('interface', 0.03709424287080765), ('graph', 0.027377430349588394), ('system', 0.019210100173950195)] ------------------------------------- [('SENT_7', 0.08965814858675003), ('SENT_8', 0.06112371012568474), ('SENT_4', 0.028300214558839798), ('SENT_5', -0.037105970084667206), ('SENT_6', -0.047132231295108795)] ------------------------------------- [('system', 0.07341058552265167), ('time', 0.059994593262672424), ('graph', 0.042242251336574554), ('survey', 0.028702296316623688), ('human', -0.020748157054185867)]
何か警告出たけど
/usr/local/python/lib/python3.5/site-packages/gensim/models/word2vec.py:406: UserWarning: C extension compilation failed, training will be slow. Install a C compiler and reinstall gensim for fast training. warnings.warn("C extension compilation failed, training will be slow. Install a C compiler and reinstall gensim for fast training.")
https://teratail.com/questions/14400
を参考にしてみる。
[root@localhost doc2vec]# pip3.5 freeze | grep scipy You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. scipy==0.18.0 [root@localhost doc2vec]# pip3.5 freeze | grep gensim You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. gensim==0.13.2
バージョンを指定してscipyを再インストール
[root@localhost doc2vec]# pip3.5 install --no-cache-dir scipy==0.15.1 File "scipy/linalg/setup.py", line 18, in configuration raise NotFoundError('no lapack/blas resources found') numpy.distutils.system_info.NotFoundError: no lapack/blas resources found ---------------------------------------- Rolling back uninstall of scipy Command "/usr/local/python/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-i9p4bki3/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-15nnf0lm-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-i9p4bki3/scipy/ You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command.
pipのバージョンが古いって怒られたのでpipをアップグレード
[root@localhost doc2vec]# pip3.5 install --upgrade pip
scipy再インストールでまたエラー
[root@localhost doc2vec]# pip3.5 install --no-cache-dir scipy==0.15.1 File "scipy/linalg/setup.py", line 18, in configuration raise NotFoundError('no lapack/blas resources found') numpy.distutils.system_info.NotFoundError: no lapack/blas resources found ---------------------------------------- Rolling back uninstall of scipy Command "/usr/local/python/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-dfyj3acv/scipy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-vqi9ewwj-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-dfyj3acv/scipy/
依存ライブラリをダウンロード
[root@localhost doc2vec]# yum install atlas-devel lapack-devel blas-devel
3度目の正直・・・
[root@localhost doc2vec]# pip3.5 install --no-cache-dir scipy==0.15.1 Collecting scipy==0.15.1 Downloading scipy-0.15.1.tar.gz (11.4MB) 100% |████████████████████████████████| 11.4MB 3.7MB/s Installing collected packages: scipy Found existing installation: scipy 0.18.0 Uninstalling scipy-0.18.0: Successfully uninstalled scipy-0.18.0 Running setup.py install for scipy ... done Successfully installed scipy-0.15.1
インストール出来た!
10分位掛かった。
でdoc2vec
また警告発生する・・
[root@localhost doc2vec]# python3.5 doc2vec_test.py /usr/local/python/lib/python3.5/site-packages/gensim/models/word2vec.py:406: UserWarning: C extension compilation failed, training will be slow. Install a C compiler and reinstall gensim for fast training. warnings.warn("C extension compilation failed, training will be slow. Install a C compiler and reinstall gensim for fast training.")
とりあえずdoc2vec動いたから良しとしようか・・
CentOSでpython3からgensimのword2vecを使ってみる
環境
VMware PlayerのCentOS6
手順
学習データにはWikipediaのデータを利用。
ライブラリをpipインストール
pip install numpy pip install scipy pip install --upgrade gensim
wp2txtインストール
CentOSにwp2txtインストール - とりあえずシステムエンジニアの備忘録
Wikipediaデータのダウンロード
wget http://dumps.wikimedia.org/jawiki/latest/jawiki-latest-pages-articles.xml.bz2
wikipediaデータをパース
wp2txt --input-file jawiki-latest-pages-articles.xml.bz2
パース結果を結合
cat jawiki-latest-pages-articles.xml-* > /work/word2vec/corpus.txt
[root@localhost word2vec]# mecab -Owakati corpus.txt -o corpus_wakati.txt input-buffer overflow. The line is split. use -b #SIZE option.
エラーが多発するので、デフォルトの10倍にバッファサイズを設定
30分位
[root@localhost word2vec]# mecab -b 81920 -Owakati corpus.txt -o corpus_wakati.txt
学習を実行しモデル作成。
[root@localhost word2vec]# python3.5 word2vec_sample.py
ソース
from gensim.models import word2vec # 学習 sentences = word2vec.Text8Corpus("corpus_wakati.txt") model = word2vec.Word2Vec(sentences, size=100) # モデルの保存と読込 model.save("sample.model")
Wikipediaデータは6.2GB
VMWare環境、8GBメモリで7時間近くかかった。
時間かかりすぎ・・
では使ってみる
こんな感じ
def load_model(): global model timeStart = time.clock(); model = word2vec.Word2Vec.load("sample.model") timeTotal = round(time.clock() - timeStart, 3) print("load model ... {0}s".format(timeTotal)) def print_result(out): print("-----") for x in out: for y in x: try: print (y, '\t') except KeyError: print("not found : " + y) try: load_model() #よく一緒に使われる(距離が近い)単語を3つ取得 out = model.most_similar(positive=[u'ピカチュウ'], topn=3) print_result(out) #単語を足して、それらとよく使われる単語を取得 out = model.most_similar(positive=[u'ピカチュウ', u'進化'], topn=5) print_result(out) #単語から単語を引いた意味を取得 out = model.most_similar(positive=[u'ピカチュウ', u'モンスター'], negative=[u'ポケモン'], topn=5) print_result(out)
読み込み時間10秒近く掛かる、遅すぎ・・・
word2vec使って色々出来そうで面白そう