最近在学习TensorFlow
记录一下学习要点
贴一下学习的代码:
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
### creat 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()### creat tensorflow structure end ###
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))
然后讲到了Session的两种打开方式 一种是直接打开
sess = tf.Session()
但是这种方式在最后需要对Session进行close
sess.close()
另外一种是利用python中的with进行打开
with tf.Session() as sess:
执行循环体
这种方式类似于for循环,可以在执行完with之后自动关闭Session,从而不用执行tf.Session.close()