DNN

入力値: x
重み: w
バイアス: b
活性化: σ

wx + b -> σ(wx + b) = 出力α

MNISTの場合、入力層は784ノード
つまり、画像認識の場合、入力層がピクセル数というイメージだ。
出力層では確率を表しており、確率の高い出力結果をoutputする
例えば、MNISTのように数字が0~9だと10通りだが、自動運転のように外景全てを認識させるとなると、無数に広がる
-> ということは1000万画素の画像認識の場合はノードは1000万?
-> 信号、人、建物、のように出力を絞れば可能か?
-> 人間の顔の場合は、目、鼻など特徴抽出ができるが、ルールがない場合は、頻度の問題が常に生じる??

活性化関数σにはシグモイド関数ReLu関数がよく用いられる
シグモイド関数: 1/(1+exp(-x))
ReLu関数: max(0,x)
-> 線形分離不可能なデータを分離するのに有効

教師あり、教師なし

教師あり学習: 正解ラベルの付いたデータセット
教師なし学習: 正解ラベルの付いていないデータセット
-> 人間の解釈が必要な場合が多い

import numpy as np 
import matplotlib.pyplot as plt 
%matplotlib inline

from sklearn import datasets 
iris = datasets.load_iris()

print(iris.DESCR)
import numpy as np 
import numpy.random as random 
import scipy as sp 
import pandas as pd 
from pandas import Series, DataFrame 

from sklearn.model_selection import train_test_split 
from sklearn.datasets import load_iris 

iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df["target"] = iris.target_names[iris.target]

df.head()

X = df.drop('target', axis=1)
Y = df['target']

X_train, X_test, y_train, y_test = train_test_split(X,Y,random_state=0)

# K-NN
from sklearn.neighbors import KNeighborsClassifier 
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)

print("train score:",model.score(X_train,y_train))
print("test score:",model.score(X_test,y_test))

# decision tree
from sklearn.tree import DecisionTreeClassifier 
model = DecisionTreeClassifier(max_depth=3)
model.fit(X_train, y_train)

print("train score:",model.score(X_train,y_train))
print("test score:",model.score(X_test,y_test))

# SVM
from sklearn.svm import LinearSVC
model = LinearSVC()
model.fit(X_train, y_train)

print("train score:",model.score(X_train,y_train))
print("test score:",model.score(X_test,y_test))

# Linear Regression
from sklearn.linear_model import LogisticRegression

model = LogisticRegression()
model.fit(X_train, y_train)

print("train score:",model.score(X_train,y_train))
print("test score:",model.score(X_test,y_test))

MNIST

MNISTとは?
Mixed National Institute of Standards and Technology database
手書き60000枚とテスト画像10000枚の画像データセット

MNISTのデータDL
http://yann.lecun.com/exdb/mnist/

import keras 
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, InputLayer
from keras.optimizers import RMSprop

(x_train, y_train),(x_test,y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 748)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)

model = Sequential()
model.add(InputLayer(input_shape=(784,)))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer='rmsprop', metrics=['accuracy'])

epochs = 20
batch_size = 128
history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))

score = model.evaluate(x_test, y_test, verbose=1)
print()
print('Test loss:', score[0])
print('Test accuracy:', score[1])

MNISTのデータは縦28ピクセル x 横28ピクセル = 計748ピクセル
各ピクセルRGBは 0 – 255 の256種類の整数値

ImageNet Large Scale Visual Recognition Challenge

画像認識コンペティション
ILSVRC(ImageNet Large Scale Visual Recognition Challenge)

2017年の内容
1,Object localization for 1000 categories.
2,Object detection for 200 fully labeled categories.
3,Object detection from video for 30 fully labeled categories.

ILSVRC2012では、AlexNetが優勝
5つの畳み込み層をもち、3つの全結合層
パラメータ数は、約6000万個

ん? 6000万?
畳み込み層のカーネルサイズ、畳み込み層のカーネル数を調整している?
VGGNetのパラーメータは1億4千個?

input -> stem -> 5x Inception-resnet-A -> Reduction A -> 10 x Inception-resnet-B -> Reduction-B -> 5 x Inception-resnet-C -> Average Pooling -> Drop0ut -> Softmax

本郷・水道橋にある画像認識系のスタートアップって、この画像認識のモデルアルゴリズムも設計してるんだろうか。。

wit.ai

https://wit.ai/

githubアカウントでログインします。

Test how your app understands a sentence
“Engineers tested da Vinci’s bridge design” と入れます。

「インテント」と「エンティティ」を学習させる
bridgeをtargetとするentityをcreateする
value for tested.

このエンティティはUserが自由に定義するようですね。
エンティティを定義して学習させる、という一連のフローは理解できました。

pyaq

Github
https://github.com/intenseG/Pyaq

[vagrant@localhost igo]$ git clone https://github.com/intenseG/Pyaq.git
Initialized empty Git repository in /home/vagrant/python/igo/Pyaq/.git/
remote: Enumerating objects: 74, done.
remote: Total 74 (delta 0), reused 0 (delta 0), pack-reused 74
Unpacking objects: 100% (74/74), done.
[vagrant@localhost igo]$ cd Pyaq
[vagrant@localhost Pyaq]$ ls
LICENSE board.py learn.py pre_train search.py
README.md gtp.py model.py pyaq.py sgf.py

tensorflowが入っていることを確認します
[vagrant@localhost Pyaq]$ pip list

囲碁のデータセット
https://github.com/yenw/computer-go-dataset
http://www.yss-aya.com/ayaself/ayaself.html

pyaqの中身

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from collections import Counter
import sys
from board import *
import gtp
import learn
import search


if __name__ == "__main__":
    args = sys.argv

    launch_mode = 0  # 0: gtp, 1: self, 2: learn
    byoyomi = 5.0
    main_time = 0.0
    quick = False
    random = False
    clean = False
    use_gpu = True

    for arg in args:
        if arg.find("self") >= 0:
            launch_mode = 1
        elif arg.find("learn") >= 0:
            launch_mode = 2
        elif arg.find("quick") >= 0:
            quick = True
        elif arg.find("random") >= 0:
            random = True
        elif arg.find("clean") >= 0:
            clean = True
        elif arg.find("main_time") >= 0:
            main_time = float(arg[arg.find("=") + 1:])
        elif arg.find("byoyomi") >= 0:
            byoyomi = float(arg[arg.find("=") + 1:])
        elif arg.find("cpu") >= 0:
            use_gpu = False

    if launch_mode == 0:
        gtp.call_gtp(main_time, byoyomi, quick, clean, use_gpu)

    elif launch_mode == 1:
        b = Board()
        if not random:
            tree = search.Tree("model.ckpt", use_gpu)

        while b.move_cnt < BVCNT * 2:
            prev_move = b.prev_move
            if random:
                move = b.random_play()
            elif quick:
                move = rv2ev(np.argmax(tree.evaluate(b)&#91;0&#93;&#91;0&#93;))
                b.play(move, False)
            else:
                move, _ = tree.search(b, 0, clean=clean)
                b.play(move, False)

            b.showboard()
            if prev_move == PASS and move == PASS:
                break

        score_list = &#91;&#93;
        b_cpy = Board()

        for i in range(256):
            b.copy(b_cpy)
            b_cpy.rollout(show_board=False)
            score_list.append(b_cpy.score())

        score = Counter(score_list).most_common(1)&#91;0&#93;&#91;0&#93;
        if score == 0:
            result_str = "Draw"
        else:
            winner = "B" if score > 0 else "W"
            result_str = "%s+%.1f" % (winner, abs(score))
        sys.stderr.write("result: %s\n" % result_str)

    else:
        learn.learn(3e-4, 0.5, sgf_dir="sgf/", use_gpu=use_gpu, gpu_cnt=1)

ImportError: /lib64/libc.so.6: version `GLIBC_2.15′ not found

ImportError: /lib64/libc.so.6: version `GLIBC_2.15′ not found
ん?

[vagrant@localhost python]$ ls -l /usr/lib64/libmagic*
lrwxrwxrwx. 1 root root 17 10月 1 20:48 2016 /usr/lib64/libmagic.so.1 -> libmagic.so.1.0.0
-rwxr-xr-x. 1 root root 119896 5月 11 06:03 2016 /usr/lib64/libmagic.so.1.0.0

[vagrant@localhost python]$ rpm -v
RPM バージョン 4.8.0
Copyright (C) 1998-2002 – Red Hat, Inc.
あれ、、

利用可能なパッケージ
名前 : glibc
アーキテクチャ : i686
バージョン : 2.12
リリース : 1.212.el6_10.3
容量 : 4.4 M
リポジトリー : updates
要約 : The GNU libc libraries
URL : http://sources.redhat.com/glibc/
ライセンス : LGPLv2+ and LGPLv2+ with exceptions and GPLv2+
説明 : The glibc package contains standard libraries which are
: used by multiple programs on the system. In order to save
: disk space and memory, as well as to make upgrading
: easier, common system code is kept in one place and shared
: between programs. This particular package contains the
: most important sets of shared libraries: the standard C
: library and the standard math library. Without these two
: libraries, a Linux system will not function.

なるほど、バージョン: 2.12となっています。
conda経由でインストールすると対応できるようです。

tensorflowのインストール

TensorFlowをインストールします。
https://www.tensorflow.org/install?hl=ja

osは、ubuntu, macos, windows, raspbian とある。
何故か、python使ってる人は、centosではなく、ubuntuで構築してますね。何故だろう。centosはRedhat系ですが、ubuntuはDebianです。
centosだけでなく、ubuntuにも慣れておかないといけないですな。
あああああああああああああ、やることがガンガン増えますね。

さて、tensoflowですが、pipで入れられるようです。少し重いようで、時間がかかります。
[vagrant@localhost python]$ pip install tensorflow
Successfully installed absl-py-0.8.1 astor-0.8.0 gast-0.3.2 google-pasta-0.1.7 grpcio-1.24.1 h5py-2.10.0 keras-applications-1.0.8 keras-preprocessing-1.1.0 markdown-3.1.1 setuptools-41.4.0 tensorboard-1.14.0 tensorflow-1.14.0 tensorflow-estimator-1.14.0 termcolor-1.1.0 werkzeug-0.16.0 wheel-0.33.6 wrapt-1.11.2

kerasのモジュールも入っていますね。

公式を見ると、preview build for cpu, gpuと記載があります。
Or preview build for CPU/GPU (unstable)
pip install tf-nightly

Chainerを始めよう3

-Chainerを使いこなすには、ニューラルネットワークの基礎知識が必要不可欠
-biasノードは通常は1 ex. ax + b のbのようなもの
-hiddenは受け取った入力値axに対し、活性化関数を掛ける:h(ax)
-誤差の計算は、cost function, lost functionなどと表現する
-重みはoptimizerとして定義

chainerのモデル定義

from chainer import Chain, Link, ChainList
import chainer.functions as F 
import chainer.links as L 

class MyChain(Chain):

	def __init__(self):
		super(MyChain, self).__init__(
			l1 = L.Linear(4,3),
			l2 = L.Linear(3,2),
		)

	def __call__(self, x):
		h = F.sigmoid(self.l1(x))
		o = self.l2(h)
		return o

l1, l2のところは、何層のNNか。

データをcsv形式ではけば、chainerで二値分類の学習ができる

Chainerを始めよう2

chainerでlinkはimportの際にLとする

import chainer.links as L

活性化関数はF

import chainer.functions as F

linkやfunctionをまとめて管理するのがchain

class MyNeuralNet(chainer.Chain):
from chainer import Chain, optimizers, Variable
import chainer.functions as F 
import chainer.links as L 

import numpy as np 

from sklearn import datasets, model_selection 

import seaborn as sns 
import matplotlib.pyplot as plt 

class MLP(Chain):
	def __init__(self, n_hid=100, n_out=10):
		super().__init__()
		<b>
		with self.init_scope():
			self.l1 = L.Liner(None, n_hid)
			self.l2 = L.Linear(n_hid, n_out)

	def __call__(self, x):
		hid = F.relu(self.l1(x))
		return self.l2(hid)</b>

iris = datasets.load_iris()

train_data, test_data, train_label, test_label = model_selection.train_test_split(iris.data.astype(np.float32),iris.target)

model = MLP(20, 3)

optimizer = optimizers.SGD()

optimizer.setup(model)

train_data_variable = Variable(train_data.astype(np.float32))
train_label_variable = Variable(train_label.astype(np.int32))

loss_log = []

for epoch in range(200):
	model.cleargrads()
	prod_label = model(train_data_variable)
	loss = F.softmax_cross_entropy(prod_label, train_label_variable)
	loss.backward()
	optimizer.update()

	loss_log.append(loss.data)

plt.plot(loss_log)

ん?
全結合層、ランプ関数の使い方、隠れ層の扱い、フォワードプロパゲーションなどがいまいち理解できん。。

損失関数を計算してから、パラメータを更新?

全結合層は、特徴量の取り出し(畳み込みフィルタ、ReLU、プーリング層)後に、特徴量に基づく分類を行う

ランプ関数は、f(x)= max(0,x)
一変数の実関数であり、独立変数とその絶対値の平均として容易に求められる?

隠れ層は、入力層、出力層の間

Softmax関数:多くの次元からなる入力のうち、自分の値が他の値たちに比べて一番目立っているならば、その値が11に近づく関数

フォワードプロパゲーション:レイヤーを進める方向に計算

あれ、NNでいう学習とは、パラメータの更新をforeachなどで繰り返し処理するってこと??