博客存档TensorFlow入门一 1.4编程练习

 

 

 1 import tensorflow as tf
 2 import numpy
 3 import matplotlib.pyplot as plt
 4 #from sklearn.model_selection import train_test_split
 5 rng = numpy.random
 6 
 7 # Parameters
 8 learning_rate = 0.01
 9 training_epochs = 2000
10 display_step = 50
11 
12 # Training Data
13 train_X = numpy.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])
14 train_Y = numpy.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])
15 n_samples = train_X.shape[0]
16 
17 # tf Graph Input
18 X = tf.placeholder("float")
19 Y = tf.placeholder("float")
20 
21 # Create Model
22 
23 # Set model weights
24 W = tf.Variable(rng.randn(), name="weight")
25 b = tf.Variable(rng.randn(), name="bias")
26 
27 # Construct a linear model
28 activation = tf.add(tf.mul(X, W), b)
29 
30 # Minimize the squared errors
31 cost = tf.reduce_sum(tf.pow(activation-Y, 2))/(2*n_samples)   #L2 loss
32 
33  #reduce_sum:把里面的平方求和
34  # pow(x,y):这个是表示x的y次幂。
35 
36 optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
37 
38 #Gradient descent
39 
40 # Initializing the variables
41 init = tf.initialize_all_variables()
42 
43 # Launch the graph
44 with tf.Session() as sess:
45     sess.run(init)
46 
47     # Fit all training data
48     for epoch in range(training_epochs):
49         for (x, y) in zip(train_X, train_Y):
50             sess.run(optimizer, feed_dict={X: x, Y: y})
51               #zip:对应的元素打包成一个个元组
52         #Display logs per epoch step
53         if epoch % display_step == 0:
54             print("Epoch:", '%04d' % (epoch+1), "cost=", \
55                 "{:.9f}".format(sess.run(cost, feed_dict={X: train_X, Y:train_Y})), \
56                 "W=", sess.run(W), "b=", sess.run(b))
57 
58     print("Optimization Finished!")
59     print("cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), \
60           "W=", sess.run(W), "b=", sess.run(b))
61 
62     #Graphic display
63     plt.plot(train_X, train_Y, 'ro', label='Original data')
64     plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
65     plt.legend()
66     plt.show()

猜你喜欢

转载自www.cnblogs.com/captain-dl/p/9270926.html