import math
import tensorflow as tf
import numpy as np
from matplotlib import pyplot
HIDDEN_UNITS =200
SAMPLES =200defsqrt(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_predict = tf.layers.dense(y,4, use_bias=False)# [-1, 3]
b = tf.placeholder(tf.float32,[None,4],'b')# [-1, 3]
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 _ inrange(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 = np.array(sorted(a_value))
b_value =[np.sin(a_value), np.cos(a_value), a_value**2/10, np.sqrt(np.abs(a_value))]
b_value = np.transpose(b_value,[1,0])# [-1, 3]
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/06_codes/deeplearning_20/p22_sin_cos_sqr.py
2020-02-2718:09:08.258672: 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