train_action

 

 

# 导入数值计算模块
import numpy as np
import tensorflow as tf

# 创建计算会话
sess = tf.Session()
# 生成数据,创建占位符和变量A
x_vales = np.random.normal(1, 0.1, 100)
y_vals = np.repeat(10., 100)
x_data = tf.placeholder(shape=[1], dtype=tf.float32)
y_target = tf.placeholder(shape=[1], dtype=tf.float32)
A = tf.Variable(tf.random_normal(shape=[1]))

# 增加乘法操作
my_output = tf.multiply(x_data, A)
# 增加L2正则损失函数
loss = tf.square(my_output - y_target)

# 在运行之前,需要初始化变量
#init = tf.initialize_all_tables()
init = tf.tables_initializer()
sess.run(init)

# 声明变量的优化器

# 学习率的选取
my_opt = tf.train.GradientDescentOptimizer(learning_rate=0.2)
train_step = my_opt.minimize(loss)

# 训练算法
for i in range(100):
    rand_index = np.random.choice(100)
    rand_x = [x_vales[rand_index]]
    rand_y = [y_vals[rand_index]]
    sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})
    if (i + 1) % 25 == 0:
        print('Step #' + str(i + 1) + 'A = ' + str(sess.run(A)))
        print('Loss = ' + str(sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})))
#
d = 3

 

 

 

 

An Op that initializes all tables. Note that if there are not tables the returned Op is a NoOp.

 

posted @ 2018-05-11 21:12  papering  阅读(219)  评论(0编辑  收藏  举报