学习来源:莫烦python教学中的tensorflow
实验代码如下:
import tensorflow as tf
import numpy as npx_data=np.random.rand(100).astype(np.float32)#生成100个随机数
y_data=x_data*0.1+0.3
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_variable_initializer()#这种方法我试过, 但会弹出错误'module' object has no attribute 'global_variable_initializer'
init=tf.initialize_all_variables()
sess=tf.Session()
sess.run(init)
for step in range(201):
sess.run(train)
if step%20==0:
print(step,sess.run(Weights),sess.run(biases))
在ubuntu上运行结果:(我用的python3.4.3)
0 [-0.15739977] [ 0.56689346]
20 [ 0.01819029] [ 0.34104016]
40 [ 0.07859091] [ 0.31073996]
60 [ 0.0943974] [ 0.30281058]
80 [ 0.09853383] [ 0.30073553]
100 [ 0.09961632] [ 0.30019248]
120 [ 0.09989959] [ 0.30005038]
140 [ 0.09997372] [ 0.30001318]
160 [ 0.09999313] [ 0.30000347]
180 [ 0.09999822] [ 0.30000091]
200 [ 0.09999955] [ 0.30000025]
权值和偏值拟合的比较好。