LoginSignup
14
16

More than 5 years have passed since last update.

TensorFlow入門時に多分一番単純で実用的なコード例(1次元入力データ群からのクラス分類)

Last updated at Posted at 2016-11-06

タイトル通りです。
特徴量を入力して分類・識別(回帰)するだけの単純なコード例が意外と無いので、自分で書いときます。
下の記事でやった単純なディープラーニングの実装のTensorFlow版です。

簡単なディープラーニングのサンプルコード (2入力1出力/2クラス分類) with Keras
http://qiita.com/ryo_grid/items/e746238c78b8c6427200

学習用データは作るのが面倒なので、学習処理のループのところで偶数奇数で分岐して食わせるデータを変えるということをしています。
学習時の回答データは、正解のラベルに対応する要素のみ1で他は0の配列を用意します。

simple_tf_regression.py
import tensorflow as tf

# number of inputs
input_len = 2
# number of classes 
classes_num = 2

sess = tf.Session()

x = tf.placeholder("float", [None, input_len])
y_ = tf.placeholder("float", [None, classes_num])

weights1 = tf.Variable(tf.truncated_normal([input_len, 50], stddev=0.0001))
biases1 = tf.Variable(tf.ones([50]))

weights2 = tf.Variable(tf.truncated_normal([50, 25], stddev=0.0001))
biases2 = tf.Variable(tf.ones([25]))

weights3 = tf.Variable(tf.truncated_normal([25, classes_num], stddev=0.0001))
biases3 = tf.Variable(tf.ones([classes_num]))

# This time we introduce a single hidden layer into our model...
hidden_layer_1 = tf.nn.relu(tf.matmul(x, weights1) + biases1)
hidden_layer_2 = tf.nn.relu(tf.matmul(hidden_layer_1, weights2) + biases2)
model = tf.nn.softmax(tf.matmul(hidden_layer_2, weights3) + biases3)

cost = -tf.reduce_sum(y_*tf.log(model))

training_step = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cost)

init = tf.initialize_all_variables()
sess.run(init)

for ii in range(10000):
    # y_ -> element of correct class only must be 1
    if ii % 2 == 0: # even number [1,2] => 0
        sess.run(training_step, feed_dict={x: [[1, 2]], y_: [[1, 0]]})
    else:           # odd number  [2,1] => 1
        sess.run(training_step, feed_dict={x: [[2, 1]], y_: [[0, 1]]})

# prediction
print("result of prediction --------")
pred_rslt = sess.run(tf.argmax(model, 1), feed_dict={x: [[1, 2]]})
print("  input: [1,2] =>" + str(pred_rslt))
pred_rslt = sess.run(tf.argmax(model, 1), feed_dict={x: [[2, 1]]})
print("  input: [2,1] =>" + str(pred_rslt))

実行結果

result of prediction --------
input: [1,2] =>[0]
input: [2,1] =>[1]

dropout入れた版 (11/8追記)

Keras版に合わせてdropoutを入れたものも書いてみました
https://github.com/ryogrid/learnDeepLearning/blob/master/simple_tf_regression_do.py

その他参考になる記事など

http://qiita.com/ryo_grid/items/2fadb2b1d16f0eab1582
http://www.buildinsider.net/small/booktensorflow/0001
http://msyksphinz.hatenablog.com/entry/2015/11/19/022254
http://qiita.com/tawago/items/c977c79b76c5979874e8
http://qiita.com/tawago/items/931bea2ff6d56e32d693

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16