LoginSignup
5
7

More than 5 years have passed since last update.

TensorFlowでカスみたいな線形回帰(Linear Regression)

Posted at

TensorFlowでカスみたいな線形回帰をやってみます。ダミーデータを作り、回帰直線が「Y = 2X + 3」になるようにがんばってみます :muscle:

linearRegression.py
import tensorflow as tf
import numpy

#学習率
learning_rate = 0.01
training_epochs = 1000
display_step = 100

# -1から1を100等分した数値が入った配列
train_X = numpy.linspace(-1, 1, 100)

# shapeで配列の次元数を取得
# 誤差を生成
err = numpy.random.randn(*train_X.shape) * 0.5
# Y = 2X + 3に誤差を加える
train_Y = 2 * train_X + 3 + err

n_samples = train_X.shape[0]

#モデルを作成(placeholderのインスタンスを作成)
X = tf.placeholder("float")
Y = tf.placeholder("float")

#重み
W = tf.Variable(numpy.random.randn(), name="weight")
#バイアス
b = tf.Variable(numpy.random.randn(), name="bias")

# Y = X * W + b
activation = tf.add(tf.mul(X, W), b)

#目的関数(二乗誤差の平均)
cost = tf.reduce_sum(tf.pow(activation - Y, 2) / (2 * n_samples))
#最急降下法
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)


init = tf.initialize_all_variables()

with tf.Session() as sess:
  #セッション開始
  sess.run(init)

  for epoch in range(training_epochs):
    for(x, y) in zip(train_X, train_Y):
      # placeholderでX,Yを定義したのでfeed_dictで渡して、sessionを実行
      sess.run(optimizer, feed_dict={X: x, Y: y})

    if epoch % display_step == 0:
      print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(sess.run(cost, feed_dict={X: train_X, Y:train_Y})), \
              "W=", sess.run(W), "b=", sess.run(b))

  print("Optimization Finished!")
  training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
  print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

データを作る

linspace

numpy.linspace — NumPy v1.10 Manual

shape

numpy.ndarray.shape — NumPy v1.10 Manual

randn

numpy.matlib.randn — NumPy v1.10 Manual

モデルの作成

reduce_sum

各行列の要素を足し合わせ0階テンソルを返す。
Math reduce_sum

学習する(Running Graphs)

session

Running Graphs session

zip

2つの変数を同時に繰り返す。
forループで便利な zip, enumerate関数 | Python Snippets

学習結果

Epoch: 0001 cost= 7.190456867 W= -1.00389 b= -0.309475
Epoch: 0101 cost= 1.629324675 W= -0.168345 b= 1.81013
Epoch: 0201 cost= 0.614938080 W= 0.427797 b= 2.58925
Epoch: 0301 cost= 0.344420433 W= 0.852618 b= 2.87544
Epoch: 0401 cost= 0.240160167 W= 1.15516 b= 2.98041
Epoch: 0501 cost= 0.191739887 W= 1.37056 b= 3.01882
Epoch: 0601 cost= 0.167796254 W= 1.52389 b= 3.03281
Epoch: 0701 cost= 0.155743539 W= 1.63303 b= 3.03784
Epoch: 0801 cost= 0.149647340 W= 1.71071 b= 3.03962
Epoch: 0901 cost= 0.146560609 W= 1.76599 b= 3.04021
Optimization Finished!
Training cost= 0.145008 W= 1.805 b= 3.04038

costが小さくなり、「Y = 2X + 3」に値が近づいているのがわかりました :smile:

参考

TensorFlowで線形回帰を実装してみる - もふもふ技術部
TensorFlow-Examples/linear_regression.py at master · aymericdamien/TensorFlow-Examples
TensorFlowを算数で理解する - Qiita

5
7
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
5
7