「人工知能の基本」では, 入門者を対象として,人工知能でできること,人工知能の仕組みを幅広く学べるようにしている.実演も交えている.実習もできる.
お断り:福山大学情報工学科で開講している授業「人工知能」の資料を、一部、手直しの上公開している。
【サイト内の関連ページ】
YouTube の再生リスト「人工知能の基本」
https://youtube.com/playlist?list=PLwoDcGBEg9WG65t7aoLki9JWAZdgauI8
動画は,このページの後半にまとめている
この回で学ぶこと
外部ページへのリンク(作者に感謝します).
この回で学ぶこと.
外部ページへのリンク(作者に感謝します).
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
Python プログラムのソースコード
a = 0
while(True):
print('a = %d' % a)
r = int(input())
if (r == 1) and (a < 21):
a = a + 1
if (r == 2) and (a < 21):
a = a + 2
if (r == 3) and (a < 21):
a = a + 3
Python プログラムのソースコード
def computer(a):
if( a == 1 ):
return 3
elif( a == 2 ):
return 2
elif( a == 3 ):
return 1
elif( a == 5 ):
return 3
elif( a == 6 ):
return 2
elif( a == 7 ):
return 1
elif( a == 9 ):
return 3
elif( a == 10 ):
return 2
elif( a == 11 ):
return 1
elif( a == 13 ):
return 3
elif( a == 14 ):
return 2
elif( a == 15 ):
return 1
elif( a == 17 ):
return 3
elif( a == 18 ):
return 2
elif( a == 19 ):
return 1
else:
return 0
def move(a, r):
if (r == 1) and (a < 21):
a = a + 1
if (r == 2) and (a < 21):
a = a + 2
if (r == 3) and (a < 21):
a = a + 3
return a
a = 0
while(True):
print('a = %d' % a)
r = int(input())
a = move(a, r)
print('a = %d' % a)
r = computer(a)
print('computer: %d' % r)
a = move(a, r)
この回で学ぶこと.
外部ページへのリンク(作者に感謝します).
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
Python プログラムのソースコード
import itertools
import sys
def move(x, y, r):
success = False
if (r == 1) and (x < 1):
x = x + 1
success = True
if (r == 2) and (x > 0):
x = x - 1
success = True
if (r == 3) and (y < 2):
y = y + 1
success = True
if (r == 4) and (y > 0):
y = y - 1
success = True
return(x, y, success)
nsteps = 3
seq = [1, 2, 3, 4]
success = False
for j in list(itertools.product(seq, repeat=nsteps)):
x, y = 0, 0
for i in j:
x, y, success = move(x, y, i)
if(not(success)):
break
if(success):
print("%s %d %d" % (str(j), x, y))
Python プログラムのソースコード
パスの長さ 2 で,総当りで調べるプログラム
import itertools
import sys
def move(x, y, r):
success = False
if (r == 1) and (x < 4):
x = 4
success = True
if (r == 2) and (x > 0):
x = 0
success = True
if (r == 3) and ((x + y) >= 3) and (y < 3):
x, y = x + y - 3, 3
success = True
if (r == 4) and ((x + y) <= 3) and (x > 0):
x, y = 0, x + y
success = True
if (r == 5) and (y < 3):
y = 3
success = True
if (r == 6) and (y > 0):
x = 0
success = True
if (r == 7) and ((x + y) >= 4) and (x < 4):
x, y = 4, x + y - 4
success = True
if (r == 8) and ((x + y) <= 4) and (y > 0):
x, y = x + y, 0
success = True
return(x, y, success)
nsteps = 2
seq = [1, 2, 3, 4, 5, 6, 7, 8]
success = False
for j in list(itertools.product(seq, repeat=nsteps)):
x, y = 0, 0
for i in j:
x, y, success = move(x, y, i)
if(not(success)):
break
if(success):
print("%s %d %d" % (str(j), x, y))
この回で学ぶこと
外部ページへのリンク(作者に感謝します).
最小全域木を選ぶ.全域木は,グラフの全ノードを網羅する木
迷路作成,A* 法と総当たりでの迷路探索の違いを見る
この回で学ぶこと.
プロダクションシステム
作業領域には「知識」のデータを置く。知識は、変化するものである。 知識は、次のような形で書くことができる。
['体毛', 'ある']
['肉食', 'する']
ルールを用いて作業領域を変化させるという推論を行う
ルールは既存の知識から新しい知識を生み出したり、知識を変化させるためのルールである。 次のように書くことができる。
'体毛' = 'ある'→ ['種類', '哺乳類']
'種類' = '哺乳類' and '肉食' = 'する' → ['種類', '肉食動物']
外部ページへのリンク(作者に感謝します).
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
m = [['x', 0], [y', 0]] print(m)
今回の授業で学ぶこと.
male(john). 1項
parent(mike, john). 2項
複数項のときは,カンマで区切る
X が Y の parent (親) ならば, Y は X の child (子供) である
child(Y, X) :- parent(X, Y).
X,Y は変数
Prolog では,問い合わせに対し事実との照合や推論を行う. 問い合わせでは, 値 false, trueを回答したり, 変数値 X = hanako, X = taro を回答する能力を持つ
外部ページへのリンク(作者に感謝します).
Prolog プログラムのソースコード
human(hanako). human(taro). think(X) :- human(X).
Prolog プログラムのソースコード
male(ali). female(zeyn). female(anne). parent(ali, anne). parent(zeyn, anne). child(Y, X) :- parent(X, Y).
この回で学ぶこと
人間の言葉を、コンピュータが処理すること
今回説明したプログラムは,Google Colaboratory というオンラインサービスで実行できる. (この授業では,Google Colaboratory の説明は行わない).
Google Colaboratory に慣れている人のために,次のページを作成しているので, 活用してほしい.
https://colab.research.google.com/drive/18Nf9FPFhOvx8_V30z8PdBD2kcyDap8b7?usp=sharing
このリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.
今回説明したプログラムは,Google Colaboratory というオンラインサービスで実行できる. (この授業では,Google Colaboratory の説明は行わない).
Google Colaboratory に慣れている人のために,次のページを作成しているので, 活用してほしい.
https://colab.research.google.com/drive/1IfArIvhh-FsvJIE9YTNO8T44Qhpi0rIJ?usp=sharing
このリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.
YouTube の再生リスト「人工知能の基本」 https://youtube.com/playlist?list=PLwoDcGBEg9WG65t7aoLki9JWAZdgauI8
外部ページへのリンク(作者に感謝します).
動画URL: https://www.youtube.com/watch/?v=RTVSxOt920A
GDB online: https://www.onlinegdb.com/
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
Python プログラムのソースコード
a = 0
while(True):
print('a = %d' % a)
r = int(input())
if (r == 1) and (a < 21):
a = a + 1
if (r == 2) and (a < 21):
a = a + 2
if (r == 3) and (a < 21):
a = a + 3
動画URL: https://www.youtube.com/watch/?v=l_Tkh01voqs
GDB online: https://www.onlinegdb.com/
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
Python プログラムのソースコード
def computer(a):
if( a == 1 ):
return 3
elif( a == 2 ):
return 2
elif( a == 3 ):
return 1
elif( a == 5 ):
return 3
elif( a == 6 ):
return 2
elif( a == 7 ):
return 1
elif( a == 9 ):
return 3
elif( a == 10 ):
return 2
elif( a == 11 ):
return 1
elif( a == 13 ):
return 3
elif( a == 14 ):
return 2
elif( a == 15 ):
return 1
elif( a == 17 ):
return 3
elif( a == 18 ):
return 2
elif( a == 19 ):
return 1
else:
return 0
def move(a, r):
if (r == 1) and (a < 21):
a = a + 1
if (r == 2) and (a < 21):
a = a + 2
if (r == 3) and (a < 21):
a = a + 3
return a
a = 0
while(True):
print('a = %d' % a)
r = int(input())
a = move(a, r)
print('a = %d' % a)
r = computer(a)
print('computer: %d' % r)
a = move(a, r)
動画URL: https://www.youtube.com/watch/?v=96A5P9eDnWg
GDB online: https://www.onlinegdb.com/
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
Python プログラムのソースコード
import itertools
import sys
def move(x, y, r):
success = False
if (r == 1) and (x < 1):
x = x + 1
success = True
if (r == 2) and (x > 0):
x = x - 1
success = True
if (r == 3) and (y < 2):
y = y + 1
success = True
if (r == 4) and (y > 0):
y = y - 1
success = True
return(x, y, success)
nsteps = 3
seq = [1, 2, 3, 4]
success = False
for j in list(itertools.product(seq, repeat=nsteps)):
x, y = 0, 0
for i in j:
x, y, success = move(x, y, i)
if(not(success)):
break
if(success):
print("%s %d %d" % (str(j), x, y))
動画URL: https://www.youtube.com/watch/?v=2bGdt85xB9
GDB online: https://www.onlinegdb.com/
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
Python プログラムのソースコード
パスの長さ 2 で,総当りで調べるプログラム
import itertools
import sys
def move(x, y, r):
success = False
if (r == 1) and (x < 4):
x = 4
success = True
if (r == 2) and (x > 0):
x = 0
success = True
if (r == 3) and ((x + y) >= 3) and (y < 3):
x, y = x + y - 3, 3
success = True
if (r == 4) and ((x + y) <= 3) and (x > 0):
x, y = 0, x + y
success = True
if (r == 5) and (y < 3):
y = 3
success = True
if (r == 6) and (y > 0):
x = 0
success = True
if (r == 7) and ((x + y) >= 4) and (x < 4):
x, y = 4, x + y - 4
success = True
if (r == 8) and ((x + y) <= 4) and (y > 0):
x, y = x + y, 0
success = True
return(x, y, success)
nsteps = 2
seq = [1, 2, 3, 4, 5, 6, 7, 8]
success = False
for j in list(itertools.product(seq, repeat=nsteps)):
x, y = 0, 0
for i in j:
x, y, success = move(x, y, i)
if(not(success)):
break
if(success):
print("%s %d %d" % (str(j), x, y))
動画URL: https://www.youtube.com/watch/?v=YQ1v6AGvCs4
外部ページへのリンク(作者に感謝します).
最小全域木を選ぶ.全域木は,グラフの全ノードを網羅する木
動画URL: https://www.youtube.com/watch/?v=qmzuj16c2Fw
外部ページへのリンク(作者に感謝します).
迷路作成,A* 法と総当たりでの迷路探索の違いを見る
動画URL: https://www.youtube.com/watch/?v=oqgrvrsI3sM
GDB online: https://www.onlinegdb.com/
右上の「language」で「Python 3」を選ぶこと.
プログラムの実行開始は「Run」,実行停止は「Stop」
m = [['x', 0], [y', 0]] print(m)
動画URL: https://www.youtube.com/watch/?v=iM9FQx2dcOk
外部ページへのリンク(作者に感謝します).
Prolog プログラムのソースコード
human(hanako). human(taro). think(X) :- human(X).
動画URL: https://www.youtube.com/watch/?v=qH02PnE6E_E
外部ページへのリンク(作者に感謝します).
Prolog プログラムのソースコード
male(ali). female(zeyn). female(anne). parent(ali, anne). parent(zeyn, anne). child(Y, X) :- parent(X, Y).
今回説明したプログラムは,Google Colaboratory というオンラインサービスで実行できる. (この授業では,Google Colaboratory の説明は行わない).
Google Colaboratory に慣れている人のために,次のページを作成しているので, 活用してほしい.
https://colab.research.google.com/drive/18Nf9FPFhOvx8_V30z8PdBD2kcyDap8b7?usp=sharing
このリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.
今回説明したプログラムは,Google Colaboratory というオンラインサービスで実行できる. (この授業では,Google Colaboratory の説明は行わない).
Google Colaboratory に慣れている人のために,次のページを作成しているので, 活用してほしい.
https://colab.research.google.com/drive/1IfArIvhh-FsvJIE9YTNO8T44Qhpi0rIJ?usp=sharing
このリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.
ニューラルネットワークを作るプログラム (Python)
import tensorflow as tf
import keras
from keras.models import Sequential
m = Sequential()
from keras.layers import Dense, Activation, Dropout
import keras.optimizers
m.add(Dense(units=64, activation='relu'))', input_dim=4))
m.add(Dense(units=3, activation='softmax'))'))
m.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True))
ニューラルネットワークの確認表示 (Python)
print(m.summary())
ニューラルネットワークの学習を行うプログラム (Python)
import numpy as np x = np.array( [[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]]) y = np.array( [0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0]) m.fit(x, keras.utils.to_categorical(y), epochs=500)
ニューラルネットワークによる分類 (Python)
m.predict( np.array([[0, 1, 0, 1]]) )
m.predict( np.array([[1, 0, 1, 0]]) )
m.predict( np.array([[1, 1, 0, 0]]) )
m.predict( np.array([[0, 0, 1, 1]]) )
第1層と第2層の間の結合の重みを表示 (Python)
m.get_weights()[2]
説明資料:
謝辞:https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html のプログラムをそのまま使用しています.
import numpy as np
from scipy.optimize import minimize
def rosen(x):
"""The Rosenbrock function"""
return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
res = minimize(rosen, x0, method='nelder-mead',
options={'xtol': 1e-8, 'disp': True})
print(res.x)
強化学習により,コンピュータは,迷路からの脱出に上達する.
迷路は配列(アレイ)で作っている.サイズは 9 × 9. 値「1」は壁で,値「0」が通路.迷路の出口は,一番右下の「0」としている.
下のプログラムでは 200回の学習を繰り返している
強化学習による迷路脱出プログラム.「下に行くべき」のスコア算出 (Python)
import numpy as np
from scipy import *
import sys, time
from pybrain.rl.environments.mazes import Maze, MDPMazeTask
from pybrain.rl.learners.valuebased import ActionValueTable
from pybrain.rl.agents import LearningAgent
from pybrain.rl.learners import Q, SARSA
from pybrain.rl.experiments import Experiment
from pybrain.rl.environments import Task
structure = array([[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1]])
environment = Maze(structure, (7, 7))
controller = ActionValueTable(81, 4)
controller.initialize(1.)
learner = Q()
agent = LearningAgent(controller, learner)
task = MDPMazeTask(environment)
experiment = Experiment(task, agent)
for i in range(200):
experiment.doInteractions(100)
agent.learn()
agent.reset()
print( np.round( controller.params.reshape(81,4)[:,0].reshape(9,9), 2) )
強化学習による迷路脱出プログラム.「右に行くべき」のスコア算出
import numpy as np
from scipy import *
import sys, time
from pybrain.rl.environments.mazes import Maze, MDPMazeTask
from pybrain.rl.learners.valuebased import ActionValueTable
from pybrain.rl.agents import LearningAgent
from pybrain.rl.learners import Q, SARSA
from pybrain.rl.experiments import Experiment
from pybrain.rl.environments import Task
structure = array([[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1]])
environment = Maze(structure, (7, 7))
controller = ActionValueTable(81, 4)
controller.initialize(1.)
learner = Q()
agent = LearningAgent(controller, learner)
task = MDPMazeTask(environment)
experiment = Experiment(task, agent)
for i in range(200):
experiment.doInteractions(100)
agent.learn()
agent.reset()
print( np.round( controller.params.reshape(81,4)[:,1].reshape(9,9), 2) )
Python プログラム
ルールのプログラム (Python)
m = [[['name', 'ichiro'], ['has', 'ball']],
[['name', 'jiro'], ['has', 'nil']],
[['name', 'saburo'], ['has', 'ball']],
[['name', 'shiro'], ['has', 'nil']]]
print(m)
ルールの探索 (Python)
m = [[['name', 'ichiro'], ['has', 'ball']],
[['name', 'jiro'], ['has', 'nil']],
[['name', 'saburo'], ['has', 'ball']],
[['name', 'shiro'], ['has', 'nil']]]
for i in m:
for j in i:
if j[0] == 'name':
if j[1] == 'ichiro':
print(i)
ルールの探索 (Python)
m = [[['name', 'ichiro'], ['has', 'ball']],
[['name', 'jiro'], ['has', 'nil']],
[['name', 'saburo'], ['has', 'ball']],
[['name', 'shiro'], ['has', 'nil']]]
for i in m:
for j in i:
if j[0] == 'has':
if j[1] == 'ball':
print(i)
m = [{"name": "ichiro", "has": "ticket", "is": "nil"},
{"name": "jiro", "has": "pen", "is": "nil"},
{"name": "saburo", "has": "book", "is": "nil"}]
for i in m:
if i['has'] == 'ticket':
i['is'] = 'happy'
print(m)
m = [{"sky": "bright", "day_or_noon": "nil", "is_free": "yes", "action": "nil"}]
for i in m:
if i['sky'] == 'bright':
i['day_or_noon'] = 'day'
if i['day_or_noon'] == 'day' and i['is_free'] == 'yes':
i['action'] = 'outdoor'
print(m)
パスの長さ 3 の総当りにより,ゴール状態にできるかを調べるプログラム
import itertools
import sys
nsteps = 3
goal = (3, 0)
path=[1,2,3,4,5,6,7,8]
for j in list(itertools.product(path, repeat=nsteps)):
x, y = 0, 0
for i in j:
if i == 1 and x < 4:
x, y = 4, y
elif i == 2 and y < 3:
x, y = x, 3
elif i == 3 and x > 0:
x, y = 0, y
elif i == 4 and y > 0:
x, y = x, 0
elif i == 5 and (x + y) >= 3 and y < 3:
x, y = x + y - 3, 3
elif i == 6 and (x + y) >= 4 and x < 4:
x, y = 4, x + y - 4
elif i == 7 and (x + y) <= 3 and x < 0:
x, y = 0, x + y
elif i == 8 and (x + y) <= 4 and y > 0:
x, y = x + y, 0
if ( goal == (x, y) ):
print("%s %d %d" % (str(j), x, y))