coincheckで仮想通貨を始めてみて気づいたこと
最近何かと話題の仮想通貨を購入して気づいたことをまとめてみました.
何か参考になりそうでしたら幸いです.
coincapだと有名どころがひと目で分かる!
coincapと呼ばれるサイトで,有名な仮想通貨の現在の価格や取引量がわかります.
CoinCap.io
各種仮想通貨の推移を見たいならCoinGeckoがオススメ
https://www.coingecko.com/ja
直近7日間の推移が分かりやすく表示されていたりします.
coincheckだと操作が分かりやすい.
- 日本で各種仮想通貨を買う有名所がcoincheckがあります.
- シンプルなUIですし掲示板など様々な機能もあるので,利用してみてはいかがでしょうか?
slackbot経由でkerasを利用しようとした際にバグってしまう問題の回避策
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from slackbot.bot import Bot, listen_to from keras.layers import Dense, Activation from keras.models import Sequential # 適当なモデル model = Sequential() model.add(Dense(output_dim=64, input_dim=100)) model.add(Activation("relu")) model.add(Dense(output_dim=10)) model.add(Activation("softmax")) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) @listen_to('Hi') def hello(message): X = np.random.random((10, 100)) y_pred = model.predict_proba(X, batch_size=32) message.reply('Hi!') def run(): bot = Bot() bot.run() if __name__ == "__main__": run()
"Hi"と送ると下記エラーが発生し上手く返答してくれない.
Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/slackbot/dispatcher.py", line 55, in _dispatch_msg_handler func(Message(self._client, msg), *args) File "run.py", line 20, in hello y_pred = model.predict_proba(X, batch_size=32) File "/usr/local/lib/python2.7/site-packages/keras/models.py", line 546, in predict_proba preds = self.predict(x, batch_size, verbose) File "/usr/local/lib/python2.7/site-packages/keras/models.py", line 459, in predict return self.model.predict(x, batch_size=batch_size, verbose=verbose) File "/usr/local/lib/python2.7/site-packages/keras/engine/training.py", line 1123, in predict self._make_predict_function() File "/usr/local/lib/python2.7/site-packages/keras/engine/training.py", line 702, in _make_predict_function **kwargs) File "/usr/local/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 677, in function return Function(inputs, outputs, updates=updates) File "/usr/local/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py", line 651, in __init__ with tf.control_dependencies(self.outputs): File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3342, in control_dependencies return get_default_graph().control_dependencies(control_inputs) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3132, in control_dependencies c = self.as_graph_element(c) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2322, in as_graph_element return self._as_graph_element_locked(obj, allow_tensor, allow_operation) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2401, in _as_graph_element_locked raise ValueError("Tensor %s is not an element of this graph." % obj) ValueError: Tensor Tensor("Softmax:0", shape=(?, 10), dtype=float32) is not an element of this graph.
おそらくtensorflowのpredictを呼び出すアプリケーション部分が立ち上がっていない事が原因で,事前に無理やり呼び出してあげれば解決する.
下記例では,run()関数部分で事前に呼び出しています.これなら,Hiと返答してくれます.
nginxとかならlazy-appsオプションを設定することで事前に呼び出さなくても回避できます.
... def run(): # 事前に適当に呼び出しておく X = np.zeros((10, 100)) model.predict_proba(X, batch_size=32) bot = Bot() bot.run() ...
mecabでinput-buffer overflow問題の回避策
改行を末尾につけると解決する模様.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os message = "Hello World" # 下記警告が出て,同じ分かち書き文章が2回表示される. # input-buffer overflow. The line is split. use -b #SIZE option. print "[START] TEST1" with open("/tmp/test1", "w") as fp: fp.write(message) os.system("mecab /tmp/test1") print "[END] TEST1\n" # bオプションを追加しても同様のメッセージが追加される. # input-buffer overflow. The line is split. use -b #SIZE option. print "[START] TEST2" with open("/tmp/test2", "w") as fp: fp.write(message) os.system("mecab /tmp/test2 -b 100000") print "[END] TEST2\n" # 改行コードを入れるとでなくなる. print "[START] TEST3" with open("/tmp/test3", "w") as fp: fp.write(message + "\n") os.system("mecab /tmp/test3") print "[END] TEST3"
出力結果
[START] TEST1 Hello 名詞,固有名詞,*,*,*,*,Hello,*,*,wikipedia, World 名詞,固有名詞,組織,*,*,*,* EOS input-buffer overflow. The line is split. use -b #SIZE option. Hello 名詞,固有名詞,*,*,*,*,Hello,*,*,wikipedia, World 名詞,固有名詞,組織,*,*,*,* EOS [END] TEST1 [START] TEST2 Hello 名詞,固有名詞,*,*,*,*,Hello,*,*,wikipedia, World 名詞,固有名詞,組織,*,*,*,* EOS input-buffer overflow. The line is split. use -b #SIZE option. Hello 名詞,固有名詞,*,*,*,*,Hello,*,*,wikipedia, World 名詞,固有名詞,組織,*,*,*,* EOS [END] TEST2 [START] TEST3 Hello 名詞,固有名詞,*,*,*,*,Hello,*,*,wikipedia, World 名詞,固有名詞,組織,*,*,*,* EOS [END] TEST3
gensimのDictionaryクラスでの注意事項
gensimのDictionaryインスタンスを作った段階ではid2token値が生成されていないので注意する.
- gensim.__version__ == "0.13.2" で確認
- items() を呼び出して再度値を代入すれば良いっぽい.
>>> texts = [["a", "b", "c"], ["b", "c", "c", "d"]] >>> import gensim >>> gensim.__version__ '0.13.2' >>> dictionary = gensim.corpora.Dictionary(texts) >>> dictionary.id2token # (id,token)のペアがまだない {} >>> dictionary.items() # id2tokenやtoken2idにキャッシュするため必要. [(0, u'a'), (1, u'c'), (2, u'b'), (3, u'd')] >>> dictionary.id2token # (id,token)に再度値が突っ込まれている. {0: u'a', 1: u'c', 2: u'b', 3: u'd'}
gymでパックマンを動かしてみる.
gymとは
インストール方法
pip install gym pip install gym[atari] # パックマンが含まれている
パックマンを動かしてみる.
import gym env = gym.make('MsPacman-v0') env.reset() for _ in range(1000): env.render() env.step(env.action_space.sample())
実行結果
References
キャリブレーション(Probability Calibration)
キャリブレーション(Probability Calibration)とは
モデルによって算出された予測確率を本来の確率に近づける手法.
例えば20%の確率で正となるようなデータを学習させてみたとする.
理想の予測確率は0.2ですが,実際は0.3となるなどずれてしまうことがある.
複数のモデルを作ることで,本来の確率に近づけようとするのがキャリブレーション.
結果として損失関数値を低くする効果がある.
また,バギングに近い効果もあってか,色々と性能が上がる.
Random ForestにCalibrationを使った例
from sklearn.datasets import make_hastie_10_2 from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import train_test_split from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import (brier_score_loss, precision_score, recall_score, f1_score) def run(): X, y= make_hastie_10_2() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) for description, clf in [ ("Random Forest Without Calibration", RandomForestClassifier()), ("Random Forest With Calibration", CalibratedClassifierCV(RandomForestClassifier(), cv=5, method='isotonic'))]: clf.fit(X_train, y_train) y_preda = clf.predict_proba(X_test)[:, 1] y_pred = clf.predict(X_test) print description print "\tBrier:", brier_score_loss(y_test, y_preda) print "\tPrecision:", precision_score(y_test, y_pred) print "\tRecall:", recall_score(y_test, y_pred) print "\tF1:", f1_score(y_test, y_pred) if __name__ == "__main__": run()
Random Forest Without Calibration Brier: 0.113356060606 Precision: 0.835116731518 Recall: 0.859359359359 F1: 0.847064627528 Random Forest With Calibration Brier: 0.089109155874 Precision: 0.843904633378 Recall: 0.938938938939 F1: 0.888888888889
References
[1]. scikit learn - 1.16. Probability calibration, http://scikit-learn.org/stable/modules/calibration.html
[2]. Don't Miss These Scripts: Otto Group Product Classification, http://blog.kaggle.com/2015/06/15/dont-miss-these-scripts-otto-group-product-classification/
[3]. 6 Tricks I Learned From The OTTO Kaggle Challenge, https://medium.com/@chris_bour/6-tricks-i-learned-from-the-otto-kaggle-challenge-a9299378cd61#.1nclulkyi
DarkForestをUbuntu14.04にインストール.
先日Facebookがオープンソースとして公開した囲碁AI - DarkForest(darkforestGo)をUbutu 14.04にインストールしてみました.
のREADME.mdで説明されています.
darkforestGoのクローン
git clone https://github.com/facebookresearch/darkforestGo.git ~/darkforestGo
Torchのインストール
# install torch mkdir ~/lib curl -s https://raw.githubusercontent.com/torch/ezinstall/master/install-deps | bash git clone https://github.com/torch/distro.git ~/lib/torch --recursive cd ~/lib/torch; ./install.sh source ~/.bashrc th # torchが立ち上がるか確認
Luarocksのインストール
sudo apt-get install luarocks # 途中で質問されるのでYを選択.
各種Luaライブラリのインストール
luarocks install class luarocks install image luarocks install tds luarocks install cudnn
darkforestGoのインストール
cd ~/darkforestGo/ sh ./compile.sh
対局前の準備
mkdir ./models cd models/ wget https://www.dropbox.com/sh/6nm8g8z163omb9f/AAAOsp9WzSQrITY9veSmOA1pa/df1.bin?dl=0 -O df1.bin wget https://www.dropbox.com/sh/6nm8g8z163omb9f/AACZwAeb0OOCReoeIWPRgILta/df2.bin?dl=0 -O df2.bin wget https://www.dropbox.com/sh/6nm8g8z163omb9f/AABrO3wRZ5hLOk70gmu3rK7Ja/LICENSE?dl=0 -O LICENSE wget https://www.dropbox.com/sh/6nm8g8z163omb9f/AABcYJKMOl6-Uol98boGa7n5a/playout-model.bin?dl=0 -O playout-model.bin cd ../local_evaluator/ sudo mkdir -p /data/local/go sudo chmod 666 /data/local/go sh cnn_evaluator.sh 1 /data/local/go cd ~/darkforestGo/cnnPlayerV2/ th cnnPlayerMCTSV2.lua --num_gpu 1 --time_limit 10
対局開始
clear_board genmove b
ちなみにGoGuiでも動作するみたいです.
References
- [1]. [Vagrant上のUbuntuでTorch7のCPU開発環境を作る](http://kakakazuma.hatenablog.com/entry/2015/08/18/141927)