[TensorFlow] demo1 完整的代码和运行结果

import tensorflow as tf
import numpy as np


x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3
#print(x_data)
#print(y_data)
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))

#print(tf.random_uniform([1], -1.0, 1.0))
#print(tf.Variable(tf.zeros([1])))
#print(Weights)
#print(Weights)

y = Weights*x_data + biases
#tf.square(y-y_data)
#print(tf.square(y-y_data))

loss = tf.reduce_mean(tf.square(y-y_data))

optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

#init = tf.initialize_all_variables() # old api 
init = tf.global_variables_initializer() #new api

sess = tf.Session()
sess.run(init)
#print(sess.run(init))
#print(sess.run(train))

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

[TensorFlow] demo1 完整的代码和运行结果_第1张图片


由结果可以看出:

y_data = x_data*0.1 + 0.3 

0.1 = 0.10000084

0.3 = 0.29999959

这么说的话,我们的一次函数的模型就建立起来了。

你可能感兴趣的:(Python,TensorFlow)