import math
import tensorflow as tf
import numpy as np
from matplotlib import pyplot
HIDDEN_UNITS = 200
SAMPLES = 5
def sqrt(a_value, b_value, lr=0.01, epoches=2000):
g = tf.Graph()
with g.as_default():
a = tf.placeholder(tf.float32, [None], 'a')
a2 = tf.reshape(a, [-1, 1]) # [-1, 1]
# w = tf.get_variable('w', [1, 200], tf.float32)
# b = tf.get_variable('b', [200], tf.float32)
# y = tf.matmul(a2, w) + b # [-1, 200]
y = tf.layers.dense(a2, HIDDEN_UNITS, activation=tf.nn.relu) # [-1, 200]
# w = tf.get_variable('w2', [200, 1], tf.float32)
# b = tf.get_variable('b2', [1], tf.float32)
# y = tf.matmul(y, w) + b # [-1, 1]
y = tf.layers.dense(y, 1, use_bias=False) # [-1, 1]
y_predict = tf.reshape(y, [-1]) # [-1]
b = tf.placeholder(tf.float32, [None], 'b')
loss = tf.reduce_mean(tf.square(y_predict - b))
opt = tf.train.AdamOptimizer(lr)
train_op = opt.minimize(loss)
with tf.Session(graph=g) as session:
session.run(tf.global_variables_initializer())
for _ in range(epoches):
session.run(train_op, {a: a_value, b: b_value})
return session.run(y_predict, {a: a_value})
if __name__ == '__main__':
a_value = np.random.uniform(-math.pi, math.pi, [SAMPLES])
a_value = sorted(a_value)
b_value = np.sin(a_value)
predict = sqrt(a_value, b_value)
pyplot.plot(a_value, b_value)
pyplot.plot(a_value, predict)
pyplot.show()
D:\Anaconda\python.exe D:/AI20/HJZ/05-深度学习项目/deeplearning_20/p21_sin.py
2020-02-27 17:54:57.138614: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
Process finished with exit code 0