【问题标题】:AttributeError: module 'tensorflow.keras.backend' has no attribute 'tf' in Custom RegularizerAttributeError:模块'tensorflow.keras.backend'在自定义正则化器中没有属性'tf'
【发布时间】:2020-07-05 08:15:49
【问题描述】:

我正在使用自定义正则化器,我将在模型中的第一个隐藏层权重中使用它

数据

XTrain,YTrain),(XTest,YTest)=mnist.load_data()
XTrain=XTrain.reshape(XTrain.shape[0],XTrain.shape[1]*XTrain.shape[2])
XTest=XTest.reshape(XTest.shape[0],XTest.shape[1]*XTest.shape[2])
YTrain=to_categorical(YTrain)
YTest=to_categorical(YTest)

自定义正则化器

def layer1_reg(weight_matrix):
        return 0.01*K.sum(K.sqrt(K.tf.reduce_sum(K.square(weight_matrix), axis=1)))

型号

from keras.layers import Dense,Dropout
from keras.utils import to_categorical
from keras.models import Sequential
from keras.optimizers import Adam
import tensorflow as tf
import tensorflow.keras.backend as K

model=Sequential()
model.add(Dense(500,activation='relu',input_shape=(784,),kernel_regularizer=layer1_reg))
model.add(Dropout(0.1))
model.add(Dense(100,activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(10,activation='softmax'))
model.compile(loss="categorical_crossentropy",optimizer=Adam(lr=0.0001))
model.fit(x=XTrain,y=YTrain,batch_size=32,epochs=10)

错误信息

AttributeError                            Traceback (most recent call last)
<ipython-input-125-db27f84e12fe> in <module>()
     22 
     23 model=Sequential()
---> 24 model.add(Dense(500,activation='relu',input_shape=(784,),kernel_regularizer=layer1_reg))
     25 model.add(Dropout(0.1))
     26 model.add(Dense(100,activation='relu'))

5 frames
<ipython-input-124-dc68394d8544> in layer1_reg(weight_matrix)
      1 def layer1_reg( weight_matrix):
----> 2   return 0.01*K.sum(K.sqrt(K.tf.reduce_sum(K.square(weight_matrix), axis=1)))

AttributeError: module 'tensorflow.keras.backend' has no attribute 'tf'

如何在我最新的 tensorflow 和 keras 版本中修复此错误,因为有些人建议使用以前版本的 tensorflow,但根据我较新的 tensorflow 和 keras 要求设置,我无法做到这一点?

【问题讨论】:

  • 请分享您的代码的“导入”部分
  • tf.reduce_sum 而不是 K.tf.reduce_sum ?

标签: python tensorflow keras


【解决方案1】:

在函数中:

def layer1_reg(weight_matrix,l1=0.01):
        return l1*K.sum(K.sqrt(K.tf.reduce_sum(K.square(weight_matrix), axis=1)))

我猜 K 是

import keras.backened as K

K 没有属性 tf(tensorflow)

你应该使用 tf.reduce_sum() 而不是 K.tf.reduce_sum() 最重要的是尝试只使用一个模块 tensorflow.keras 或 keras 两者都不同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2018-04-14
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多