ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

最近のことをつらつらと

  • 4ヶ月前74kg。8kg痩せた。現在66kg
    • お金なかったから牛丼やらラーメンやら酒飲まなくなったら痩せた
    • 卵と豆腐ばっか食ってたら痩せた
    • 沖縄いるとき頑張って走っていたけど、結局のところ食事制限でどうにかなるのね
    • 今お金あるから戻らないようにジムで調整中
  • データサイエンティストってどんな感じ?
    • 前処理9割 + 分析1割で地味な感じです
    • 統計の知識学べるでしょ?と思いきや、入社してからほぼディープラーニングしかしていないので統計基礎弱い
    • ディープラーニングはハイパーパラメータとの戦い
    • 最近数式でロジック考えてたらハッとした。苦手だったのに。これが環境変化か
    • でもまぁ、Pythonは楽しい。Rはさわる業務が来ていないのでほとんど触っていない

そろそろ沖縄帰ります。

【Python】Tensorflowでresizeした画像をmatplotlibで表示したい

>>> import matplotlib
>>> import matplotlib.pyplot as plt
>>> import tensorflow as tf
>>> tf.__version__
'1.1.0'
>>> matplotlib.__version__
'2.0.0'

Tensorflowの画像前処理関数って結構豊富っぽくて使いたいって練習しようとしてた。

https://www.tensorflow.org/api_docs/python/tf/image/resize_images

単純にresizeしたいと思って↑の関数を使う。

# image -> opencvとかで読み込んだ画像
>>> tf_image = tf.image.resize_images(image, [100, 100])
>>> session = tf.Session()
>>> with session.as_default():
...     output = tf_image.eval()
...
>>> plt.imshow(output)
>>> plt.show()

そしたら、反転?みたいな画像がでてきて困惑。

なーぜー?

stackoverflow.com

matplotlibでtensorを表示するためには、tf.float32でcastしたあとに255.0で割ってあげればおk

>>> image = tf.cast(image, tf.float32) / 255.0
>>> tf_image = tf.image.resize_images(tf_image, [100, 100])
>>> session = tf.Session()
>>> with session.as_default():
...     output = tf_image.eval()
...
>>> plt.imshow(output)
>>> plt.show()

これで閲覧できた。

そもそもmatplotlibじゃなくて、tensorboardでみればいいのでは?

・・・・。(試してないからわからんけど)

【Python】kerasで保存したweightsをh5pyを使って取得する

難しかった。(というかこのファイル構造よくわからん)

$ ls
model_weights.h5 # kerasで保存したファイル
$ python
# ...
>>> import h5py

>>> model_weights = h5py.File('./model_weights.h5', 'r')
>>> model_weights.keys()
KeysView(<Attributes of HDF5 object at 4383104920>) # (´・ω・`)?

>>> model_weights.attrs.keys()
KeysView(<Attributes of HDF5 object at 4383104920>) # (´;ω;`)?

>>> list(model_weights.attrs.keys())
['layer_names', 'backend', 'keras_version'] # (`・ω・’)!

>>> list(model_weights.attrs.get('layer_names'))
[b'dense_1', b'activation_1', b'dropout_1', b'dense_2', b'activation_2', b'dropout_2', b'dense_3', b'activation_3'] # (`・ω・’)

>>> list(model_weights.attrs.get('layer_names'))[0]
b'dense_1' # (´・ω・`)?

>>> # .....悩み中

>>> # !? そういえばattrs無しで試していない!

>>> list(model_weights)
['activation_1', 'activation_2', 'activation_3', 'dense_1', 'dense_2', 'dense_3', 'dropout_1', 'dropout_2'] # うぉおおお!!!

>>> list(model_weights)['dense']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str # (´・ω・`)

>>> list(model_weights.get('dense_1'))
['dense_1'] # !? なにこれ・・・?

>>> model_weights['dense_1'].keys()
KeysView(<HDF5 group "/dense_1" (1 members)>) # わけわかめ

>>> model_weights['dense_1'].get('dense_1')
<HDF5 group "/dense_1/dense_1" (2 members)> # !? なるほど...

>>> list(array.get('dense_1').keys())
['bias:0', 'kernel:0']

>>> array.get('dense_1').get('bias:0')
<HDF5 dataset "bias:0": shape (512,), type "<f4">

>>> array.get('dense_1').get('bias:0')[()]
array([ -5.14987158e-04,  -1.05651123e-02,  -6.37231674e-03,
# ...
         1.46674449e-02,  -1.39807556e-02], dtype=float32) # ヾ(*´∀`*)ノキャッキャ

>>> np_array = array.get('dense_1').get('bias:0')[()]
>>> np_array.shape
(512,)

ちなみにpipでインストールすることができます。

$ pip install h5py

【Python】Cython試してみた

Jupyterではマジックコマンド?を書けばすぐ実行できるけど、コマンドラインから実行するやりかたがわからなかったのでメモ。

  • setup.py
# -*- coding:utf-8 -*-

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
from Cython.Compiler import Options
import numpy

Options.annotate = True

ext_modules = [Extension('example_cython', ['example.py'], language='c++')]

setup(cmdclass={'build_ext': build_ext}, ext_modules=ext_modules, include_dirs = [numpy.get_include()])

これで実行する。

$ python setup.py build_ext --inplace

いろいろできている。

$ ls -lt
-rw-r--r--  1 user staff       141  5 22 18:42 example.py
-rwxr-xr-x  1 user staff    159116  5 22 18:39 example_cython.cpython-36m-darwin.so
drwxr-xr-x  3 user staff       102  5 22 18:39 build
-rw-r--r--  1 user staff    376329  5 22 18:39 example.html
-rw-r--r--  1 user staff    414963  5 22 18:39 example.cpp
-rw-r--r--  1 user staff       403  5 22 18:39 setup.py

soファイルをリネームする

$ mv example.cpython-36m-darwin.so example_cython

pythonで読み込んでみる

$ python
>>> import example_cython

これでおk.あとは普通にpythonから使えるようになる(はず)

ちなみに、速度はそんなにかわりませんでした・・・なぜ?