【永久解决】AttributeError: module ‘tensorflow.compat.v1‘ has no attribute ‘contrib‘

本文介绍了在使用TensorFlow2环境中遇到AttributeError:moduletensorflow.compat.v1hasnoattributecontrib问题的原因,即TensorFlow2已移除contrib库。提供了解决方案,即查找TensorFlow2官方文档替换相应的API,如将`tf.contrib.layers.l2_regularizer`替换为`tf.keras.regularizers.L2`。
摘要由CSDN通过智能技术生成

【永久解决】AttributeError: module ‘tensorflow.compat.v1‘ has no attribute ‘contrib‘

新手入门tensorflow时大部分教程都是基于tensorflow1,但自己环境大部分是比较新的tensorflow2,所以会出现教程的代码本地跑不通的情况


例如:这段代码用tensorflow2的环境跑会提示module ‘tensorflow.compat.v1‘ has no attribute ‘contrib‘

def get_weight(shape, regularizer):
	w = tf.Variable(tf.random_normal(shape), dtype=tf.float32)
	tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))
	return w

原因

网上已经有很多教程提到过了,主要是因为TensorFlow2取消了contrib库,因此调用tf.contrib会报错

解决方法

tensorflow官网搜索tensorflow2中对应功能的函数名,直接替换即可。例如本案例中核心函数是表示正则化的regularizer函数,因此直接在搜索框中搜索regularizer,发现TensorFlow v2.15中已经更改为tf.keras.regularizers.L2
在这里插入图片描述
因此上述代码仅需更改为

def get_weight(shape, regularizer):
	w = tf.Variable(tf.random_normal(shape), dtype=tf.float32)
	tf.add_to_collection('losses', tf.keras.regularizers.L2(regularizer)(w))
	return w

完美解决!


除此之外,对于其他函数也可能有类似情况,通用解决方案就是在上述官网搜索框中搜索核心函数名称,查找TensorFlow2中对应的函数名,例如文章中是初始化的函数无法找到,则直接搜索initializer并做相应替换即可。

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值