美文网首页
用tensorflow写函数拟合demo

用tensorflow写函数拟合demo

作者: AI_Finance | 来源:发表于2019-01-30 16:31 被阅读0次

import numpyas np

import tensorflowas tf

def data_generator():

while True:

a1 = np.random.rand(10, 2)

factors = np.array([[20], [30]])

yield a1, np.matrix(a1)*np.matrix(factors)

dg = data_generator()

input_x = tf.placeholder(dtype=tf.float32, shape=[10, 2], name="input_x")

input_y = tf.placeholder(dtype=tf.float32, shape=[10, 1], name="input_y")

weights = tf.get_variable(name="weights", shape=[2, 1], dtype=tf.float32, trainable=True)

y_hat = tf.matmul(a=input_x, b=weights)

loss = tf.reduce_mean(input_tensor=tf.square(x=input_y-y_hat))

train_op = tf.train.AdamOptimizer(learning_rate=1e-3).minimize(loss=loss)

with tf.Session()as sess:

sess.run(tf.global_variables_initializer())

loss_ =10

    while abs(loss_) >1e-8:

x, y = dg.__next__()

_, loss_, weights_ = sess.run(fetches=[train_op, loss, weights], feed_dict={input_x: x, input_y: y})

print(loss_, "\t", weights_.flatten())

相关文章

网友评论

      本文标题:用tensorflow写函数拟合demo

      本文链接:https://www.haomeiwen.com/subject/ixecsqtx.html