初识session

功能:拟合y=0.1x+0.3,python代码

#encoding=utf-8

import tensorflow as tf

import numpy as np

#creat data

#创建100个随机数,及真实输出

x_data = np.random.rand(100).astype(np.float32)

y_data = x_data*0.1+0.3

#create tensorflow structure start#

#定义权重(1维,-1~1之间)和偏置(1维,0)

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

train = optimizer.minimize(loss)

#初始化变量init

init = tf.initialize_all_variables()

#create tensorflow structure end#

#创建会话

sess = tf.Session()

#会话初始化

sess.run(init)

#训练201步

for step in range(201):

#执行一次训练

    sess.run(train)

    if step % 20 == 0:

        print step,sess.run(Weights),sess.run(biases)#输出参数查看效果

你可能感兴趣的:(初识session)