tensorflow tutorials(二):用tensorflow建立岭回归模型


声明:版权所有,转载请联系作者并注明出


岭回归模型与线性回归模型的不同点在于损失函数加了权重的范数



from __future__ import print_function

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline


# Parameters
learning_rate = 0.01
training_epochs = 1000
display_step = 50

# Generate the training data
train_X = np.linspace(-1, 1, 200)
train_Y = 2*train_X + np.random.randn(*train_X.shape)*0.2

n_samples = train_X.shape[0]

# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Initialize the variable w and b
W = tf.Variable(np.random.randn(), name="weight")
b = tf.Variable(np.random.randn(), name="bias")

# Define the linear model
pred = tf.add(tf.mul(X, W), b)

# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
cost = tf.add(cost, tf.mul(1e-6, tf.global_norm([W])))

# Build the optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Fit all training data
    for epoch in range(training_epochs):
        for (x, y) in zip(train_X, train_Y):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "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')
    
    # Graphic display
    plt.plot(train_X, train_Y, 'ro', label='Original data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()

    # Generate the test data
    test_X = np.linspace(-1, 1, 100)
    test_Y = 2*test_X + np.random.randn(*test_X.shape)*0.2

    print("Testing... (Mean square loss Comparison)")
    testing_cost = sess.run(
        tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * test_X.shape[0]),
        feed_dict={X: test_X, Y: test_Y})  # same function as cost above
    print("Testing cost=", testing_cost)
    print("Absolute mean square loss difference:", abs(
        training_cost - testing_cost))

    plt.plot(test_X, test_Y, 'bo', label='Testing data')
    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
    plt.legend()
    plt.show()
Epoch: 0050 cost= 1.009541750 W= -0.33969 b= 0.376634
Epoch: 0100 cost= 0.702758729 W= 0.0235049 b= 0.232964
Epoch: 0150 cost= 0.498448133 W= 0.330189 b= 0.14565
Epoch: 0200 cost= 0.357965827 W= 0.589313 b= 0.0925447
Epoch: 0250 cost= 0.259650648 W= 0.808264 b= 0.0602112
Epoch: 0300 cost= 0.190185249 W= 0.993274 b= 0.0404949
Epoch: 0350 cost= 0.140851215 W= 1.14962 b= 0.0284476
Epoch: 0400 cost= 0.105722852 W= 1.28173 b= 0.0210654
Epoch: 0450 cost= 0.080674000 W= 1.39336 b= 0.0165246
Epoch: 0500 cost= 0.062797219 W= 1.48771 b= 0.0137168
Epoch: 0550 cost= 0.050037120 W= 1.56741 b= 0.0119684
Epoch: 0600 cost= 0.040922150 W= 1.63479 b= 0.0108697
Epoch: 0650 cost= 0.034413237 W= 1.69173 b= 0.0101709
Epoch: 0700 cost= 0.029763201 W= 1.73985 b= 0.00971972
Epoch: 0750 cost= 0.026443416 W= 1.78049 b= 0.00942297
Epoch: 0800 cost= 0.024071420 W= 1.81484 b= 0.00922345
Epoch: 0850 cost= 0.022376413 W= 1.84387 b= 0.0090859
Epoch: 0900 cost= 0.021165809 W= 1.86839 b= 0.00898854
Epoch: 0950 cost= 0.020300159 W= 1.88912 b= 0.00891769
Epoch: 1000 cost= 0.019681456 W= 1.90664 b= 0.00886476
Optimization Finished!
Training cost= 0.0196815 W= 1.90664 b= 0.00886476 


Testing... (Mean square loss Comparison)
Testing cost= 0.0167068
Absolute mean square loss difference: 0.00297463


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值