Tensorflow机器学习1 入门案例

任务1:产生100个随机数x,y=0.1*x+0.3
通过这些数据,得到预测的weights和biases,使之接近0.1和0.3

import tensorflow as tf
import numpy as np

#P9 例子2 https://www.bilibili.com/video/av16001891/?p=9

#创建100个[0,1)的随机数
xData = np.random.rand(100).astype(np.float32) #tensorflow中一般都是float32格式

#预测的weights应接近0.1,biases接近于0.3
yData = xData*0.1+0.3

#创建tensorflow结构  start###

#Weights大写是因为其可能是矩阵,[1]表明是一个1维的数,位于-1和1之间均匀分布
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
#biases初始值时0
biases  = tf.Variable(tf.zeros([1]))

#预测的y
y = Weights*xData+biases


#预测的y和yDate的误差
loss = tf.reduce_mean(tf.square(y-yData))
#创建神经网络优化器,学习效率 = 0.5
optimizer = tf.train.GradientDescentOptimizer(0.5)
#利用优化器减少误差
train = optimizer.minimize(loss)

#初始化
init = tf.global_variables_initializer()
#创建tensorflow结构  end###

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))

sess.close()

运行结果:

0 [0.19668129] [0.32946035]
20 [0.11306386] [0.29339242]
40 [0.10262074] [0.29867446]
60 [0.10052574] [0.29973412]
80 [0.10010545] [0.29994667]
100 [0.10002115] [0.2999893]
120 [0.10000426] [0.29999787]
140 [0.10000084] [0.2999996]
160 [0.10000016] [0.29999992]
180 [0.1000001] [0.29999995]
200 [0.1000001] [0.29999995]

你可能感兴趣的:(Tensorflow机器学习1 入门案例)