Python 如何用TensorFlow2写出这个方程?(4x+;2=0)

Python 如何用TensorFlow2写出这个方程?(4x+;2=0),python,tensorflow,tensorflow2.0,Python,Tensorflow,Tensorflow2.0,此代码不在TensorFlow 2中运行代码是什么 import tensorflow as tf # the equation is : 4x+2 = 0 unknownvalue = tf.Variable(0.0) a = tf.constant(4.0) b = tf.constant(2.0) c = tf.multiply(unknownvalue,a) # 4x equation = tf.add(c,b) # 4x+2 zerovalue = tf.constant(0.

此代码不在TensorFlow 2中运行代码是什么

import tensorflow as tf

# the equation is  : 4x+2 = 0
unknownvalue = tf.Variable(0.0)
a = tf.constant(4.0)
b = tf.constant(2.0)
c = tf.multiply(unknownvalue,a)  # 4x
equation  = tf.add(c,b) # 4x+2
zerovalue = tf.constant(0.0)
diff = tf.square(equation-zerovalue) # differnce is : 4x+2  -  0 
solving = tf.train.GradientDescentOptimizer(0.01).minimize(diff)
init = tf.global_variables_initializer()

TF2更改了自TF1以来生成训练循环的方式。 我鼓励您阅读本指南:,以了解更多如何做到这一点

以下是tf1代码在TF2中的简单实现:

将tensorflow导入为tf
x=tf.变量(0.0)
优化器=tf.optimizers.SGD(1e-2)
对于范围(1,26)内的idx:
使用tf.GradientTape()作为磁带:
#公式为:4x+2=0
方程=x*4+2#4x+2
损耗=tf.平方(方程式)
梯度=磁带梯度(损耗,[x])
优化器。应用_梯度(zip(grad,[x]))
如果不是idx%5:
print(f“迭代:{idx},丢失:{loss:.4f},x:{x.numpy():.4f}”)
这导致

Iteration:5,loss:0.1829,x:-0.4273
Iteration:10,loss:0.0039,x:-0.4894
Iteration:15,loss:0.0001,x:-0.4985
Iteration:20,loss:0.0000,x:-0.4998
Iteration:25,loss:0.0000,x:-0.5000

TF2更改了自TF1以来生成训练循环的方式。 我鼓励您阅读本指南:,以了解更多如何做到这一点

以下是tf1代码在TF2中的简单实现:

将tensorflow导入为tf
x=tf.变量(0.0)
优化器=tf.optimizers.SGD(1e-2)
对于范围(1,26)内的idx:
使用tf.GradientTape()作为磁带:
#公式为:4x+2=0
方程=x*4+2#4x+2
损耗=tf.平方(方程式)
梯度=磁带梯度(损耗,[x])
优化器。应用_梯度(zip(grad,[x]))
如果不是idx%5:
print(f“迭代:{idx},丢失:{loss:.4f},x:{x.numpy():.4f}”)
这导致

Iteration:5,loss:0.1829,x:-0.4273
Iteration:10,loss:0.0039,x:-0.4894
Iteration:15,loss:0.0001,x:-0.4985
Iteration:20,loss:0.0000,x:-0.4998
Iteration:25,loss:0.0000,x:-0.5000

Tensorflow 2代码更加简单直观(GradientTape部分除外,如果您不习惯的话):


Tensorflow 2代码更加简单直观(GradientTape部分除外,如果您不习惯的话):