TensorFlow

base

constant

In [2]:
pip install tensorflow==1.15
Collecting tensorflow==1.15
  Downloading https://files.pythonhosted.org/packages/3f/98/5a99af92fb911d7a88a0005ad55005f35b4c1ba8d75fba02df726cd936e6/tensorflow-1.15.0-cp36-cp36m-manylinux2010_x86_64.whl (412.3MB)
     |████████████████████████████████| 412.3MB 42kB/s 
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (1.32.0)
Requirement already satisfied: keras-preprocessing>=1.0.5 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (1.1.2)
Requirement already satisfied: six>=1.10.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (1.15.0)
Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (0.36.2)
Requirement already satisfied: numpy<2.0,>=1.16.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (1.19.4)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (3.3.0)
Requirement already satisfied: protobuf>=3.6.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (3.12.4)
Collecting tensorflow-estimator==1.15.1
  Downloading https://files.pythonhosted.org/packages/de/62/2ee9cd74c9fa2fa450877847ba560b260f5d0fb70ee0595203082dafcc9d/tensorflow_estimator-1.15.1-py2.py3-none-any.whl (503kB)
     |████████████████████████████████| 512kB 47.1MB/s 
Collecting keras-applications>=1.0.8
  Downloading https://files.pythonhosted.org/packages/71/e3/19762fdfc62877ae9102edf6342d71b28fbfd9dea3d2f96a882ce099b03f/Keras_Applications-1.0.8-py3-none-any.whl (50kB)
     |████████████████████████████████| 51kB 8.3MB/s 
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (1.1.0)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (1.12.1)
Requirement already satisfied: astor>=0.6.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (0.8.1)
Requirement already satisfied: absl-py>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (0.10.0)
Collecting tensorboard<1.16.0,>=1.15.0
  Downloading https://files.pythonhosted.org/packages/1e/e9/d3d747a97f7188f48aa5eda486907f3b345cd409f0a0850468ba867db246/tensorboard-1.15.0-py3-none-any.whl (3.8MB)
     |████████████████████████████████| 3.8MB 48.1MB/s 
Requirement already satisfied: google-pasta>=0.1.6 in /usr/local/lib/python3.6/dist-packages (from tensorflow==1.15) (0.2.0)
Collecting gast==0.2.2
  Downloading https://files.pythonhosted.org/packages/4e/35/11749bf99b2d4e3cceb4d55ca22590b0d7c2c62b9de38ac4a4a7f4687421/gast-0.2.2.tar.gz
Requirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from protobuf>=3.6.1->tensorflow==1.15) (50.3.2)
Requirement already satisfied: h5py in /usr/local/lib/python3.6/dist-packages (from keras-applications>=1.0.8->tensorflow==1.15) (2.10.0)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (1.0.1)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (3.3.3)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (3.3.0)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (3.4.0)
Requirement already satisfied: typing-extensions>=3.6.4; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tensorboard<1.16.0,>=1.15.0->tensorflow==1.15) (3.7.4.3)
Building wheels for collected packages: gast
  Building wheel for gast (setup.py) ... done
  Created wheel for gast: filename=gast-0.2.2-cp36-none-any.whl size=7540 sha256=98b5feeaaf7eb61b01c1b5b65a26be4b4c18d95c954c707e4bf0c383b0ef38ee
  Stored in directory: /root/.cache/pip/wheels/5c/2e/7e/a1d4d4fcebe6c381f378ce7743a3ced3699feb89bcfbdadadd
Successfully built gast
ERROR: tensorflow-probability 0.11.0 has requirement gast>=0.3.2, but you'll have gast 0.2.2 which is incompatible.
Installing collected packages: tensorflow-estimator, keras-applications, tensorboard, gast, tensorflow
  Found existing installation: tensorflow-estimator 2.4.0
    Uninstalling tensorflow-estimator-2.4.0:
      Successfully uninstalled tensorflow-estimator-2.4.0
  Found existing installation: tensorboard 2.4.0
    Uninstalling tensorboard-2.4.0:
      Successfully uninstalled tensorboard-2.4.0
  Found existing installation: gast 0.3.3
    Uninstalling gast-0.3.3:
      Successfully uninstalled gast-0.3.3
  Found existing installation: tensorflow 2.4.0
    Uninstalling tensorflow-2.4.0:
      Successfully uninstalled tensorflow-2.4.0
Successfully installed gast-0.2.2 keras-applications-1.0.8 tensorboard-1.15.0 tensorflow-1.15.0 tensorflow-estimator-1.15.1
In [1]:
import tensorflow as tf
import numpy as np

# それぞれ定数を定義
a = tf.constant(1)
b = tf.constant(2, dtype=tf.float32, shape=[3,2])
c = tf.constant(np.arange(4), dtype=tf.float32, shape=[2,2])

print('a:', a)
print('b:', b)
print('c:', c)

sess = tf.Session()

print('a:', sess.run(a))
print('b:', sess.run(b))
print('c:', sess.run(c))
a: Tensor("Const:0", shape=(), dtype=int32)
b: Tensor("Const_1:0", shape=(3, 2), dtype=float32)
c: Tensor("Const_2:0", shape=(2, 2), dtype=float32)
a: 1
b: [[2. 2.]
 [2. 2.]
 [2. 2.]]
c: [[0. 1.]
 [2. 3.]]

placeholder

In [2]:
import tensorflow as tf
import numpy as np

# プレースホルダーを定義
x = tf.placeholder(dtype=tf.float32, shape=[None,3])

print('x:', x)

sess = tf.Session()

X = np.random.rand(2,3)
print('X:', X)

# プレースホルダにX[0]を入力
# shapeを(3,)から(1,3)にするためreshape
print('x:', sess.run(x, feed_dict={x:X[0].reshape(1,-1)}))
# プレースホルダにX[1]を入力
print('x:', sess.run(x, feed_dict={x:X[1].reshape(1,-1)}))
x: Tensor("Placeholder:0", shape=(?, 3), dtype=float32)
X: [[0.2176188  0.54047256 0.24247657]
 [0.22682811 0.60997548 0.23297333]]
x: [[0.2176188  0.54047257 0.24247657]]
x: [[0.22682811 0.60997546 0.23297332]]

variables

In [3]:
# 定数を定義
a = tf.constant(10)
print('a:', a)
# 変数を定義
x = tf.Variable(1)
print('x:', x)

calc_op = x * a

# xの値を更新
update_x = tf.assign(x, calc_op)

sess = tf.Session()

# 変数の初期化
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(x))

sess.run(update_x)
print(sess.run(x))

sess.run(update_x)
print(sess.run(x))
a: Tensor("Const_3:0", shape=(), dtype=int32)
x: <tf.Variable 'Variable:0' shape=() dtype=int32_ref>
1
10
100

線形回帰


[try]

  • noiseの値を変更しよう
  • dの数値を変更しよう

In [18]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

iters_num = 300
plot_interval = 10

# データを生成
n = 100
x = np.random.rand(n)
d = 12 * x + 10

# ノイズを加える
noise = 0.1
d = d + noise * np.random.randn(n) 

# 入力値
xt = tf.placeholder(tf.float32)
dt = tf.placeholder(tf.float32)

# 最適化の対象の変数を初期化
W = tf.Variable(tf.zeros([1]))
b = tf.Variable(tf.zeros([1]))

y = W * xt + b

# 誤差関数 平均2乗誤差
loss = tf.reduce_mean(tf.square(y - dt))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(loss)

# 初期化
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# 作成したデータをトレーニングデータとして準備
x_train = x.reshape(-1,1)
d_train = d.reshape(-1,1)

# トレーニング
for i in range(iters_num):
    sess.run(train, feed_dict={xt:x_train,dt:d_train})
    if (i+1) % plot_interval == 0:
        loss_val = sess.run(loss, feed_dict={xt:x_train,dt:d_train}) 
        W_val = sess.run(W)
        b_val = sess.run(b)
        print('Generation: ' + str(i+1) + '. 誤差 = ' + str(loss_val))

print(W_val)
print(b_val)

#  予測関数
def predict(x):
    return W_val * x + b_val

fig = plt.figure()
subplot = fig.add_subplot(1, 1, 1)
plt.scatter(x, d)
linex = np.linspace(0, 1, 2)
liney = predict(linex)
subplot.plot(linex,liney)
plt.show()
Generation: 10. 誤差 = 3.1102407
Generation: 20. 誤差 = 1.6176286
Generation: 30. 誤差 = 1.170737
Generation: 40. 誤差 = 0.8495356
Generation: 50. 誤差 = 0.6170961
Generation: 60. 誤差 = 0.44888416
Generation: 70. 誤差 = 0.32715115
Generation: 80. 誤差 = 0.23905525
Generation: 90. 誤差 = 0.17530188
Generation: 100. 誤差 = 0.12916493
Generation: 110. 誤差 = 0.09577628
Generation: 120. 誤差 = 0.07161365
Generation: 130. 誤差 = 0.054127574
Generation: 140. 誤差 = 0.041473266
Generation: 150. 誤差 = 0.03231548
Generation: 160. 誤差 = 0.025688194
Generation: 170. 誤差 = 0.020892227
Generation: 180. 誤差 = 0.017421287
Generation: 190. 誤差 = 0.014909419
Generation: 200. 誤差 = 0.013091722
Generation: 210. 誤差 = 0.011776253
Generation: 220. 誤差 = 0.010824252
Generation: 230. 誤差 = 0.010135322
Generation: 240. 誤差 = 0.00963677
Generation: 250. 誤差 = 0.009275947
Generation: 260. 誤差 = 0.009014871
Generation: 270. 誤差 = 0.0088259205
Generation: 280. 誤差 = 0.008689169
Generation: 290. 誤差 = 0.008590237
Generation: 300. 誤差 = 0.008518609
[11.91935]
[10.053823]

非線形回帰


[try]

  • noiseの値を変更しよう
  • dの数値を変更しよう

In [19]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

iters_num = 10000
plot_interval = 100

# データを生成
n=100
x = np.random.rand(n).astype(np.float32) * 4 - 2
d =  - 0.4 * x ** 3 + 1.6 * x ** 2 - 2.8 * x + 1 + 2.0 * x ** 3

#  ノイズを加える
noise = 0.2
d = d + noise * np.random.randn(n) 

# モデル
# bを使っていないことに注意.
xt = tf.placeholder(tf.float32, [None, 4])
dt = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.random_normal([4, 1], stddev=0.01))
y = tf.matmul(xt,W)

# 誤差関数 平均2乗誤差
loss = tf.reduce_mean(tf.square(y - dt))
optimizer = tf.train.AdamOptimizer(0.001)
train = optimizer.minimize(loss)

# 初期化
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# 作成したデータをトレーニングデータとして準備
d_train = d.reshape(-1,1)
x_train = np.zeros([n, 4])
for i in range(n):
    for j in range(4):
        x_train[i, j] = x[i]**j

#  トレーニング
for i in range(iters_num):
    if (i+1) % plot_interval == 0:
        loss_val = sess.run(loss, feed_dict={xt:x_train, dt:d_train}) 
        W_val = sess.run(W)
        print('Generation: ' + str(i+1) + '. 誤差 = ' + str(loss_val))
    sess.run(train, feed_dict={xt:x_train,dt:d_train})

print(W_val[::-1])
    
# 予測関数
def predict(x):
    result = 0.
    for i in range(0,4):
        result += W_val[i,0] * x ** i
    return result

fig = plt.figure()
subplot = fig.add_subplot(1,1,1)
plt.scatter(x ,d)
linex = np.linspace(-2,2,100)
liney = predict(linex)
subplot.plot(linex,liney)
plt.show()
Generation: 100. 誤差 = 13.4005
Generation: 200. 誤差 = 11.142644
Generation: 300. 誤差 = 9.355879
Generation: 400. 誤差 = 7.945735
Generation: 500. 誤差 = 6.8251643
Generation: 600. 誤差 = 5.9193544
Generation: 700. 誤差 = 5.169635
Generation: 800. 誤差 = 4.534532
Generation: 900. 誤差 = 3.9873414
Generation: 1000. 誤差 = 3.511676
Generation: 1100. 誤差 = 3.0971103
Generation: 1200. 誤差 = 2.736177
Generation: 1300. 誤差 = 2.422742
Generation: 1400. 誤差 = 2.151293
Generation: 1500. 誤差 = 1.9166882
Generation: 1600. 誤差 = 1.7141037
Generation: 1700. 誤差 = 1.5390614
Generation: 1800. 誤差 = 1.3874574
Generation: 1900. 誤差 = 1.2556018
Generation: 2000. 誤差 = 1.1402336
Generation: 2100. 誤差 = 1.0385331
Generation: 2200. 誤差 = 0.9481102
Generation: 2300. 誤差 = 0.8669844
Generation: 2400. 誤差 = 0.79355186
Generation: 2500. 誤差 = 0.7265426
Generation: 2600. 誤差 = 0.6649747
Generation: 2700. 誤差 = 0.6081039
Generation: 2800. 誤差 = 0.5553759
Generation: 2900. 誤差 = 0.5063838
Generation: 3000. 誤差 = 0.46082863
Generation: 3100. 誤差 = 0.41848603
Generation: 3200. 誤差 = 0.37918282
Generation: 3300. 誤差 = 0.34277833
Generation: 3400. 誤差 = 0.30914992
Generation: 3500. 誤差 = 0.27818486
Generation: 3600. 誤差 = 0.24977256
Generation: 3700. 誤差 = 0.22380412
Generation: 3800. 誤差 = 0.200168
Generation: 3900. 誤差 = 0.17875032
Generation: 4000. 誤差 = 0.15943462
Generation: 4100. 誤差 = 0.1421025
Generation: 4200. 誤差 = 0.12663312
Generation: 4300. 誤差 = 0.11290483
Generation: 4400. 誤差 = 0.10079529
Generation: 4500. 誤差 = 0.09018238
Generation: 4600. 誤差 = 0.08094488
Generation: 4700. 誤差 = 0.07296306
Generation: 4800. 誤差 = 0.066119954
Generation: 4900. 誤差 = 0.06030176
Generation: 5000. 誤差 = 0.055398684
Generation: 5100. 誤差 = 0.051305827
Generation: 5200. 誤差 = 0.047923576
Generation: 5300. 誤差 = 0.04515857
Generation: 5400. 誤差 = 0.04292386
Generation: 5500. 誤差 = 0.041139755
Generation: 5600. 誤差 = 0.039733764
Generation: 5700. 誤差 = 0.038640995
Generation: 5800. 誤差 = 0.037804063
Generation: 5900. 誤差 = 0.037173003
Generation: 6000. 誤差 = 0.03670494
Generation: 6100. 誤差 = 0.03636389
Generation: 6200. 誤差 = 0.0361199
Generation: 6300. 誤差 = 0.035948783
Generation: 6400. 誤差 = 0.035831224
Generation: 6500. 誤差 = 0.03575223
Generation: 6600. 誤差 = 0.035700377
Generation: 6700. 誤差 = 0.035667144
Generation: 6800. 誤差 = 0.035646357
Generation: 6900. 誤差 = 0.03563378
Generation: 7000. 誤差 = 0.035626315
Generation: 7100. 誤差 = 0.035622057
Generation: 7200. 誤差 = 0.035619713
Generation: 7300. 誤差 = 0.035618436
Generation: 7400. 誤差 = 0.03561778
Generation: 7500. 誤差 = 0.03561745
Generation: 7600. 誤差 = 0.03561729
Generation: 7700. 誤差 = 0.035617243
Generation: 7800. 誤差 = 0.03561718
Generation: 7900. 誤差 = 0.03561719
Generation: 8000. 誤差 = 0.035617188
Generation: 8100. 誤差 = 0.03561718
Generation: 8200. 誤差 = 0.035617158
Generation: 8300. 誤差 = 0.035617184
Generation: 8400. 誤差 = 0.035617176
Generation: 8500. 誤差 = 0.035617176
Generation: 8600. 誤差 = 0.035617173
Generation: 8700. 誤差 = 0.03561716
Generation: 8800. 誤差 = 0.035617188
Generation: 8900. 誤差 = 0.03561717
Generation: 9000. 誤差 = 0.03561717
Generation: 9100. 誤差 = 0.03561716
Generation: 9200. 誤差 = 0.03561717
Generation: 9300. 誤差 = 0.03561716
Generation: 9400. 誤差 = 0.035617158
Generation: 9500. 誤差 = 0.03561717
Generation: 9600. 誤差 = 0.03561718
Generation: 9700. 誤差 = 0.035617173
Generation: 9800. 誤差 = 0.03561717
Generation: 9900. 誤差 = 0.035617154
Generation: 10000. 誤差 = 0.035617184
[[ 1.5968845]
 [ 1.5704507]
 [-2.7983077]
 [ 1.0383744]]

[try]

  • 次の式をモデルとして回帰を行おう $$ y=30x^{2} +0.5x+0.2 $$
  • 誤差が収束するようiters_numやlearning_rateを調整しよう

In [60]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

iters_num = 9000
plot_interval = 1000

n = 100
x = np.random.rand(n)*4-2
d = 30*x**2 + 0.5*x + 0.2

#noise = 0.3
#d = d + noise * np.random.randn(n) 

xt = tf.placeholder(tf.float32, [None, 3])
dt = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([3, 1]))
y = tf.matmul(xt, W)

loss = tf.reduce_mean(tf.square(y - dt))
optimizer = tf.train.AdamOptimizer(0.01)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

d_train = d.reshape(n ,1)
x_train = np.zeros([n, 3])
for i in range(n):
    for j in range(3):
        x_train[i, j] = x[i]**j

for i in range(iters_num):
    if (i+1) % plot_interval == 0:
        loss_val = sess.run(loss, feed_dict={xt:x_train, dt:d_train}) 
        W_val = sess.run(W)
        print('Generation: ' + str(i+1) + '. 誤差 = ' + str(loss_val))
    sess.run(train, feed_dict={xt:x_train,dt:d_train})

print(W_val[::-1])
    
def predict(x):
    result = 0.
    for i in range(0, 3):
        result += W_val[i,0] * x ** i
    return result

fig = plt.figure()
subplot = fig.add_subplot(1, 1, 1)
plt.scatter(x, d)
linex = np.linspace(-2,2,100)
liney = predict(linex)
subplot.plot(linex,liney)
plt.show()
Generation: 1000. 誤差 = 791.5388
Generation: 2000. 誤差 = 268.75586
Generation: 3000. 誤差 = 121.87769
Generation: 4000. 誤差 = 56.342533
Generation: 5000. 誤差 = 17.720467
Generation: 6000. 誤差 = 2.8662353
Generation: 7000. 誤差 = 0.14900254
Generation: 8000. 誤差 = 0.001104235
Generation: 9000. 誤差 = 3.1687614e-07
[[29.999508  ]
 [ 0.5000475 ]
 [ 0.20074062]]

分類1層 (mnist)


[try]

- x:入力値, d:教師データ, W:重み, b:バイアス をそれぞれ定義しよう

In [6]:
import tensorflow as tf
import matplotlib.pyplot as plt

# logging levelを変更
tf.logging.set_verbosity(tf.logging.ERROR)

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

iters_num = 100
batch_size = 100
plot_interval = 1

# -------------- ここを補填 ------------------------
x = tf.placeholder(tf.float32, [None, 784])
d = tf.placeholder(tf.float32, [None, 10])
W = tf.Variable(tf.random_normal([784, 10], stddev = 0.01))
b = tf.Variable(tf.zeros([10]))
# ------------------------------------------------------

y = tf.nn.softmax(tf.matmul(x, W) + b)

# 交差エントロピー
cross_entropy = -tf.reduce_sum(d * tf.log(y), reduction_indices=[1])
loss = tf.reduce_mean(cross_entropy)
train = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# 正誤を保存
correct = tf.equal(tf.argmax(y, 1), tf.argmax(d, 1))
# 正解率
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

accuracies = []
for i in range(iters_num):
    x_batch, d_batch = mnist.train.next_batch(batch_size)
    sess.run(train, feed_dict={x: x_batch, d: d_batch})
    if (i+1) % plot_interval == 0:
        print(sess.run(correct, feed_dict={x: mnist.test.images, d: mnist.test.labels}))
        accuracy_val = sess.run(accuracy, feed_dict={x: mnist.test.images, d: mnist.test.labels})
        accuracies.append(accuracy_val)
        print('Generation: ' + str(i+1) + '. 正解率 = ' + str(accuracy_val))
        
        
lists = range(0, iters_num, plot_interval)
plt.plot(lists, accuracies)
plt.title("accuracy")
plt.ylim(0, 1.0)
plt.show()        
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
[False  True  True ... False False False]
Generation: 1. 正解率 = 0.3358
[ True  True  True ... False  True  True]
Generation: 2. 正解率 = 0.4964
[ True  True  True ... False False  True]
Generation: 3. 正解率 = 0.5189
[False  True  True ... False False  True]
Generation: 4. 正解率 = 0.5384
[ True  True  True ... False False  True]
Generation: 5. 正解率 = 0.5973
[ True  True  True ... False False  True]
Generation: 6. 正解率 = 0.712
[ True False  True ... False False  True]
Generation: 7. 正解率 = 0.64
[ True False  True ... False False  True]
Generation: 8. 正解率 = 0.6313
[ True  True  True ... False False  True]
Generation: 9. 正解率 = 0.7265
[ True  True  True ... False False  True]
Generation: 10. 正解率 = 0.6754
[ True  True  True ... False False  True]
Generation: 11. 正解率 = 0.7531
[ True  True  True ...  True False  True]
Generation: 12. 正解率 = 0.7679
[ True  True  True ...  True  True  True]
Generation: 13. 正解率 = 0.7034
[ True  True  True ...  True False  True]
Generation: 14. 正解率 = 0.7371
[ True  True  True ...  True  True  True]
Generation: 15. 正解率 = 0.7221
[ True  True  True ...  True False  True]
Generation: 16. 正解率 = 0.7833
[ True  True  True ...  True False  True]
Generation: 17. 正解率 = 0.7864
[ True  True  True ...  True False  True]
Generation: 18. 正解率 = 0.7969
[ True  True  True ...  True False  True]
Generation: 19. 正解率 = 0.8082
[ True  True  True ...  True False  True]
Generation: 20. 正解率 = 0.8224
[ True  True  True ... False False  True]
Generation: 21. 正解率 = 0.8143
[ True  True  True ... False False  True]
Generation: 22. 正解率 = 0.7906
[ True  True  True ... False False  True]
Generation: 23. 正解率 = 0.8089
[ True  True  True ...  True False  True]
Generation: 24. 正解率 = 0.8147
[ True  True  True ...  True False  True]
Generation: 25. 正解率 = 0.8201
[ True  True  True ...  True False  True]
Generation: 26. 正解率 = 0.8186
[ True  True  True ...  True False  True]
Generation: 27. 正解率 = 0.8186
[ True  True  True ...  True False  True]
Generation: 28. 正解率 = 0.8243
[ True  True  True ...  True False  True]
Generation: 29. 正解率 = 0.8158
[ True  True  True ...  True  True  True]
Generation: 30. 正解率 = 0.8258
[ True  True  True ...  True False  True]
Generation: 31. 正解率 = 0.8284
[ True  True  True ...  True False  True]
Generation: 32. 正解率 = 0.8187
[ True  True  True ...  True False  True]
Generation: 33. 正解率 = 0.8267
[ True  True  True ...  True False  True]
Generation: 34. 正解率 = 0.8313
[ True  True  True ...  True False  True]
Generation: 35. 正解率 = 0.8304
[ True  True  True ...  True False  True]
Generation: 36. 正解率 = 0.8351
[ True  True  True ...  True False  True]
Generation: 37. 正解率 = 0.8373
[ True  True  True ...  True False  True]
Generation: 38. 正解率 = 0.8406
[ True  True  True ...  True False  True]
Generation: 39. 正解率 = 0.8426
[ True  True  True ...  True False  True]
Generation: 40. 正解率 = 0.8392
[ True  True  True ...  True False  True]
Generation: 41. 正解率 = 0.8429
[ True  True  True ...  True False  True]
Generation: 42. 正解率 = 0.8363
[ True  True  True ...  True  True  True]
Generation: 43. 正解率 = 0.8338
[ True  True  True ...  True  True  True]
Generation: 44. 正解率 = 0.8456
[ True  True  True ...  True  True  True]
Generation: 45. 正解率 = 0.8373
[ True  True  True ...  True False  True]
Generation: 46. 正解率 = 0.8355
[ True  True  True ...  True False  True]
Generation: 47. 正解率 = 0.8392
[ True  True  True ...  True False  True]
Generation: 48. 正解率 = 0.8395
[ True  True  True ...  True False  True]
Generation: 49. 正解率 = 0.8406
[ True  True  True ...  True  True  True]
Generation: 50. 正解率 = 0.8472
[ True  True  True ...  True False  True]
Generation: 51. 正解率 = 0.8448
[ True  True  True ...  True False  True]
Generation: 52. 正解率 = 0.8489
[ True  True  True ...  True False  True]
Generation: 53. 正解率 = 0.8491
[ True  True  True ...  True False  True]
Generation: 54. 正解率 = 0.8484
[ True  True  True ...  True False  True]
Generation: 55. 正解率 = 0.8481
[ True  True  True ...  True False  True]
Generation: 56. 正解率 = 0.8521
[ True  True  True ...  True False  True]
Generation: 57. 正解率 = 0.8488
[ True  True  True ...  True False  True]
Generation: 58. 正解率 = 0.8489
[ True  True  True ...  True False  True]
Generation: 59. 正解率 = 0.8453
[ True  True  True ...  True False  True]
Generation: 60. 正解率 = 0.842
[ True  True  True ...  True False  True]
Generation: 61. 正解率 = 0.8512
[ True  True  True ...  True False  True]
Generation: 62. 正解率 = 0.8501
[ True  True  True ...  True False  True]
Generation: 63. 正解率 = 0.8529
[ True  True  True ...  True False  True]
Generation: 64. 正解率 = 0.858
[ True  True  True ...  True False  True]
Generation: 65. 正解率 = 0.8575
[ True  True  True ...  True False  True]
Generation: 66. 正解率 = 0.8534
[ True  True  True ...  True False  True]
Generation: 67. 正解率 = 0.8487
[ True  True  True ...  True False  True]
Generation: 68. 正解率 = 0.8545
[ True  True  True ...  True False  True]
Generation: 69. 正解率 = 0.8576
[ True  True  True ...  True False  True]
Generation: 70. 正解率 = 0.852
[ True  True  True ...  True False  True]
Generation: 71. 正解率 = 0.8595
[ True  True  True ...  True False  True]
Generation: 72. 正解率 = 0.8593
[ True  True  True ...  True False  True]
Generation: 73. 正解率 = 0.859
[ True  True  True ...  True False  True]
Generation: 74. 正解率 = 0.8542
[ True  True  True ...  True False  True]
Generation: 75. 正解率 = 0.8568
[ True  True  True ...  True False  True]
Generation: 76. 正解率 = 0.8593
[ True  True  True ...  True False  True]
Generation: 77. 正解率 = 0.8599
[ True  True  True ...  True False  True]
Generation: 78. 正解率 = 0.8634
[ True  True  True ...  True False  True]
Generation: 79. 正解率 = 0.8594
[ True  True  True ...  True False  True]
Generation: 80. 正解率 = 0.8555
[ True  True  True ...  True False  True]
Generation: 81. 正解率 = 0.8611
[ True  True  True ...  True False  True]
Generation: 82. 正解率 = 0.8577
[ True  True  True ...  True False  True]
Generation: 83. 正解率 = 0.8636
[ True  True  True ...  True False  True]
Generation: 84. 正解率 = 0.8645
[ True  True  True ...  True False  True]
Generation: 85. 正解率 = 0.8685
[ True  True  True ...  True False  True]
Generation: 86. 正解率 = 0.8661
[ True  True  True ...  True False  True]
Generation: 87. 正解率 = 0.8652
[ True  True  True ...  True False  True]
Generation: 88. 正解率 = 0.8654
[ True  True  True ...  True False  True]
Generation: 89. 正解率 = 0.8625
[ True  True  True ...  True False  True]
Generation: 90. 正解率 = 0.8643
[ True  True  True ...  True False  True]
Generation: 91. 正解率 = 0.8596
[ True  True  True ...  True False  True]
Generation: 92. 正解率 = 0.8655
[ True  True  True ...  True False  True]
Generation: 93. 正解率 = 0.8655
[ True  True  True ...  True False  True]
Generation: 94. 正解率 = 0.8692
[ True  True  True ...  True False  True]
Generation: 95. 正解率 = 0.8699
[ True  True  True ...  True False  True]
Generation: 96. 正解率 = 0.8701
[ True  True  True ...  True False  True]
Generation: 97. 正解率 = 0.8682
[ True  True  True ...  True False  True]
Generation: 98. 正解率 = 0.8699
[ True  True  True ...  True False  True]
Generation: 99. 正解率 = 0.871
[ True  True  True ...  True False  True]
Generation: 100. 正解率 = 0.8703

分類3層 (mnist)


[try]

  • 隠れ層のサイズを変更してみよう
  • optimizerを変更しよう

tf.train.GradientDescentOptimizer
__init__( learning_rate, use_locking=False, name='GradientDescent' )

tf.train.MomentumOptimizer
__init__( learning_rate, momentum, use_locking=False, name='Momentum', use_nesterov=False )

tf.train.AdagradOptimizer
__init__( learning_rate, initial_accumulator_value=0.1, use_locking=False, name='Adagrad' )

tf.train.RMSPropOptimizer
__init__( learning_rate, decay=0.9, momentum=0.0, epsilon=1e-10, use_locking=False, centered=False, name='RMSProp' )

tf.train.AdamOptimizer
__init__( learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam' )


In [32]:
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt

# logging levelを変更
tf.logging.set_verbosity(tf.logging.ERROR)

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

iters_num = 3000
batch_size = 100
plot_interval = 100

hidden_layer_size_1 = 1200
hidden_layer_size_2 = 900

dropout_rate = 0.5

x = tf.placeholder(tf.float32, [None, 784])
d = tf.placeholder(tf.float32, [None, 10])
W1 = tf.Variable(tf.random_normal([784, hidden_layer_size_1], stddev=0.01))
W2 = tf.Variable(tf.random_normal([hidden_layer_size_1, hidden_layer_size_2], stddev=0.01))
W3 = tf.Variable(tf.random_normal([hidden_layer_size_2, 10], stddev=0.01))

b1 = tf.Variable(tf.zeros([hidden_layer_size_1]))
b2 = tf.Variable(tf.zeros([hidden_layer_size_2]))
b3 = tf.Variable(tf.zeros([10]))

z1 = tf.sigmoid(tf.matmul(x, W1) + b1)
z2 = tf.sigmoid(tf.matmul(z1, W2) + b2)

keep_prob = tf.placeholder(tf.float32)
drop = tf.nn.dropout(z2, keep_prob)

y = tf.nn.softmax(tf.matmul(drop, W3) + b3)
loss = tf.reduce_mean(-tf.reduce_sum(d * tf.log(y), reduction_indices=[1]))

#optimizer = tf.train.GradientDescentOptimizer(0.5)
#optimizer = tf.train.MomentumOptimizer(0.3, 0.5)
#optimizer = tf.train.AdagradOptimizer(0.3)
#optimizer = tf.train.RMSPropOptimizer(0.001)
optimizer = tf.train.AdamOptimizer(0.01)

train = optimizer.minimize(loss)
correct = tf.equal(tf.argmax(y, 1), tf.argmax(d, 1))
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

accuracies = []
for i in range(iters_num):
    x_batch, d_batch = mnist.train.next_batch(batch_size)
    sess.run(train, feed_dict={x:x_batch, d:d_batch, keep_prob:(1 - dropout_rate)})
    if (i+1) % plot_interval == 0:
        accuracy_val = sess.run(accuracy, feed_dict={x:mnist.test.images, d:mnist.test.labels, keep_prob:1.0})            
        accuracies.append(accuracy_val)
        print('Generation: ' + str(i+1) + '. 正解率 = ' + str(accuracy_val))        
    
lists = range(0, iters_num, plot_interval)
plt.plot(lists, accuracies)
plt.title("accuracy")
plt.ylim(0, 1.0)
plt.show()            
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
Generation: 100. 正解率 = 0.3058
Generation: 200. 正解率 = 0.9165
Generation: 300. 正解率 = 0.9237
Generation: 400. 正解率 = 0.9533
Generation: 500. 正解率 = 0.9607
Generation: 600. 正解率 = 0.957
Generation: 700. 正解率 = 0.9643
Generation: 800. 正解率 = 0.9648
Generation: 900. 正解率 = 0.9582
Generation: 1000. 正解率 = 0.9644
Generation: 1100. 正解率 = 0.9678
Generation: 1200. 正解率 = 0.9681
Generation: 1300. 正解率 = 0.9656
Generation: 1400. 正解率 = 0.9672
Generation: 1500. 正解率 = 0.9674
Generation: 1600. 正解率 = 0.9691
Generation: 1700. 正解率 = 0.9723
Generation: 1800. 正解率 = 0.9713
Generation: 1900. 正解率 = 0.9668
Generation: 2000. 正解率 = 0.9676
Generation: 2100. 正解率 = 0.9748
Generation: 2200. 正解率 = 0.9675
Generation: 2300. 正解率 = 0.9689
Generation: 2400. 正解率 = 0.97
Generation: 2500. 正解率 = 0.9753
Generation: 2600. 正解率 = 0.9727
Generation: 2700. 正解率 = 0.9715
Generation: 2800. 正解率 = 0.9679
Generation: 2900. 正解率 = 0.9725
Generation: 3000. 正解率 = 0.9658

分類CNN (mnist)

conv - relu - pool - conv - relu - pool -
affin - relu - dropout - affin - softmax


[try]

- ドロップアウト率を0に変更しよう

In [34]:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# logging levelを変更
tf.logging.set_verbosity(tf.logging.ERROR)

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import matplotlib.pyplot as plt

iters_num = 300
batch_size = 100
plot_interval = 10

dropout_rate = 0

# placeholder
x = tf.placeholder(tf.float32, shape=[None, 784])
d = tf.placeholder(tf.float32, shape=[None, 10])

# 画像を784の一次元から28x28の二次元に変換する
# 画像を28x28にreshape
x_image = tf.reshape(x, [-1,28,28,1])

# 第一層のweightsとbiasのvariable
W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1))
b_conv1 = tf.Variable(tf.constant(0.1, shape=[32]))

# 第一層のconvolutionalとpool
# strides[0] = strides[3] = 1固定
h_conv1 = tf.nn.relu(tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='SAME') + b_conv1)
# プーリングサイズ n*n にしたい場合 ksize=[1, n, n, 1]
h_pool1 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

# 第二層
W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1))
b_conv2 = tf.Variable(tf.constant(0.1, shape=[64]))
h_conv2 = tf.nn.relu(tf.nn.conv2d(h_pool1, W_conv2, strides=[1, 1, 1, 1], padding='SAME') + b_conv2)
h_pool2 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

# 第一層と第二層でreduceされてできた特徴に対してrelu
W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1024], stddev=0.1))
b_fc1 = tf.Variable(tf.constant(0.1, shape=[1024]))
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# Dropout
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# 出来上がったものに対してSoftmax
W_fc2 = tf.Variable(tf.truncated_normal([1024, 10], stddev=0.1))
b_fc2 = tf.Variable(tf.constant(0.1, shape=[10]))
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# 交差エントロピー
loss = -tf.reduce_sum(d * tf.log(y_conv))

train = tf.train.AdamOptimizer(1e-4).minimize(loss)

correct = tf.equal(tf.argmax(y_conv,1), tf.argmax(d,1))
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)


accuracies = []
for i in range(iters_num):
    x_batch, d_batch = mnist.train.next_batch(batch_size)
    sess.run(train, feed_dict={x: x_batch, d: d_batch, keep_prob: 1-dropout_rate})
    if (i+1) % plot_interval == 0:
        accuracy_val = sess.run(accuracy, feed_dict={x:x_batch, d: d_batch, keep_prob: 1.0})
        accuracies.append(accuracy_val)
        print('Generation: ' + str(i+1) + '. 正解率 = ' + str(accuracy_val))        
    
    
lists = range(0, iters_num, plot_interval)
plt.plot(lists, accuracies)
plt.title("accuracy")
plt.ylim(0, 1.0)
plt.show()                
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
Generation: 10. 正解率 = 0.28
Generation: 20. 正解率 = 0.59
Generation: 30. 正解率 = 0.63
Generation: 40. 正解率 = 0.75
Generation: 50. 正解率 = 0.71
Generation: 60. 正解率 = 0.84
Generation: 70. 正解率 = 0.86
Generation: 80. 正解率 = 0.83
Generation: 90. 正解率 = 0.85
Generation: 100. 正解率 = 0.85
Generation: 110. 正解率 = 0.91
Generation: 120. 正解率 = 0.89
Generation: 130. 正解率 = 0.91
Generation: 140. 正解率 = 0.92
Generation: 150. 正解率 = 0.9
Generation: 160. 正解率 = 0.94
Generation: 170. 正解率 = 0.93
Generation: 180. 正解率 = 0.93
Generation: 190. 正解率 = 0.93
Generation: 200. 正解率 = 0.95
Generation: 210. 正解率 = 0.93
Generation: 220. 正解率 = 0.94
Generation: 230. 正解率 = 0.86
Generation: 240. 正解率 = 0.94
Generation: 250. 正解率 = 0.97
Generation: 260. 正解率 = 0.92
Generation: 270. 正解率 = 0.96
Generation: 280. 正解率 = 0.92
Generation: 290. 正解率 = 0.96
Generation: 300. 正解率 = 0.98
In [ ]: