ディープラーニング tensorflow

import tensorflow as tf
print(tf.__version__)
#じゃんけんデータを作成する
import pickle
import numpy as np

#ジャン絵の手と結果を定義
hands = {'グー': 0, 'チョキ': 1, 'パー': 2}
results = ['あいこ', '負け', '勝ち']

#じゃんけんの公式を定義
judge = lambda a, b: (a - b + 3) % 3

#ランダムにデータを作成
import random
random_hand = lambda : random.randint(0,2)
x_items = []
y_items = []
for i in range(3000):
    a = random_hand()
    b = random_hand()
    result = judge(a, b)
    x_items.append([a,b])
    y_items.append(result)
#作成したデータを表示
print(x_items)
print(y_items)

#データを学習用とテスト用に分割
x_train = x_items[0:2000]
y_train = y_items[0:2000]
x_test = x_items[2000:]
y_test = y_items[2000:]
#データを保存
items = [[x_train, y_train],
         [x_test, y_test]]
with open("janken-data.pkl", "wb") as fp:
    pickle.dump(items, fp)
    
#tensorflowでじゃんけん学習

import tensorflow as tf
import numpy as np
import pickle

# じゃんけんデータを読み込む
with open("janken-data.pkl", "rb") as fp:
    data = pickle.load(fp)
(x_train, y_train), (x_test, y_test) = data

# データをNumPy配列に変換
x_train = np.array(x_train)
y_train = np.array(y_train)
x_test = np.array(x_test)
y_test = np.array(y_test)

# 学習モデルを構築
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(30, activation='relu', input_dim=2),
    tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 学習を実行
model.fit(x_train, y_train, epochs=20)
# テストデータで評価
model.evaluate(x_test, y_test, verbose=2)

# 実際に勝負
def janken(a, b):
    hands = {'グー': 0, 'チョキ': 1, 'パー': 2}
    results = ['あいこ', '負け', '勝ち']
    x = np.array([[hands[a], hands[b]]])
    r = model.predict(x)
    print(r)
    print(a, b, '→', results[r[0].argmax()])

janken('グー', 'グー')
janken('チョキ', 'パー')
janken('パー', 'チョキ')
#グラフでモデルを確認

import tensorflow as tf
import numpy as np
import pickle

# じゃんけんデータを読み込む
with open("janken-data.pkl", "rb") as fp:
    data = pickle.load(fp)  
(x_train, y_train), (x_test, y_test) = data

# データをNumPy配列に変換
x_train = np.array(x_train)
y_train = np.array(y_train)
x_test = np.array(x_test)
y_test = np.array(y_test)

#学習モデルを構築
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(30, activation='relu', input_dim=2),
    tf.keras.layers.Dense(3, activation='softmax')
])

#モデル構築
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']) 

#モデルの概要を表示
model.summary()
#図でモデルを出力
tf.keras.utils.plot_model(model,to_file='janken-model.png')

#学習と評価
model.fit(x_train, y_train, epochs=20)
#テストデータを評価
model.evaluate(x_test, y_test, verbose=2)
タイトルとURLをコピーしました