私は,"詳解 ディープラーニング"(ISBN:9784839962517)「詳解 ディープラーニング」の本で勉強しています.
そこで4章でmnistのデータで簡単なニューラルネットワークを作りました.
本ではkerasのみの実装でtensorflowがなかったのでtensorflowで同じモデルを作ることを試みました.
import numpy as np
import tensorflow as tf
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
#7000070000のデータから10000だけ選ぶ
n = len(mnist.data)
N = 1000
indices = np.random.permutation(range(n))[:N]
X = mnist.data[indices]
y = mnist.target[indices]
Y = np.eye(10)[y.astype(int)]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size = 0.8)
#モデルの設定
n_in = len(X[0])
n_hidden = 200
n_out = 10
x = tf.placeholder(tf.float32,shape = [None,n_in])
t = tf.placeholder(tf.float32,shape = [None,n_out])
#入力~隠れ層
W = tf.Variable(tf.truncated_normal([n_in,n_hidden]))
b = tf.Variable(tf.zeros([n_hidden]))
h = tf.nn.sigmoid(tf.matmul(x,W) + b)
#隠れ層~出力
V = tf.Variable(tf.truncated_normal([n_hidden,n_out]))
c = tf.Variable(tf.zeros([n_out]))
y = tf.nn.softmax(tf.matmul(h,V)+ c)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(t * tf.log(y),reduction_indices = [1]))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(t,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
epochs = 1000
batch_size = 100
n_batches = epochs // batch_size
#モデルの学習
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for epoch in range(epochs):
X_, Y_ = shuffle(X_train,Y_train)
for i in range(n_batches):
start = batch_size * i
end = start + batch_size
sess.run(train_step, feed_dict = {
x:X_[start:end],
t:Y_[start:end]
})
accuracy_rate = accuracy.eval(session = sess, feed_dict = {
x:X_test,
t:Y_test
})
print(accuracy_rate)