TensorFlow-Variable和Session实际操练

版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/samylee/article/details/84643394

tensorflow完成一次线性优化实例

硬件:NVIDIA-GTX1080

软件:Windows7、python3.6.5、tensorflow-gpu-1.4.0

一、基础知识

定义两个序列,求出序列的权重和偏置

二、代码展示

import tensorflow as tf
import numpy as np

#create 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.global_variables_initializer()
#create tensorflow structure end

sess = tf.Session()
sess.run(init) #remember?

for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(Weights), sess.run(Biases))

sess.close()

三、结果展示

0 [-0.3038275] [0.7421163]
20 [-0.00337278] [0.35705975]
40 [0.07848056] [0.31187832]
60 [0.09552025] [0.30247274]
80 [0.09906745] [0.30051476]
100 [0.09980587] [0.30010718]
120 [0.09995961] [0.3000223]
140 [0.0999916] [0.30000466]
160 [0.09999825] [0.30000097]
180 [0.09999964] [0.30000022]
200 [0.09999991] [0.30000007]

任何问题请加唯一QQ2258205918(名称samylee)!

猜你喜欢

转载自blog.csdn.net/samylee/article/details/84643394