解決Keras 自定義層時(shí)遇到版本的問(wèn)題
在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)景分類的過(guò)程中,需要自定義損失函數(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)
這里面簡(jiǎn)單的來(lái)說(shuō),y_true就是訓(xùn)練數(shù)據(jù)的標(biāo)簽,y_pred就是模型訓(xùn)練時(shí)經(jīng)過(guò)softmax層的預(yù)測(cè)值。經(jīng)過(guò)計(jì)算,得出損失值。
那么我們要新建損失函數(shù)totoal_loss,就要在本文件下,進(jìn)行新建。
def get_loss(labels,features, alpha,lambda_c,lambda_g,num_classes):
#由于涉及研究?jī)?nèi)容,詳細(xì)代碼不做公開(kāi)
return loss
#total_loss(y_true,y_pred),y_true代表標(biāo)簽(類別),y_pred代表模型的輸出
#( 如果是模型中間層輸出,即代表特征,如果模型輸出是經(jīng)過(guò)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í)遇到版本的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python讀取和處理文件后綴為.sqlite的數(shù)據(jù)文件(實(shí)例講解)
下面小編就為大家?guī)?lái)一篇Python讀取和處理文件后綴為.sqlite的數(shù)據(jù)文件(實(shí)例講解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
用python實(shí)現(xiàn)的可以拷貝或剪切一個(gè)文件列表中的所有文件
python 實(shí)現(xiàn)剪切或是拷貝一個(gè)文件列表中的所有文件2009-04-04
解決PyCharm的Python.exe已經(jīng)停止工作的問(wèn)題
今天小編就為大家分享一篇解決PyCharm的Python.exe已經(jīng)停止工作的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
python 解決動(dòng)態(tài)的定義變量名,并給其賦值的方法(大數(shù)據(jù)處理)
今天小編就為大家分享一篇python 解決動(dòng)態(tài)的定義變量名,并給其賦值的方法(大數(shù)據(jù)處理),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
關(guān)于windows下Tensorflow和pytorch安裝教程
Tensorflow是廣泛使用的實(shí)現(xiàn)機(jī)器學(xué)習(xí)以及其它涉及大量數(shù)學(xué)運(yùn)算的算法庫(kù)之一。這篇文章主要介紹了Tensorflow和pytorch安裝(windows安裝),需要的朋友可以參考下2020-02-02

