实现一个简单函数
声明a和b为变量,x为占位符。向目标值50优化输出结果。
代码如下:
import tensorflow as tf
import numpy as np
sess=tf.Session()
a=tf.Variable(tf.constant(1.))
b=tf.Variable(tf.constant(1.))
x_val=10.
x_data=tf.placeholder(dtype=tf.float32)
y_target=tf.constant(50.)
two_gate=tf.add(tf.multiply(a,x_data),b)
loss=tf.square(tf.subtract(two_gate,y_target))
train_step=tf.train.GradientDescentOptimizer(0.001).minimize(loss)
sess.run(tf.initialize_all_variables())
for i in range(100):
sess.run(train_step,feed_dict={x_data:x_val})
a_val,b_val=sess.run(a),sess.run(b)
two_gate_output=sess.run(two_gate,feed_dict={x_data:x_val})
print(str(a_val)+"*"+str(x_val)+"+"+str(b_val)+"="+str(two_gate_output))