module ‘tensorflow_core.compat.v1‘ has no attribute ‘contrib‘问题的完美解决

该博客主要介绍了在升级到TensorFlow2后遇到的由于`tf.contrib`模块移除导致的错误。作者指出,将`tf.contrib.rnn.BasicLSTMCell`替换为`tf.compat.v1.nn.rnn_cell.BasicLSTMCell`可以成功解决这个问题。这个更改不影响模型的功能,并且是向后兼容的解决方案。博客内容对于正在迁移TensorFlow1到TensorFlow2的开发者具有参考价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

Instructions for updating:
Use keras.layers.Dense instead.
Traceback (most recent call last):
  File "run_cnn.py", line 200, in <module>
    model = TextCNN(config)
  File "D:\MY DATA\学习资料\研究生\深度学习\text-classification-cnn-rnn-master\cnn_model.py", line 43, in __init__
    self.cnn()
  File "D:\MY DATA\学习资料\研究生\深度学习\text-classification-cnn-rnn-master\cnn_model.py", line 61, in cnn
    fc = tf.contrib.layers.dropout(fc, self.keep_prob)
AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'

原因:
TensorFlow 2 删除了部分v1的库
很多代码大佬们都是用v1版本写的,所以一种解决办法是将tensorflow版本降回v1,我这么干了,结果引发更大的问题,因为菜啊。。。找了好久,下面这种方法完美解决。
解决办法:

cell = tf.contrib.rnn.BasicLSTMCel

cell = tf.compat.v1.nn.rnn_cell.BasicLSTMCell
代替就可以完美的解决出现的问题。得到的结果没啥区别。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值