p18_tf_sqrt

import math
import tensorflow as tf


def sqrt(a, lr=0.01, epoches=2000):
    g = tf.Graph()
    with g.as_default():
        x = tf.get_variable('x', [], tf.float32)  #  x = 1.0
        # y = (x**2 - a) ** 2
        y = tf.abs(x**2 - a)

        opt = tf.train.GradientDescentOptimizer(lr)
        train_op = opt.minimize(y)

    with tf.Session(graph=g) as session:
        session.run(tf.global_variables_initializer())
        for _ in range(epoches):
            session.run(train_op)
        return session.run(x)


# tf.get_default_graph()

if __name__ == '__main__':
    for a in range(2, 10+1):
        print(a, math.sqrt(a), sqrt(a))



D:\Anaconda\python.exe D:/AI20/06_codes/deeplearning_20/p18_tf_sqrt.py
2020-02-27 15:39:58.354334: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2 1.4142135623730951 1.4146459
3 1.7320508075688772 1.7184467
4 2.0 1.984637
5 2.23606797749979 -2.2003498
6 2.449489742783178 2.4752276
7 2.6457513110645907 -2.6047804
8 2.8284271247461903 2.8138382
9 3.0 -2.989889
10 3.1622776601683795 3.181918

Process finished with exit code 0

发布了88 篇原创文章 · 获赞 2 · 访问量 1298

猜你喜欢

转载自blog.csdn.net/HJZ11/article/details/104537738
tf
今日推荐