1、項(xiàng)目場(chǎng)景:
使用tensorflow2.x版本的時(shí)候,使用調(diào)用tensorflow1.x函數(shù)的代碼時(shí),常常會(huì)出現(xiàn)module ‘tensorflow’ has no attribute ‘contrib’這樣的問題,這是由于tensorflow2.x廢棄了很多tensorflow1.x API接口,本文針對(duì)常見的幾種錯(cuò)誤來使tf2.0不降版本也能運(yùn)行代碼。
2、問題描述和解決辦法
1、報(bào)錯(cuò)AttributeError: module ‘tensorflow’ has no attribute ‘random_normal’
在報(bào)錯(cuò)的行數(shù)將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])
2、報(bào)錯(cuò) 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()
3、報(bào)錯(cuò)AttributeError: module ‘tensorflow’ has no attribute ‘contrib’
這個(gè)是比較麻煩的,因?yàn)閠ensorflow2.x版本已經(jīng)沒有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)
代碼修改后:
文章來源:http://www.zghlxwxcb.cn/news/detail-780905.html
outputs, _ = tf.nn.static_rnn(stacked_lstm_cells, inputs, dtype=tf.float32)
參考博客
①tf2.0不降版本也能完美解決module ‘tensorflow’ has no attribute ‘contrib’ 等類似的問題
②tf2.0不降版本也能完美解決module ‘tensorflow’ has no attribute ‘contrib’的問題文章來源地址http://www.zghlxwxcb.cn/news/detail-780905.html
到了這里,關(guān)于解決 AttributeError: module ‘tensorflow‘ has no attribute ‘contrib‘ 等類似的問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!