tensorflow 学习笔记(2)-basic_example

来源:互联网 发布:苹果mac爱奇艺视频 编辑:程序博客网 时间:2024/06/06 16:26

tensorflow 学习笔记(2)-basic_example

  1. linear_regression
import tensorflow as tfimport matplotlib.pyplot as pltimport numpy as nptrain_epochs = 1000 # the step of epochdiaplay_step = 50learn_rate = 0.01 # the learning rate of GradientDescentOptimizer# the data set of trainingtrain_x=np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])train_y=np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])# tf graph inputX = tf.placeholder("float")Y = tf.placeholder("float")n_sample = train_x.shape[0]# set model weightsW = tf.Variable(np.random.randn(), name = "weight")b = tf.Variable(np.random.randn(), name = "bias")# construct a  linear modelpred = tf.add(tf.multiply(X, W), b)# MSEcost = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_sample)optimizer=tf.train.GradientDescentOptimizer(learn_rate).minimize(cost)init = tf.global_variables_initializer()# Initializing the variableswith tf.Session() as sess:    sess.run(init)    for epoch in range(train_epochs):        for (x, y) in zip(train_x, train_y):            sess.run(optimizer, feed_dict = {X: x, Y: y})        if (epoch + 1) % 50 == 0:            c = sess.run(cost, feed_dict = {X: train_x, Y: train_y})            print("Epoch: ", epoch + 1, "cost = ", c , "W = ", sess.run(W), "b = ", sess.run(b))    print("Optimization Finished!")    train_cost = sess.run(cost, feed_dict = {X: train_x, Y: train_y})    print("Training cost = ", train_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, train_x * sess.run(W) + sess.run(b), label = "Fitted line")    plt.legend()    plt.show()    # Testing example,    test_x = numpy.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])    test_y = numpy.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03])    print("Testing... (Mean square loss Comparison)")    test_cost = sess.run(tf.reduce_sum(tf.pow(pred - Y, 2))/(2 * test_x.shape[0]), feed_dict = {X:test_x,Y:test_y})    print("Testing cost: ", test_cost)    print("Absolute mean square loss difference: ",abs( test_cost - train_cost))    # Graphic display    plt.plot(test_x, test_y, "bo", label = "Testing data")    plt.plot(test_x, test_x * sess.run(W) + sess.run(b),label = "Fitted line")    plt.legend()    plt.show()

这里写图片描述
这里写图片描述
这里写图片描述

原创粉丝点击