我訓練了一個keras模型,其中有一個自定義層。該模型訓練得非常好,并被存盤起來。但是當我試圖加載該模型時,我無法加載它。以下是來自自定義類的代碼:
from keras.engine.base_layer import Layer
class AttentionLayer(Layer)。
def __init__(self, attention_dim, **kwargs)。
super(AttentionLayer, self).__init__(name="attention_layer")
self.init = initializers.get("normal")
self.supports_masking = Truesuper(AttentionLayer, self).__init__(**kwargs)
def get_config(self)。
config = {
"init": self.init。
"supports_masking": self.supports_masking。
"attention_dim": self.attention_dim。
}
base_config = super(AttentionLayer, self).get_config()
return dict(list(base_config.items() ) list(config.items())
然后我嘗試用下面的方式來加載模型:
model = keras.models.load_model("model.h5",
custom_objects={"AttentionLayer": AttentionLayer})
但我一直得到
ValueError: 未知的config_item。RandomNormal。請確保這個物件 是傳遞給'custom_objects'引數。
幾乎所有我在StackOverflow上提到的問題都提出了同樣的建議,但不幸的是,在我的情況下,它并沒有發揮作用。誰能指出我是否犯了什么錯誤?
我的合作專案的鏈接是這里。
。uj5u.com熱心網友回復:
我已經嘗試解決你的問題。但在這之前,我想讓你看一件事
preds = Dense(2, activation="softmax")(l_att_sent)
model = Model(review_input, preds)
model.compile(loss="binary_crossentropy"/span>,
optimizer="rmsprop", metrics=["準確性"])
如果你設定了(...2, activations='softmax'),通常你應該使用categorical_cross_entropy和相應的度量(上述度量是可以的,因為你使用了string identifier)。但是我看到你使用了binary_crossentropy作為損失函式,所以我認為你在最后一層可能需要如下。(...1, activations='sigmoid')。這里有一些參考資料:a). 為Tensorflow模型選擇損失和度量。) 神經網路和二進制分類指導。
在你的代碼中,我認為問題來自于在
get_config方法中使用"init": self.init,;反正你不需要這樣做。
from tensorflow.keras import initializers
self.init = initializers.get("normal")
為了便于以后參考,這里是端到端的作業代碼。
import numpy as np
from tensorflow.keras import backend as K
from tensorflow.keras import initializers
from tensorflow.keras import layers
from tensorflow.keras.layer import (Embedding, Dense, Input, GRU,
雙向的,時間分布的)
from tensorflow.keras.models import Model
class AttentionLayer(layer.Layer)。
def __init__(self, attention_dim, supports_masking=True, **kwargs)。
super(AttentionLayer, self).__init__(name="attention_layer")
self.init = initializers.get("normal")
self.supports_masking = supports_masking
self.attention_dim = attention_dim
super(AttentionLayer, self).__init__(**kwargs)
def build(self, input_shape)。
assert len(input_shape) == 3
self.W = K.variable(self.init((input_shape[-1], self.attention_dim)), name="W" )
self.b = K.變數(self.init((self.attention_dim, )), name="b")
self.u = K.變數(self.init((self.attention_dim, 1)), name="u")
self._trainable_weights = [self.W, self.b, self.u].
super(AttentionLayer, self).build(input_shape)
def call(self, x, mask=None)。
uit = K.tanh(K.bias_add(K.dot(x, self.W), self.b))
ait = K.dot(uit, self.u)
ait = K.squeeze(ait, -1)
ait = K.exp(ait)
if mask is not None:
ait *= K.cast(mask, K.floatx() )
ait /= K.cast(K.sum(ait, axis=1, keepdims=True) K.epsilon(), K.floatx())
ait = K.expand_dims(ait)
加權輸入 = x * ait
output = K.sum(weighted_input, axis=1)
return output
def compute_output_shape(self, input_shape)。
return (input_shape[0], input_shape[-1] )
def get_config(self)。
config = {
"supports_masking": self.supports_masking。
"attention_dim": self.attention_dim。
}
base_config = super(AttentionLayer, self).get_config()
return dict(list(base_config.items() ) list(config.items())
MAX_SENTENCE_LEN = 10.
MAX_SENTENCES = 15
MAX_NUM_WORDS=200
EMBEDDING_DIM =10
VALIDATION_SPLIT =0.2
# 我們使用嵌入層將正整數轉換為密集的向量。
# 固定大小的向量
embedding_layer = Embedding(
100,
EMBEDDING_DIM,
input_length=MAX_SENTENCE_LEN,
trainable=True,
mask_zero=True.
)
sentence_input = Input(shape=(MAX_SENTENCE_LEN, ) , dtype="int32")
embedded_sequences = embedding_layer(sentence_input)
l_lstm = Bidirectional(GRU(100, return_sequences=True))(embedded_sequences)
l_att = AttentionLayer(100)(l_lstm)
sentEncoder = Model(sentence_input, l_att)
sentEncoder.summary() # OK .
review_input = Input(shape=(MAX_SENTENCES, MAX_SENTENCE_LEN), dtype="int32"/span>)
review_encoder = TimeDistributed(sendEncoder)(review_input)
l_lstm_sent = Bidirectional(GRU(100, return_sequences=True))(review_encoder)
l_att_sent = AttentionLayer(100)(l_lstm_sent)
preds = Dense(1, activation="sigmoid") (l_att_sent)
model = Model(review_input, preds)
model.summary() # OK[/span
DummyData
import tensorflow as tf
import numpy as np
x_train = np.random. randint(0, 10, (100,15,10) )。) print(x_train. 形狀)
y_train = np.random.randint(2, size=(100, 1); print(y_train.shape)
(100, 15, 10)
(100, 1)
培訓
filepath = "model.h5"。
model.compile(loss="binary_crossentropy", optimizer="rmsprop",
metrics=["準確性"])
model.fit(x_train, y_train, epochs=2, verbose=2)
model.save(filepath)
Epoch 1/2
142ms/步 - 損失。0.6964 -精確度。0.4100 - 精度:0.6964
Epoch 2/2
144ms/步 - 損失。0.5919 -精確度。0.5500 - 精度:0.5919
重新加載和檢查
from tensorflow.keras.models import load_model
new_model = load_model(filepath,
custom_objects={"AttentionLayer"/span>: AttentionLayer})
# Let's check: # OK
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/328144.html
標籤:
上一篇:向Lambda層Tensorflow提供多個輸入資訊
下一篇:AWS-子域不支持HSTS
