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

报错AttributeError: module 'tensorflow' has no attribute 'random_normal'

在报错的行数将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])

报错AttributeError: module 'tensorflow' has no attribute 'placeholder'

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

修改前

import tensorflow as tf

修改后

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

报错AttributeError: module 'tensorflow' has no attribute 'contrib'

这个是比较麻烦的,因为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)

另附参考资料,这个更加直观,帮助解决contrib的问题
tf2.0不降版本也能完美解决module ‘tensorflow’ has no attribute ‘contrib’的问题

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐