重みやバイアスは損失関数が最小になるように調整される
損失関数の例: 二乗誤差
E = 1/2*|t – y|^2
※t=正解ラベル、y=NN出力
→ 二乗誤差を最小化するため、微分計算する
損失関数の例: クロスエントロピー
E = -Σt*log[e]y
※t=正解ラベル、y=NN出力
正解ラベルが0か1の値のみ持つ場合、正解ラベル1に対応する出力の自然対数を計算する
y=1, E=0
随机应变 ABCD: Always Be Coding and … : хороший
重みやバイアスは損失関数が最小になるように調整される
損失関数の例: 二乗誤差
E = 1/2*|t – y|^2
※t=正解ラベル、y=NN出力
→ 二乗誤差を最小化するため、微分計算する
損失関数の例: クロスエントロピー
E = -Σt*log[e]y
※t=正解ラベル、y=NN出力
正解ラベルが0か1の値のみ持つ場合、正解ラベル1に対応する出力の自然対数を計算する
y=1, E=0
入力値(0層目): x01 x02 x03 ※α:層の数、β:ノードの数
出力値(出力層):a21 a22 a23
wαβγ ※α:次の層の数、β:α層のノードの数(β番目)、γ:α-1層のノードの数(バイアスbの場合は記載なし)
中間層の計算
x11 = w111*a01 + w112a02 + w13a03 + b11
x12 = w121*a01 + w122a02 + w23a03 + b12
バイアスはパラメータとして入る
計算は行列を用いると
x1(中間層) = W1a0(入力層) + b1(バイアス) に置き換えられる
中間層の出力 a11, a12
a11 = σ1(x11)
a12 = σ1(x12)
σに活性化関数を選択し、x11 = 0 だった場合は、中間層の出力はa11 = σ1(0) = 0.5となる。シグモイド関数を挟むことで、出力は0 or 1 ではなくなる。
x2, w2, a1, b1を行列として出力層を表現すると
x2 = W2a1 + b2
最後の出力層では、softmax関数で非線形変換される。
softmax関数で確率に変換される。
yi = exp(xi)/ (exp(x1) + exp(x2) + … exp(xn)) (1≦i≦n)
入力値: 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とは?
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種類の整数値
画像認識コンペティション
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
本郷・水道橋にある画像認識系のスタートアップって、この画像認識のモデルアルゴリズムも設計してるんだろうか。。
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が自由に定義するようですね。
エンティティを定義して学習させる、という一連のフローは理解できました。
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)[0][0])) 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 = [] 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)[0][0] 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
ん?
[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をインストールします。
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