预测线性回归方程:y = 0.1*x + 0.3
# -*- coding: utf-8 -*-
"""
Created on Tue May 11 11:56:47 2021
@author: monastic
"""
生成训练数据
import tensorflow as tf
import numpy as np
#creat data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1+0.3
create tensorflow structure start
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights*x_data + biases
损失函数
loss = tf.reduce_mean(tf.square(y-y_data))
优化器
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
初始化变量
init = tf.initialize_all_variables()
create tensorflow structure end
迭代201次
sess = tf.Session()
sess.run(init) #very important
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step,sess.run(Weights),sess.run(biases))
运行结果
0 [0.47600085] [0.1285792]
20 [0.18036349] [0.25675154]
40 [0.11778681] [0.29042786]
60 [0.10393675] [0.2978814]
80 [0.10087132] [0.2995311]
100 [0.10019284] [0.29989624]
120 [0.10004268] [0.29997703]
140 [0.10000945] [0.29999495]
160 [0.1000021] [0.29999888]
180 [0.10000046] [0.29999977]
200 [0.1000001] [0.29999995]