20210113

今天主要是基本的TensorFlow的Tensor相关概念,基本写法(但由于教程为TF1.X而个人所使用是TF2.X,出现了问题,现已解决)

今天最大的问题是TensorFlow1.x及TensorFlow2.x之间的差异导致的代码不兼容。

在视频的示例代码中,需要通过tf.global_variables_initializer()以及tf.Session()来初始化并进行相关操作的实际运行。譬如以下代码(来源自所学习视讯中之示例)

1 w=tf.Variable([[0.5,1.0]])
2 x=tf.Variable([[2.0],[1.0]])
3 y=tf.matmul(w,x)
4 print(y)
5 
6 init_op = tf.global_variables_initializer()
7 with tf.Session() as sess:
8     sesss.run(init_op)
9     print(y.eval())
Code

但在TF2.0中这些是不需要的,直接写出运行即可。而且许多旧方法有问题或干脆没有,如网路上虽说可以采用tensorflow.compat.v1来使用旧方法,但上述代码仍然会出莫名其妙的问题无法运行。

TF2.0的与上列代码等效的代码如下

 1 import tensorflow as tf
 2 
 3 #check whether the executing eagerly is Enabled
 4 tf.executing_eagerly();
 5 
 6 #primary Code(s) starts here
 7 w=tf.Variable([[0.5,1.0]])
 8 x=tf.Variable([[2.0],[1.0]])
 9 y=tf.matmul(w,x)
10 print(y.numpy())
Code

运行如下:

 

posted @ 2021-01-13 19:41  水無月鈴乃  阅读(53)  评论(0编辑  收藏  举报