tf2.0不降版本也能完美解决module ‘tensorflow’ has no attribute ‘contrib’ 等类似的问题

在使用tensorflow2.x版本的时候,如果使用调用tensorflow1.x函数的代码时,常常会出现 module ‘tensorflow’ has no attribute ‘contrib’这样的问题,原因是tensorflow2.x废弃了很多tensorflow1.xAPI接口,本文针对常见的几种错误来使tf2.0不降版本也能运行代码

在报错的行数将tf.random_normal修改成tf.random.normal即可

修改前

w = tf.Variable(tf.random_normal([num_neurons[-1], 1]))

修改后

w = tf.Variable(tf.random.normal([num_neurons[-1], 1])

将前边的import tensorflow改成兼容处理的tensorflow.compat.v1,再禁用eager_execution

修改前

import tensorflow as tf

修改后

import tensorflow.compat.v1 as tf
tf.compat.v1.disable_eager_execution()

这个是比较麻烦的,因为tensorflow2.x版本已经没有contrib库,但是读者可以试试下面的方法,多尝试,笔者也是不断调试才解决了问题

首先用placeholder的方法,先修改 import tensorflow as tf 改成

import tensorflow.compat.v1 as tf
tf.compat.v1.disable_eager_execution()

BasicLSTMCell处理方法,DropoutWrapper和MultiRNNCell同理

cell = tf.contrib.rnn.BasicLSTMCell(num_units=units, forget_bias=0.9)
cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=units,forget_bias=0.9)

contrib.rnn改成 nn.rnn_cell

如果使用了static_rnn类似的,就把contrib.rnn改成nn即可

outputs, _ = tf.contrib.rnn.static_rnn(stacked_lstm_cells, inputs, dtype=tf.float32)
outputs, _ = tf.nn.static_rnn(stacked_lstm_cells, inputs, dtype=tf.float32)

Original: https://blog.csdn.net/jinyuehai/article/details/113280968
Author: 200-
Title: tf2.0不降版本也能完美解决module ‘tensorflow’ has no attribute ‘contrib’ 等类似的问题

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/511924/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球