tf样例1和tf样例2

首先测试了一个书上样例:

1
2
3
4
5
6
7
8
9
10
import tensorflow as tf
a = tf.constant(5,name="input_a")
b = tf.constant(3,name="input_b")
c = tf.multiply(a,b,name="mul_c")
d = tf.add(a,b,name="add_d")
e = tf.add(c,d,name="add_e")

sess = tf.Session()
sess.run(e)

报错:

1
2
3
4
  File "C:\Users\qinsi\tensorflow_workspace\steam_tf.py", line 8, in <module>
sess = tf.Session()
AttributeError: module 'tensorflow' has no attribute 'Session'

这个在昨天的样例中碰到过,是v1和v2的版本区别。
修改为
sess = tf.compat.v1.Session()
后可以跑起来,在run步骤报如下错误:
Tensor.graph is meaningless when eager execution is enabled.
先找了一个hello跑了一下,可用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : TensorFlow入门操作.py
# @Author: 赵路仓
# @Date : 2020/3/26
# @Desc :
# @Contact : 398333404@qq.com

import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"

tf.compat.v1.disable_eager_execution()
hello=tf.constant('---Hello,TensorFlow')
config=tf.compat.v1.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9
sess=tf.compat.v1.Session(config=config)
print(sess.run(hello))

然后查阅资料修改文件,找到一个比较通用的方法,在前面添加如下语句:

1
2
3
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

整个程序如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : TensorFlow入门操作2.py
# @Author: qinsibo.com
# @Date : 2022/02/06
# @Desc :
# @Contact : qinsibo@sohu.com
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

a = tf.constant(5,name="input_a")
b = tf.constant(3,name="input_b")
c = tf.multiply(a,b,name="mul_c")
d = tf.add(a,b,name="add_d")
e = tf.add(c,d,name="add_e")
# 关闭动态图机制
tf.compat.v1.disable_eager_execution()
#
tf.compat.v1.get_default_graph()
sess = tf.compat.v1.Session()
hello=tf.constant('---Hello,TensorFlow')
#print(sess.run(hello))
print(sess.run(e))
sess.close()

输入结果为:

1
2
3
4
5
6
7
8
9
(TensorFlowGPU3_9) C:\Users\qinsi\tensorflow_workspace>python steam_tf.py
WARNING:tensorflow:From C:\Users\qinsi\anaconda3\envs\TensorFlowGPU3_9\lib\site-packages\tensorflow\python\compat\v2_compat.py:107: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
2022-02-06 13:10:41.291245: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-02-06 13:10:41.798922: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 1360 MB memory: -> device: 0, name: NVIDIA GeForce GTX 750 Ti, pci bus id: 0000:01:00.0, compute capability: 5.0
23

结果正确
手里的资料还是有点老,后续争取找一下tf2的相关资料进行进一步学习。