码迷,mamicode.com
首页 > 其他好文 > 详细

[吃药深度学习随笔] 练习:训练二次方程的参数

时间:2018-05-12 22:28:31      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:函数的参数   variable   color   col   variables   oat   index   one   step   

import tensorflow as tf
import numpy as np

#训练二次函数的参数
#二次函数: y = ax^2 + bx +c

SEED = 12345
#ABC参数
pA = 2
pB = 5
pC = 100

rng = np.random.RandomState(SEED)

X = rng.rand(320, 1)
#定义一个a=2 b=5 c=10的二次方程
Y = [[float(pA * pow(i, 2) + pB * i + pC)] for i in X]
print ("X:\n", X)
print ("Y:\n", Y)

#定义神经网络的输入、参数和输出
x = tf.placeholder(tf.float32, shape=(None, 1))
y = tf.placeholder(tf.float32, shape=(None, 1))

A = tf.Variable(tf.random_normal([1, 1]))
B = tf.Variable(tf.random_normal([1, 1]))
C = tf.Variable(tf.random_normal([1, 1]))

r1 = tf.matmul(pow(x, 2), A) + tf.matmul(x, B) + C

#损失函数
loss = tf.reduce_mean(tf.reduce_sum(tf.square(r1 - y)))

#学习步骤
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)

#生成会话
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    for i in range(10000):
        index = i % 320
        sess.run(train_step, feed_dict={x: X, y: Y})
        if i % 50 == 0:
            total_loss = sess.run(loss,feed_dict={x: X, y: Y})
            print (total_loss)
    print("A:\n", sess.run(A))
    print("B:\n", sess.run(B))
    print("C:\n", sess.run(C))

最终得到结果:

A:
 [[1.9997427]]
B:
 [[5.0002966]]
C:
 [[99.99993]]

 

[吃药深度学习随笔] 练习:训练二次方程的参数

标签:函数的参数   variable   color   col   variables   oat   index   one   step   

原文地址:https://www.cnblogs.com/EatMedicine/p/9030045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!