欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解決Keras 自定義層時(shí)遇到版本的問題

 更新時(shí)間:2020年06月16日 14:32:20   作者:orDream  
這篇文章主要介紹了解決Keras 自定義層時(shí)遇到版本的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

在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ǔ)充知識:Keras自定義損失函數(shù)在場景分類的使用

在做圖像場景分類的過程中,需要自定義損失函數(shù),遇到很多坑。Keras自帶的損失函數(shù)都在losses.py文件中。(以下默認(rèn)為分類處理)

#losses.py
#y_true是分類的標(biāo)簽,y_pred是分類中預(yù)測值(這里指,模型最后一層為softmax層,輸出的是每個(gè)類別的預(yù)測值)
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ù)測值。經(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ù)測值)
#其他有需要的參數(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ù)測值
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對應(yīng)的是fc2層輸出的特征
#categorical_crossentropy對應(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ù)測值維度相同
#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)建方法

    今天小編就為大家分享一篇python+django+rest框架配置創(chuàng)建方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 最新anaconda安裝配置教程

    最新anaconda安裝配置教程

    Anaconda是一個(gè)開源的Python發(fā)行版本,包括Conda、Python以及一大堆安裝好的工具包,比如:numpy、pandas等,這篇文章主要介紹了最新anaconda安裝配置教程,需要的朋友可以參考下
    2023-04-04
  • 深入講解Python中的上下文管理器和with語句

    深入講解Python中的上下文管理器和with語句

    這篇文章主要為大家介紹了Python中的上下文管理器和with語句的深入講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • Python多進(jìn)程原理與用法分析

    Python多進(jìn)程原理與用法分析

    這篇文章主要介紹了Python多進(jìn)程原理與用法,結(jié)合實(shí)例形式分析了Python多進(jìn)程原理、開啟使用進(jìn)程、進(jìn)程隊(duì)列、進(jìn)程池等相關(guān)概念與使用方法,需要的朋友可以參考下
    2018-08-08
  • PyTorch中常見損失函數(shù)的使用詳解

    PyTorch中常見損失函數(shù)的使用詳解

    損失函數(shù),又叫目標(biāo)函數(shù),是指計(jì)算機(jī)標(biāo)簽值和預(yù)測值直接差異的函數(shù),本文為大家整理了PyTorch中常見損失函數(shù)的簡單解釋和使用,希望對大家有所幫助
    2023-06-06
  • 在Python程序中進(jìn)行文件讀取和寫入操作的教程

    在Python程序中進(jìn)行文件讀取和寫入操作的教程

    這篇文章主要介紹了在Python程序中進(jìn)行文件讀取和寫入操作的教程,是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-04-04
  • Python中的單繼承與多繼承實(shí)例分析

    Python中的單繼承與多繼承實(shí)例分析

    這篇文章主要介紹了Python中的單繼承與多繼承,結(jié)合實(shí)例詳細(xì)分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中單繼承與多繼承的概念、原理、實(shí)現(xiàn)方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2018-05-05
  • Python使用gensim計(jì)算文檔相似性

    Python使用gensim計(jì)算文檔相似性

    在文本處理中,比如商品評論挖掘,有時(shí)需要了解每個(gè)評論分別和商品的描述之間的相似度,以此衡量評論的客觀性。那么python 里面有計(jì)算文本相似度的程序包嗎,恭喜你,不僅有,而且很好很強(qiáng)大。下面我們就來體驗(yàn)下gensim的強(qiáng)大
    2016-04-04
  • 18個(gè)Python入門經(jīng)典必背的程序分享

    18個(gè)Python入門經(jīng)典必背的程序分享

    這篇文章主要為大家介紹了Python入門經(jīng)典必背的18個(gè)程序。注意:這是初學(xué)者要牢記的 18 個(gè)代碼,入門之后就簡單了,快跟隨小編一起來學(xué)習(xí)一下吧
    2023-02-02
  • 利用Python實(shí)現(xiàn)自動化監(jiān)控文件夾完成服務(wù)部署

    利用Python實(shí)現(xiàn)自動化監(jiān)控文件夾完成服務(wù)部署

    本篇文章將為大家詳細(xì)介紹如何利用Python語言實(shí)現(xiàn)監(jiān)控文件夾,以此輔助完成服務(wù)的部署動作,文中的示例代碼講解詳細(xì),感興趣的可以嘗試一下
    2022-07-07

最新評論