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

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]]

 

转载于:https://www.cnblogs.com/EatMedicine/p/9030045.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值