TensorFlow学习:线性回归算法

The linear regression algorithm

we begin our exploration of machine learning techniques with the linear regression algorithm. Our goal is to build a model by which to predict the values of a dependent variable from the values of one or more independent variables.

The relationship between these two variables is linear; that is, if y is the dependent variable and x the independent, then the linear relationship between the two variables will look like this: y = Ax + b.

The linear regression algorithm adapts to a great variety of situations; for its versatility, it is used extensively in the field of applied sciences, for example, biology and economics.

Furthermore, the implementation of this algorithm allows us to introduce in a totally clear and understandable way the two important concepts of machine learning: the cost function and the gradient descent algorithms.

Data model

The first crucial step is to build our data model. We mentioned earlier that the relationship between our variables is linear, that is: y = Ax + b, where A and b are constants. To test our algorithm, we need data points in a two-dimensional space.

We start by importing the Python library NumPy:

import numpy as np

Then we define the number of points we want to draw:

number_of_points = 500

We initialize the following two lists:

x_point = []
y_point = []

These points will contain the generated points.

We then set the two constants that will appear in the linear relation of y with x:

a = 0.22
b = 0.78

Via NumPy's random.normal function, we generate 300 random points around the regression equation y = 0.22x + 0.78:

for i in range(number_of_points):
    x = np.random.normal(0.0,0.5)
    y = a*x + b +np.random.normal(0.0,0.1)
    x_point.append([x])
    y_point.append([y])

Finally, view the generated points by matplotlib:

import matplotlib.pyplot as plt
plt.plot(x_point,y_point, 'o', label='Input Data')
plt.legend()
plt.show()
Linear regression: The data model
Cost functions and gradient descent

The machine learning algorithm that we want to implement with TensorFlow must predict values of y as a function of x data according to our data model. The linear regression algorithm will determine the values of the constants A and b (fixed for our data model), which are then the true unknowns of the problem.

The first step is to import the tensorflow library:

import tensorflow as tf

Then define the A and b unknowns, using the TensorFlow tf.Variable:

A = tf.Variable(tf.random_uniform([1], -1.0, 1.0))

The unknown factor A was initialized using a random value between -1 and 1, while the variable b is initially set to zero:

b = tf.Variable(tf.zeros([1]))

So we write the linear relationship that binds y to x:

y = A * x_point + b

Now we will introduce, this cost function: that has parameters containing a pair of values A and b to be determined which returns a value that estimates how well the parameters are correct. In this example, our cost function is mean square error:

cost_function = tf.reduce_mean(tf.square(y - y_point))

It provides an estimate of the variability of the measures, or more precisely, of the dispersion of values around the average value; a small value of this function corresponds to a best estimate for the unknown parameters A and b.

To minimize cost_function, we use an optimization algorithm with the gradient descent. Given a mathematical function of several variables, gradient descent allows to find a local minimum of this function. The technique is as follows:

Evaluate, at an arbitrary first point of the function's domain, the function itself and its gradient. The gradient indicates the direction in which the function tends to a minimum.

Select a second point in the direction indicated by the gradient. If the function for this second point has a value lower than the value calculated at the first point, the descent can continue.

You can refer to the following figure for a visual explanation of the algorithm:

The gradient descent algorithm

We also remark that the gradient descent is only a local function minimum, but it can also be used in the search for a global minimum, randomly choosing a new start point once it has found a local minimum and repeating the process many times. If the number of minima of the function is limited, and there are very high number of attempts, then there is a good chance that sooner or later the global minimum will be identified.

Using TensorFlow, the application of this algorithm is very simple. The instruction are as follows:

optimizer = tf.train.GradientDescentOptimizer(0.5)

Here 0.5is the learning rate of the algorithm.

The learning rate determines how fast or slow we move towards the optimal weights. If it is very large, we skip the optimal solution, and if it is too small, we need too many iterations to converge to the best values.

An intermediate value (0.5) is provided, but it must be tuned in order to improve the performance of the entire procedure.

We define train as the result of the application of the cost_function
(optimizer), through its minimizefunction:

train = optimizer.minimize(cost_function)

Testing the model

Now we can test the algorithm of gradient descent on the data model you created earlier. As usual, we have to initialize all the variables:

model = tf.initialize_all_variables()

So we build our iteration (20 computation steps), allowing us to determine the best values of A and b, which define the line that best fits the data model. Instantiate the evaluation graph:

with tf.Session() as session:

We perform the simulation on our model:

session.run(model) for step in range(0,21):

For each iteration, we execute the optimization step:

session.run(train)

Every five steps, we print our pattern of dots:

if (step % 5) == 0: 
          plt.plot(x_point,y_point,'o',
               label='step = {}'         
               .format(step))

And the straight lines are obtained by the following command:

                   plt.plot(x_point,
                              session.run(A) * 
                              x_point + 
                              session.run(B))
                     plt.legend()
                     plt.show()

The following figure shows the convergence of the implemented algorithm:

Linear regression : start computation (step = 0)

After just five steps, we can already see (in the next figure) a substantial improvement in the fit of the line:

Linear regression: situation after 5 computation steps
Linear regression: situation after 5 computation steps

The following (and final) figure shows the definitive result after 20 steps. We can see the efficiency of the algorithm used, with the straight line efficiency perfectly across the cloud of points.

Linear regression: final result
Linear regression: final result

Finally we report, to further our understanding, the complete code:

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
number_of_points = 200
x_point = []
y_point = []
a = 0.22
b = 0.78
for i in range(number_of_points):
    x = np.random.normal(0.0,0.5)
    y = a*x + b +np.random.normal(0.0,0.1)
    x_point.append([x])
    y_point.append([y])
plt.plot(x_point,y_point, 'o', label='Input Data')
plt.legend()
plt.show()
A = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
B = tf.Variable(tf.zeros([1]))
y = A * x_point + B
cost_function = tf.reduce_mean(tf.square(y - y_point))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(cost_function)
model = tf.initialize_all_variables()
with tf.Session() as session:
        session.run(model)
        for step in range(0,21):
                session.run(train)
                if (step % 5) == 0:
                        plt.plot(x_point,y_point,'o',
                                 label='step = {}'
                                 .format(step))
                        plt.plot(x_point,
                                 session.run(A) * 
                                 x_point + 
                                 session.run(B))
                        plt.legend()
                        plt.show()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,552评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,666评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,519评论 0 334
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,180评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,205评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,344评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,781评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,449评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,635评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,467评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,515评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,217评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,775评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,851评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,084评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,637评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,204评论 2 341

推荐阅读更多精彩内容