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
时间: 2024-11-08 05:43:47