sess.run([], feed_dict={})

"""
在tensorflow中,tf.gradients()的参数如下:
tf.gradients(ys, xs,
             grad_ys=None,
             name='gradients',
             colocate_gradients_with_ops=False,
             gate_gradients=False,
             aggregation_method=None,
             stop_gradients=None)
以线性回归为例,实践tf.gradients()的基础功能。线性回归:y=3*x+2
"""
import numpy as np
import tensorflow as tf

sess = tf.Session()

x_input = tf.placeholder(tf.float32, name="x_input")
y_input = tf.placeholder(tf.float32, name="y_input")
# print("x_input:", x_input)
# print("y_input:", y_input)

w = tf.Variable(2.0, name="weight")
b = tf.Variable(1.0, name="biases")
# print("w:", w)
# print("b:", b)
y = tf.add(tf.multiply(x_input, w), b)

loss_op = tf.reduce_sum(tf.pow(y_input - y, 2)) / (2 * 32)
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss_op)

'''tensorboard'''
gradients_node = tf.gradients(loss_op, w)

init = tf.global_variables_initializer()
sess.run(init)

"""构造数据集"""
x_pure = np.random.randint(-10, 100, 1000)# low high size
# print("x_pure:", x_pure) 32
"""
x_pure: [43 35 10 -2 37 24 49 66 -8 94 71 49  1 85 87 47 77 -7 16 21 84 85 56 80
 51 18 34 27 88 14 17 96]
len(x_pure): 32
"""
# print("len(x_pure):", len(x_pure))

x_train = x_pure + np.random.randn(1000) / 10 # 为x加噪声
# print("x_train:", x_train)
y_train = 3 * x_pure + 2 + np.random.randn(1000) / 10 # 为y加噪音

for i in range(500):              # 这是输出列表
    _, gradients, loss = sess.run([train_op, gradients_node,loss_op],
                                  feed_dict={x_input: x_train[i], y_input: y_train[i]})
                                  # 参数,一般从函数开始就开始了,place,x_input = tf.placeholder(tf.float32, name="x_input")
    print("epoch: {} \t loss: {} \t gradients: {}".format(i, loss, gradients))
    
ans_w = sess.run(w)
ans_b = sess.run(b)
print("ans_w:", ans_w)
print("ans_b:", ans_b)
sess.close()



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值