import tensorflowas tf
inputs = tf.Variable(initial_value=tf.random_normal(shape=[5000, 6], dtype=tf.float32), name="inputs", trainable=False)
poly_factor = tf.constant(value=[[1], [2], [3], [4], [5], [6]], dtype=tf.float32, name="poly_factor")
y_ = tf.matmul(inputs, poly_factor)
weights = tf.Variable(initial_value=tf.random_normal(shape=[6, 1], stddev=0.1, mean=0.0), name="weights", trainable=True)
y = tf.matmul(inputs, weights)
loss = tf.reduce_sum(tf.pow(x=y-y_, y=2, name="loss"))
train_op = tf.train.AdadeltaOptimizer(learning_rate=0.01).minimize(loss=loss)
with tf.Session()as sess:
sess.run(tf.initialize_all_variables())
while True:
loss1, _, w = sess.run(fetches=(loss, train_op, weights))
if loss1 <0.01:
break
print(loss1, w)
运行结束以后会输出以下内容:
0.010092118 [[1.0002018]
[2.0001423]
[3.0001147]
[4.0000753]
[5.000069 ]
[5.9986215]]
0.010038901 [[0.99982595]
[1.9998068 ]
[2.9999206 ]
[3.9999056 ]
[4.999968 ]