Tensorflow 常用函数模块

记录一下因为tensorflow版本更新,存在部分模块在2.0 被移除或更改写法。尝试如何解决报错,正常使用tensorflow 1.0的函数。

调用相关包
  • 1)RNN

只需更改调用tensorflow库和包的写法,就OK啦

# 原1.0写法:
import tensorflow as tf
import tensorflow.contrib.rnn as rnn

# 现2.0需改成
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.python.ops import rnn
#rnn_cell包同样
#from tensorflow.python.ops import rnn_cell
  • 2)CRF

出现以下报错:

from tensorflow.contrib.crf import crf_log_likelihood
(或者是调用此库"from tensorflow.contrib.crf import viterbi_decode"[解决方法同理])
ModuleNotFoundError: No module named 'tensorflow.contrib'

Tensorflow2.0 将tf.contrib移除,转移至第三方库

# 原1.0写法:
from tensorflow.contrib.crf import crf_log_likelihood

# 现2.0需改成
from tensorflow_addons.text.crf import crf_log_likelihood
"""
对于tensorflow_addons的下载:pip install tensorflow-addons
ps:注意:tfa版本需要安装对应Tensorflow版本,若tf为最新,则直接上面那样pip ↑ 就可以啦
"""

CRP函数理解,参考链接

函数模块
  • 1)Session函数

只需更改调用tensorflow库的写法

# 原1.0写法:
import tensorflow as tf
with tf.Session() as sess:
    print(sess.run(result))

# 现2.0需改成
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
with tf.Session() as sess:
    print(sess.run(result))

猜你喜欢

转载自blog.csdn.net/Fuziqp/article/details/119815749