パーセプトロン

多層パーセプトロン(Multilayer Perceptron, MLP)でORやXORの学習をする神経回路網モデル。 Kerasによる1細胞2入力モデルと3層MLPのサンプルプログラムがあります。

サンプルプログラム

パーセプトロン by Keras

パーセプトロンでORやXORの学習をする神経回路網モデル。1細胞モデルのサンプルと3層のサンプルがあります。

  • プログラムについてはコメントを見て解読して下さい。
  • jupyter notebookにペタペタと貼ればすぐに実行できます。
view raw 0-README.md hosted with ❤ by GitHub

ヘッダ部分

  • モジュールの読み込みと, MLPの学習履歴の表示のための関数定義の部分
  • 以下の2-layer perceptron, 3-layer perceptronのどちらの実行にも必要
!pip install keras # jupyter notebookで実行するとき, この行必要
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD
import matplotlib.pyplot as plt
# 学習履歴をグラフ表示する関数
# - 目的関数(loss), 正確性(acc)の変化
# - 正確性はcompile時のmetricで定義した指標
def hist_plot(hist):
plt.plot(hist.history['loss'], marker='.', label='loss')
plt.plot(hist.history['acc'], marker='.', label='acc')
plt.grid()
plt.legend(loc='best', fontsize=12)
plt.xlabel('epoch')
plt.ylabel('loss/acc')
plt.show()

単純パーセプトロンによるOR回路の学習

  • 2入力1出力をもつ1細胞による学習プログラム
  • AND/OR回路等は学習できても, 線形分離不可能なXOR回路は学習できない
# NNモデル構築
# Sequential : 直列につなげる
# Dense: 通常の全結合ニューラルネットワークレイヤー
# Activation: 活性化関数
model=Sequential()
model.add(Dense(input_dim=2, units=1))
model.add(Activation('sigmoid'))
# - loss: 目的関数
# - optimizer: 最適化アルゴリズム (SGD: 確率的勾配法)
# - metrics: モデルの正確性の評価に使う指標(学習には使わないが評価履歴を残せる)
#model.compile(loss='mean_squared_error', # 最小二乗誤差(こちらも試してみよ)
model.compile(loss='binary_crossentropy', # バイナリクロスエントロピー(H(p, q)=-\sum_x p(x)\log q(x) )
optimizer=SGD(lr=0.1),
metrics=['accuracy'])
# OR回路に対する訓練データ(XORだと学習できない)
x_train=np.array([[0,0],[0,1],[1,0],[1,1]])
y_train=np.array([[0],[1],[1],[1]])
# 学習
hist=model.fit(x_train, y_train, epochs=50, batch_size=1, verbose=True)
# 履歴のグラフ化
hist_plot(hist)
# 評価
y_test=model.predict_classes(x_train, batch_size=1)
print(y_test==y_train)
score=model.evaluate(x_train, y_train, batch_size=1)
print('score: ', score)

多層パーセプトロンによるXOR回路の学習

  • 細胞数は(入力層,中間層,出力層)=(2,2,1)
# NNモデル構築
# Sequential : 直列につなげる
# Dense: 通常の全結合ニューラルネットワークレイヤー
# Activation: 活性化関数
model=Sequential()
model.add(Dense(input_dim=2, units=2)) # middle layer
model.add(Activation('sigmoid'))
model.add(Dense(units=1)) # middle layer
model.add(Activation('sigmoid'))
# NNモデル構築
# - loss: 目的関数
# - optimizer: 最適化アルゴリズム (SGD: 確率的勾配法)
# - metrics: モデルの正確性の評価に使う指標(学習には使わないが評価履歴を残せる)
#model.compile(loss='mean_squared_error', # 最小二乗誤差(こちらも試してみよ)
model.compile(loss='binary_crossentropy', # バイナリクロスエントロピー(H(p, q)=-\sum_x p(x)\log q(x) )
optimizer=SGD(lr=0.1),
metrics=['accuracy'])
# XOR回路の教師データ (3層MLPなら学習できる!)
x_train=np.array([[0,0],[0,1],[1,0],[1,1]])
y_train=np.array([[0],[1],[1],[0]])
# 学習
hist=model.fit(x_train, y_train, epochs=1000, batch_size=1,verbose=False)
# 履歴のグラフ化
hist_plot(hist)
# 評価
y_test=model.predict_classes(x_train, batch_size=4)
print(y_test==y_train)
score = model.evaluate(x_train, y_train, batch_size=4)
print('score: ', score)
view raw 3-1-MLP hosted with ❤ by GitHub