Tensorflow实例1——拟合曲线y=x^2+1

 

import numpy as np
import matplotlib.pyplot as plt

num_points = 10000   #随机生成10000个点(近似y=x^2+1)
vectors_set = []
for i in range(num_points):
     x1= np.random.normal(0.0, 2.0)
     y1= x1 * x1 + 1 + np.random.normal(0.0, 0.03)
     vectors_set.append([x1, y1])
        
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]
 
 
 
#Graphic display
plt.plot(x_data, y_data, 'ro')
plt.legend()
plt.show()

import tensorflow as tf
 
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
y = W * x_data * x_data + b

loss = tf.reduce_mean(tf.square(y - y_data))   #损失函数(方差)
optimizer = tf.train.AdamOptimizer(0.05)       #使用Adam优化器,学习率0.05
train = optimizer.minimize(loss)               #

init = tf.initialize_all_variables()           #初始化变量

sess = tf.Session()
sess.run(init)

for step in range(200):
     sess.run(train)
     if step % 10 == 0:
         print(step, sess.run(W), sess.run(b))
         print(step, sess.run(loss))
 
         #Graphic display
         plt.plot(x_data, y_data, 'ro')
         plt.plot(x_data, sess.run(W) * x_data * x_data + sess.run(b))
         plt.xlabel('x')
         plt.xlim(-8,8)
         plt.ylim(0,60)
         plt.ylabel('y')
         plt.legend()
         plt.show()

 

运行效果如下:

在200次训练过后,可以看到w和b已经非常接近设置的w=1和b=1,从图中可以看出训练的过程(未放出,可自行尝试)

点赞

发表评论