【永久解决】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
并做相应替换即可。