【发布时间】: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