概要
tensorflowで九九、やってみた。
結果
0.395087
0.0249247
0.00668623
0.00196402
0.000861049
0.000167826
0.000323401
4.22531e-05
1.31142e-05
0.000113024
1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 2 4 6 8 10 12 14 16 18
3 3 6 9 12 15 18 21 24 27
4 4 8 12 16 20 24 28 32 36
5 5 10 15 20 25 30 35 40 45
6 6 12 18 24 30 36 42 48 54
7 7 14 21 28 35 42 49 56 63
8 8 16 24 32 40 48 56 64 72
9 9 18 27 36 45 54 63 72 81
サンプルコード
import numpy as np
import tensorflow as tf
#kuku
def in_encode(i, j):
k = j * 16 + i
return np.array([k >> d & 1 for d in range(8)])
def out_encode(i, j):
k = j * i
return np.array([k >> d & 1 for d in range(7)])
def decode(p):
f = 0
if p[0] > 0.5:
f += 1
if p[1] > 0.5:
f += 2
if p[2] > 0.5:
f += 4
if p[3] > 0.5:
f += 8
if p[4] > 0.5:
f += 16
if p[5] > 0.5:
f += 32
if p[6] > 0.5:
f += 64
return f
trX = np.array([in_encode(i, j) for i in range(1, 10) for j in range(1, 10)], dtype = np.float32)
trY = np.array([out_encode(i, j) for i in range(1, 10) for j in range(1, 10)], dtype = np.float32)
g = tf.Graph()
with g.as_default():
x = tf.placeholder(tf.float32, shape = (None, 8))
h1 = tf.layers.dense(x, 96, activation = tf.nn.relu)
y_answer = tf.placeholder(tf.float32, shape = (None, 7))
y_pred = tf.layers.dense(h1, units = 7)
loss = tf.losses.mean_squared_error(labels = y_answer, predictions = y_pred)
optimizer = tf.train.AdamOptimizer(0.01)
train = optimizer.minimize(loss)
with tf.Session(graph = g) as session:
session.run(tf.global_variables_initializer())
dic = {
x: trX,
y_answer: trY
}
for i in range(1000):
_, loss_value = session.run((train, loss), dic)
if i % 100 == 0:
print (loss_value)
#print ('prediction:', session.run(y_pred, dic))
y = session.run(y_pred, dic)
p = ' '
j = 1
for i in range(1, 10):
p += '%3d ' % (i * j)
p += '\n'
for j in range(1, 10):
p += '%3d ' % (j)
for i in range(1, 10):
g = y[(i - 1) * 9 + (j - 1)]
k = decode(g)
p += '%3d ' % (k)
p += '\n'
print (p)
以上。