第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何自定義 Keras 圖層名稱并使其自動(dòng)遞增 layer.name

如何自定義 Keras 圖層名稱并使其自動(dòng)遞增 layer.name

MMTTMM 2022-06-22 17:03:39
我目前正在嘗試使用名稱為自定義激活的多個(gè)圖層cust_sig。但是當(dāng)我嘗試編譯模型時(shí),我得到一個(gè) ValueError ,因?yàn)槎鄠€(gè)層具有相同的 name cust_sig。我知道我可以手動(dòng)更改每個(gè)圖層的名稱,但想知道是否可以_1, _2, ...像對(duì)內(nèi)置圖層一樣自動(dòng)添加到名稱中。可以在下面找到模型定義。# Creating a modelfrom tensorflow.python.keras import kerasfrom tensorflow.python.keras.models import Modelfrom tensorflow.python.keras.layers import Dense# Custom activation functionfrom tensorflow.python.keras.layers import Activationfrom tensorflow.python.keras import backend as Kfrom keras.utils.generic_utils import get_custom_objectsdef custom_activation(x):    return (K.sigmoid(x) * 5) - 1get_custom_objects().update({'custom_activation': Activation(custom_activation)})data_format = 'channels_first'spec_input = keras.layers.Input(shape=(1, 3, 256), name='spec')x = keras.layers.Flatten(data_format)(spec_input)for layer in range(3):  x = Dense(512)(x)  x = Activation('custom_activation', name='cust_sig')(x)out = Dense(256, activation="sigmoid", name='out')(x)model = Model(inputs=spec_input, outputs=out)錯(cuò)誤信息如下所示Traceback (most recent call last):  File "/home/xyz/anaconda3/envs/ctf/lib/python3.7/site-packages/tensorflow/python/training/tracking/base.py", line 457, in _method_wrapper    result = method(self, *args, **kwargs)  File "/home/xyz/anaconda3/envs/ctf/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py", line 315, in _init_graph_network    self.inputs, self.outputs)  File "/home/xyz/anaconda3/envs/ctf/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py", line 1861, in _map_graph_network    str(all_names.count(name)) + ' times in the model. 'ValueError: The name "cust_sig" is used 3 times in the model. All layer names should be unique.
查看完整描述

3 回答

?
嗶嗶one

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊

下面應(yīng)該做:


def custom_activation(x):

    return (K.sigmoid(x) * 5) - 1


class CustSig(Layer):

    def __init__(self, my_activation, **kwargs):

        super(CustSig, self).__init__(**kwargs)

        self.supports_masking = True

        self.activation = my_activation


    def call(self, inputs):

        return self.activation(inputs)


    def get_config(self):

        config = {'activation': activations.serialize(self.activation)}

        base_config = super(Activation, self).get_config()

        return dict(list(base_config.items()) + list(config.items()))


    def compute_output_shape(self, input_shape):

        return input_shape

說明:

從源代碼來看,自動(dòng)命名的工作原理如下:


if not name:

  self._name = backend.unique_object_name(

      generic_utils.to_snake_case(self.__class__.__name__),

      zero_based=zero_based)

else:

  self._name = name

檢查 Keras 圖是否存在與您定義的對(duì)象同名的對(duì)象 - 如果存在,則繼續(xù)遞增 1,直到?jīng)]有匹配項(xiàng)。問題是,您不能指定name=,因?yàn)檫@消除了上述條件的自動(dòng)命名。


唯一的解決方法可能是使用所需的名稱作為類名定義您自己的自定義激活層,如上所示,其表現(xiàn)如下:


ipt = Input(shape=(1, 3, 256), name='spec')

x   = Flatten('channels_last')(ipt)

for _ in range(3):

    x   = Dense(512)(x)

    x   = CustSig(custom_activation)(x)

out = Dense(256, activation='sigmoid', name='out')(x)


model = Model(ipt, out)


print(model.layers[3].name)

print(model.layers[5].name)

print(model.layers[7].name)

cust_sig

cust_sig_1

cust_sig_2


查看完整回答
反對(duì) 回復(fù) 2022-06-22
?
ITMISS

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊

如果您查看Layerclass的源代碼,您可以找到?jīng)Q定層名稱的這些行。


if not name:

    prefix = self.__class__.__name__

    name = _to_snake_case(prefix) + '_' + str(K.get_uid(prefix))

self.name = name

K.get_uid(prefix)將從圖中獲取唯一 ID,這就是您看到activation_1,的原因activation_2。


如果你想對(duì)你的自定義激活函數(shù)有同樣的效果,更好的方法是定義你自己的繼承自Layer.


class MyAct(Layer):

    def __init__(self):

        super().__init__()


    def call(self, inputs):

        return (K.sigmoid(inputs) * 5) - 1 


spec_input = Input(shape=(10,10))

x = Flatten()(spec_input)

for layer in range(3):

    x = Dense(512)(x)

    x = MyAct()(x)


model = Model(spec_input, x)

model.summary()

輸出


# Layer (type)                 Output Shape              Param #   

# =================================================================

# input_1 (InputLayer)         (None, 10, 10)            0         

# _________________________________________________________________

# flatten_1 (Flatten)          (None, 100)               0         

# _________________________________________________________________

# dense_1 (Dense)              (None, 512)               51712     

# _________________________________________________________________

# my_act_1 (MyAct)             (None, 512)               0         

# _________________________________________________________________

# dense_2 (Dense)              (None, 512)               262656    

# _________________________________________________________________

# my_act_2 (MyAct)             (None, 512)               0         

# _________________________________________________________________

# dense_3 (Dense)              (None, 512)               262656    

# _________________________________________________________________

# my_act_3 (MyAct)             (None, 512)               0         

# =================================================================

# Total params: 577,024

# Trainable params: 577,024

# Non-trainable params: 0


查看完整回答
反對(duì) 回復(fù) 2022-06-22
?
紅顏莎娜

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊

如果要specific_name多次使用數(shù)字后綴,請(qǐng)使用以下命令:


tf.get_default_graph().unique_name("specific_name")

或者


tf.compat.v1.get_default_graph().unique_name("specific_name")

在你的情況下:


...

for layer in range(3):

  x = Dense(512)(x)

  x = Activation('custom_activation', name=tf.get_default_graph().unique_name("cust_sig"))(x)

...


查看完整回答
反對(duì) 回復(fù) 2022-06-22
  • 3 回答
  • 0 關(guān)注
  • 277 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)