解決Keras 自定義層時(shí)遇到版本的問題
在2.2.0版本前,
from keras import backend as K
from keras.engine.topology import Layer
class MyLayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
# 為該層創(chuàng)建一個(gè)可訓(xùn)練的權(quán)重
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[1], self.output_dim),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape) # 一定要在最后調(diào)用它
def call(self, x):
return K.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
2.2.0 版本時(shí):
from keras import backend as K
from keras.layers import Layer
class MyLayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.kernel = self.add_weight(name='kernel',
shape=(input_shape[1], self.output_dim),
initializer='uniform',
trainable=True)
super(MyLayer, self).build(input_shape) # Be sure to call this at the end
def call(self, x):
return K.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
如果你遇到:
<module> from keras.engine.base_layer import InputSpec ModuleNotFoundError: No module named 'keras.engine.base_layer'
不妨試試另一種引入!
補(bǔ)充知識(shí):Keras自定義損失函數(shù)在場(chǎng)景分類的使用
在做圖像場(chǎng)景分類的過程中,需要自定義損失函數(shù),遇到很多坑。Keras自帶的損失函數(shù)都在losses.py文件中。(以下默認(rèn)為分類處理)
#losses.py #y_true是分類的標(biāo)簽,y_pred是分類中預(yù)測(cè)值(這里指,模型最后一層為softmax層,輸出的是每個(gè)類別的預(yù)測(cè)值) def mean_squared_error(y_true, y_pred): return K.mean(K.square(y_pred - y_true), axis=-1) def mean_absolute_error(y_true, y_pred): return K.mean(K.abs(y_pred - y_true), axis=-1) def mean_absolute_percentage_error(y_true, y_pred): diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true),K.epsilon(),None)) return 100. * K.mean(diff, axis=-1) def mean_squared_logarithmic_error(y_true, y_pred): first_log = K.log(K.clip(y_pred, K.epsilon(), None) + 1.) second_log = K.log(K.clip(y_true, K.epsilon(), None) + 1.) return K.mean(K.square(first_log - second_log), axis=-1) def squared_hinge(y_true, y_pred): return K.mean(K.square(K.maximum(1. - y_true * y_pred, 0.)), axis=-1)
這里面簡單的來說,y_true就是訓(xùn)練數(shù)據(jù)的標(biāo)簽,y_pred就是模型訓(xùn)練時(shí)經(jīng)過softmax層的預(yù)測(cè)值。經(jīng)過計(jì)算,得出損失值。
那么我們要新建損失函數(shù)totoal_loss,就要在本文件下,進(jìn)行新建。
def get_loss(labels,features, alpha,lambda_c,lambda_g,num_classes):
#由于涉及研究內(nèi)容,詳細(xì)代碼不做公開
return loss
#total_loss(y_true,y_pred),y_true代表標(biāo)簽(類別),y_pred代表模型的輸出
#( 如果是模型中間層輸出,即代表特征,如果模型輸出是經(jīng)過softmax就是代表分類預(yù)測(cè)值)
#其他有需要的參數(shù)也可以寫在里面
def total_loss(y_true,y_pred):
git_loss=get_loss(y_true,y_pred,alpha=0.5,lambda_c=0.001,lambda_g=0.001,num_classes=45)
return git_loss
自定義損失函數(shù)寫好之后,可以進(jìn)行使用了。這里,我使用交叉熵?fù)p失函數(shù)和自定義損失函數(shù)一起使用。
#這里使用vgg16模型
model = VGG16(input_tensor=image_input, include_top=True,weights='imagenet')
model.summary()
#fc2層輸出為特征
last_layer = model.get_layer('fc2').output
#獲取特征
feature = last_layer
#softmax層輸出為各類的預(yù)測(cè)值
out = Dense(num_classes,activation = 'softmax',name='predictions')(last_layer)
#該模型有一個(gè)輸入image_input,兩個(gè)輸出out,feature
custom_vgg_model = Model(inputs = image_input, outputs = [feature,out])
custom_vgg_model.summary()
#優(yōu)化器,梯度下降
sgd = optimizers.SGD(lr=learn_Rate,decay=decay_Rate,momentum=0.9,nesterov=True)
#這里面,剛才有兩個(gè)輸出,這里面使用兩個(gè)損失函數(shù),total_loss對(duì)應(yīng)的是fc2層輸出的特征
#categorical_crossentropy對(duì)應(yīng)softmax層的損失函數(shù)
#loss_weights兩個(gè)損失函數(shù)的權(quán)重
custom_vgg_model.compile(loss={'fc2': 'total_loss','predictions': "categorical_crossentropy"},
loss_weights={'fc2': 1, 'predictions':1},optimizer= sgd,
metrics={'predictions': 'accuracy'})
#這里使用dummy1,dummy2做演示,為0
dummy1 = np.zeros((y_train.shape[0],4096))
dummy2 = np.zeros((y_test.shape[0],4096))
#模型的輸入輸出必須和model.fit()中x,y兩個(gè)參數(shù)維度相同
#dummy1的維度和fc2層輸出的feature維度相同,y_train和softmax層輸出的預(yù)測(cè)值維度相同
#validation_data驗(yàn)證數(shù)據(jù)集也是如此,需要和輸出層的維度相同
hist = custom_vgg_model.fit(x = X_train,y = {'fc2':dummy1,'predictions':y_train},batch_size=batch_Sizes,
epochs=epoch_Times, verbose=1,validation_data=(X_test, {'fc2':dummy2,'predictions':y_test}))
寫到這里差不多就可以了,不夠詳細(xì),以后再做補(bǔ)充。
以上這篇解決Keras 自定義層時(shí)遇到版本的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python+django+rest框架配置創(chuàng)建方法
今天小編就為大家分享一篇python+django+rest框架配置創(chuàng)建方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08
18個(gè)Python入門經(jīng)典必背的程序分享
這篇文章主要為大家介紹了Python入門經(jīng)典必背的18個(gè)程序。注意:這是初學(xué)者要牢記的 18 個(gè)代碼,入門之后就簡單了,快跟隨小編一起來學(xué)習(xí)一下吧2023-02-02
利用Python實(shí)現(xiàn)自動(dòng)化監(jiān)控文件夾完成服務(wù)部署
本篇文章將為大家詳細(xì)介紹如何利用Python語言實(shí)現(xiàn)監(jiān)控文件夾,以此輔助完成服務(wù)的部署動(dòng)作,文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下2022-07-07

