python: 开始使用tensorflow 出现的一些问题即解决办法

python 用了快一年了, 想试用一下tensorflow, 了解一下深度学习(deep learning), 但是与其他的模块不同, tensorflow用起来并不容易, 或许是刚开始吧。

1. 版本问题,版本不同, 用法差别很大

所以,有必要首先了解自己用的是版本1.x, 或者是2.x. 可以用以下办法查版本:

a) pip list

b) conda list

c) 在python 程序内: print(tf.__version__)

我的版本是2.6.2

看教程, 很多给的第一个示范程序是:

l = tf.constant(23,dtype="int32",name="val1")

m = tf.constant(22,dtype="int32",name="val2")

with tf.Session() as val:

new_output=val.run(l*m)

print(new_output)

结果不运行,出错讯息是:

AttributeError “module ‘Tensorflow’ has no attribute ‘session'”

网上查了, 以上的教科程序只适合与tensorflow 版本1.x, 不适合2.x

解决办法:

import tensorflow as tf

tf.compat.v1.disable_eager_execution() 

l = tf.constant(23,dtype="int32",name="val1")

m = tf.constant(22,dtype="int32",name="val2")

with tf.compat.v1.Session() as val:

    new_output=val.run(l*m)

    print(new_output)

2. interl-CPU优化/GPU问题

运行如下代码,估计其他代码也会出现同样的问题:

import tensorflow.compat.v1 as tf

tf.compat.v1.disable_eager_execution() #not working without it
a1=tf.placeholder(tf.float32)
a2=tf.placeholder(tf.float32)
a3=tf.placeholder(tf.float32)
a_sum=tf.add_n([a1,a2,a3])
sess=tf.compat.v1.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(a_sum,feed_dict={a1:10,a2:20,a3:30}))

出现了警告讯息:

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.

解决方法:

AVX(Advanced Vector Extensions-Intel® AVX) 是intel 优化CPU用于浮点计算的技术,如果有GPU了,其实不用考虑该警告讯息。 不过, 不管怎么说, 如果不愿意看到该警告讯息, 可以加上如下2行代码:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

警告讯息就不见了

来源:北京维多

物联沃分享整理
物联沃-IOTWORD物联网 » python: 开始使用tensorflow 出现的一些问题即解决办法

发表评论