【Python】数字認識APIを使って実感

# 機械学習といえばPython
- Pythonには機械学習に関するライブラリが豊富にそろっていて、初心者でも簡単に使い始められることが理由の１つ
- 使用するパッケージ
    - tensorflow：機械学習に関連するもの
    - Flask：Webアプリ化するためのもの

        ```
pip install tensorflow==1.12.0 keras matplotlib
pip install Flask flask-cors
```

# Jupyter Notebookで機械学習（Google Colaboratoryを使用）
ノートブック場で機械学習を動かして、数字画像を認識させてみる。
ipython.notebookがどうもうまく動作しない。。。
ので、結局CentOS7に jupyter notebookをインストールして検証

```:処理１
# (1) 学習済みモデルの読み込み
from keras.models import load_model
model = load_model('/content/drive/My Drive/Colab Notebooks/cnn.h5')

# (2) MNISTテスト画像の読み込み
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
test_images = test_images.astype('float32') / 255

# (3) 予測する画像を表示
%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(test_images[0], cmap='gray_r')

# (4) 機械学習モデルによる予測
import numpy as np
pred = model.predict(test_images[0].reshape(1, 28, 28, 1))
print(pred)
#=> [[6.83331218e-11 9.19927301e-10 5.45313406e-10 3.99958111e-09 1.16873996e-14
#     2.17858523e-10 2.98024704e-16 1.00000000e+00 2.00886807e-10 4.71085215e-09]]
print(np.argmax(pred)) #=> 7
```

<img width="273" alt="Untitled3_ipynb_-_Colaboratory.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/141308/79ad12ab-30d9-7b75-45a8-6819a2809328.png">

```:処理２
# (1) Canvasを表示する HTML
html = '''
<canvas width="280" style="border:solid"></canvas>
<script type="text/javascript">
    var pixels = [];
    for (var i = 0; i < 28 * 28; i++) pixels[i] = 0;
    var canvas = document.querySelector("canvas");
    var drawing = false;
    
    canvas.addEventListener("mousedown", function() {
      drawing = true;
    });
    
    canvas.addEventListener("mouseup", function() {
      drawing = false;
      IPython.notebook.kernel.execute("image = [" + pixels + "]");  # <<-- Google Colab
ではここがどうしても動かない
    });
    
    canvas.addEventListener("mousemove", function(e) {
      if (drawing) {
        var x = Math.floor(e.offsetX / 10);
        var y = Math.floor(e.offsetY / 10);
        if (0 <= x && x <= 27 && 0 <= y && y <= 27) {
          canvas.getContext("2d").fillRect(x*10, y*10, 10, 10);
          pixels[x+y*28] = 1;
        }
      }
    });
</script>
'''

# (2) HTMLの実行
from IPython.display import HTML
HTML(html)
```
<img width="300" alt="image.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/141308/05aa8c6f-779c-da90-e415-480783716aaf.png">

```:処理３
# 機械学習モデルによる予測
img = np.array(image, dtype=np.float32)  <<-- 処理２で書いた文字を認識できない
pred = model.predict(img.reshape(1, 28, 28, 1))
print(np.argmax(pred)) #=> 9
```
<img width="449" alt="image.png" src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/141308/a813fdbb-e6fd-18db-6d7f-d44c3d4c78e8.png">


## Jupyter Notebook使用できるまで
anaconda3をダウンロード

```
[root@centos7 ~]# curl https://repo.continuum.io/archive/Anaconda3-4.3.1-Linux-x86_64.sh -O
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  474M  100  474M    0     0  9855k      0  0:00:49  0:00:49 --:--:-- 11.0M
```

```
[root@centos7 ~]# bash ./Anaconda3-4.3.1-Linux-x86_64.sh
```

jupyter notebookの設定

```
[root@centos7 ~]# mkdir -p /root/.jupyter
[root@centos7 ~]# touch ~/.jupyter/jupyter_notebook_config.py
[root@centos7 ~]# vi ~/.jupyter/jupyter_notebook_config.py

[root@centos7 ~]# cat ~/.jupyter/jupyter_notebook_config.py
c = get_config()

c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = false
c.NotebookApp.port = 8888
c.NotebookApp.password = u'sha1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  <--あとで
[root@centos7 ~]#
```
firewallの設定

```
[root@centos7 ~]# firewall-cmd --state
Traceback (most recent call last):
  File "/usr/bin/firewall-cmd", line 24, in <module>
    from gi.repository import GObject

[root@centos7 ~]# ll /usr/bin/python
lrwxrwxrwx. 1 root root 16  9月  1 16:11 /usr/bin/python -> /usr/bin/python3

[root@centos7 ~]# ln -nfs /usr/bin/python2 /usr/bin/python
[root@centos7 ~]# ll /usr/bin/python
lrwxrwxrwx. 1 root root 16  9月 15 14:41 /usr/bin/python -> /usr/bin/python2

[root@centos7 ~]# firewall-cmd --state
running

[root@centos7 ~]# firewall-cmd --list-all --zone=public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens999
  sources:
  services: ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

[root@centos7 ~]# firewall-cmd --add-port=8888/tcp --zone=public --permanent
success
[root@centos7 ~]# firewall-cmd --add-service=http --zone=public --permanent
success
[root@centos7 ~]# firewall-cmd --reload
success
[root@centos7 ~]#
[root@centos7 ~]# firewall-cmd --list-all --zone=public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens999
  sources:
  services: ssh http
  ports: 8888/tcp
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

[root@centos7 ~]# ipython
Python 3.6.8 (default, May  2 2019, 20:40:44)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.

c = get_config()
In [1]: from notebook.auth import passwd

In [2]: passwd()
Enter password:
Verify password:
Out[2]: 'sha1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

In [4]: exit
[root@centos7 ~]# vi ~/.jupyter/jupyter_notebook_config.py
```

```
[root@centos7 ~]# jupyter notebook --allow-root
[E 14:54:57.290 NotebookApp] Exception while loading config file /root/.jupyter/jupyter_notebook_config.py
    Traceback (most recent call last):
      File "/usr/lib/python3.6/site-packages/traitlets/config/application.py", line 562, in _load_config_files
        config = loader.load_config()
      File "/usr/lib/python3.6/site-packages/traitlets/config/loader.py", line 457, in load_config
        self._read_file_as_dict()
      File "/usr/lib/python3.6/site-packages/traitlets/config/loader.py", line 489, in _read_file_as_dict
        py3compat.execfile(conf_filename, namespace)
      File "/usr/lib/python3.6/site-packages/ipython_genutils/py3compat.py", line 198, in execfile
        exec(compiler(f.read(), fname, 'exec'), glob, loc)
      File "/root/.jupyter/jupyter_notebook_config.py", line 4, in <module>
        c.NotebookApp.open_browser = false
    NameError: name 'false' is not defined
[I 14:54:57.498 NotebookApp] Serving notebooks from local directory: /root
[I 14:54:57.498 NotebookApp] The Jupyter Notebook is running at:
[I 14:54:57.499 NotebookApp] http://localhost:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[I 14:54:57.499 NotebookApp]  or http://127.0.0.1:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[I 14:54:57.499 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[W 14:54:57.553 NotebookApp] No web browser found: could not locate runnable browser.
[C 14:54:57.553 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///root/.local/share/jupyter/runtime/nbserver-21530-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
     or http://127.0.0.1:8888/?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```