■ 선형 회귀 알고리즘을 사용하는 방법을 보여준다.
▶ linear_regression.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import matplotlib.pyplot as pp import numpy as np import tensorflow as tf pointCount = 200 xList = [] yList = [] a = 0.22 b = 0.78 for i in range(pointCount): x = np.random.normal(0.0, 0.5) y = a * x + b + np.random.normal(0.0, 0.1) xList.append(x) yList.append(y) pp.plot(xList, yList, "o", label = "Input Data") pp.legend() pp.show() aVariable = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) bVariable = tf.Variable(tf.zeros([1])) yTensor = aVariable * xList + bVariable costTensor = tf.reduce_mean(tf.square(yTensor - yList)) optimizer = tf.train.GradientDescentOptimizer(0.5) trainOperation = optimizer.minimize(costTensor) initializerOperation = tf.global_variables_initializer() with tf.Session() as session: session.run(initializerOperation) for step in range(0, 21): session.run(trainOperation) if (step % 5) == 0: pp.plot(xList, yList, "o", label = "step = {0}".format(step)) pp.plot(xList, session.run(aVariable) * xList + session.run(bVariable)) pp.legend() pp.show() |