1
+ import tensorflow as tf
2
+ import numpy
3
+ import matplotlib .pyplot as plt
4
+ rng = numpy .random
5
+
6
+ # Parameters
7
+ learning_rate = 0.01
8
+ training_epochs = 2000
9
+ display_step = 50
10
+
11
+ # Training Data
12
+ 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 ])
13
+ 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 ])
14
+
15
+ # Create Model
16
+ W = tf .Variable (rng .randn (), name = "weight" )
17
+ b = tf .Variable (rng .randn (), name = "bias" )
18
+
19
+ X = tf .placeholder ("float" )
20
+ Y = tf .placeholder ("float" )
21
+ n_samples = train_X .shape [0 ]
22
+
23
+ activation = tf .add (tf .mul (X , W ), b ) #linear
24
+ cost = tf .reduce_sum (tf .pow (activation - Y , 2 ))/ (2 * n_samples ) #L2
25
+
26
+ optimizer = tf .train .GradientDescentOptimizer (learning_rate ).minimize (cost )
27
+
28
+ init = tf .initialize_all_variables ()
29
+
30
+ with tf .Session () as sess :
31
+ sess .run (init )
32
+
33
+ for epoch in range (training_epochs ):
34
+ for (x , y ) in zip (train_X , train_Y ):
35
+ sess .run (optimizer , feed_dict = {X : x , Y : y })
36
+
37
+ if epoch % display_step == 0 :
38
+ print "Epoch:" , '%04d' % (epoch + 1 ), "cost=" , "{:.9f}" .format (sess .run (cost , feed_dict = {X : train_X , Y :train_Y })), \
39
+ "W=" , sess .run (W ), "b=" , sess .run (b )
40
+
41
+ print "Optimization Finished!"
42
+ print "cost=" , sess .run (cost , feed_dict = {X : train_X , Y : train_Y }), "W=" , sess .run (W ), "b=" , sess .run (b )
43
+
44
+ plt .plot (train_X , train_Y , 'ro' , label = 'Original data' )
45
+ plt .plot (train_X , sess .run (W ) * train_X + sess .run (b ), label = 'Fitted line' )
46
+ plt .legend ()
47
+ plt .show ()
0 commit comments