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)

# 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= 0.279346764 W= 0.906848 b= -0.289415
Epoch: 0100 cost= 0.190719262 W= 1.08085 b= -0.172213
Epoch: 0150 cost= 0.137108132 W= 1.22794 b= -0.10121
Epoch: 0200 cost= 0.102369718 W= 1.35228 b= -0.058217
Epoch: 0250 cost= 0.078859627 W= 1.45738 b= -0.0322007
Epoch: 0300 cost= 0.062546395 W= 1.5462 b= -0.0164717
Epoch: 0350 cost= 0.051067844 W= 1.62127 b= -0.00697438
Epoch: 0400 cost= 0.042932797 W= 1.68473 b= -0.00125022
Epoch: 0450 cost= 0.037147172 W= 1.73835 b= 0.00219109
Epoch: 0500 cost= 0.033023905 W= 1.78365 b= 0.00425255
Epoch: 0550 cost= 0.030082876 W= 1.82193 b= 0.00548112
Epoch: 0600 cost= 0.027983051 W= 1.85429 b= 0.00620784
Epoch: 0650 cost= 0.026483836 W= 1.88163 b= 0.00663306
Epoch: 0700 cost= 0.025413597 W= 1.90473 b= 0.00687784
Epoch: 0750 cost= 0.024649082 W= 1.92426 b= 0.00701518
Epoch: 0800 cost= 0.024103273 W= 1.94076 b= 0.0070891
Epoch: 0850 cost= 0.023713501 W= 1.95469 b= 0.00712603
Epoch: 0900 cost= 0.023435200 W= 1.96647 b= 0.00714172
Epoch: 0950 cost= 0.023235969 W= 1.97644 b= 0.00714552
Epoch: 1000 cost= 0.023093617 W= 1.98488 b= 0.007143
Optimization Finished!
Training cost= 0.0230936 W= 1.98488 b= 0.007143 


Testing... (Mean square loss Comparison)
Testing cost= 0.0219461
Absolute mean square loss difference: 0.00114749

猜你喜欢

转载自blog.csdn.net/fdbvm/article/details/80984107