最初我們有一個多層的 MLP。我們有一個 200 維的輸入嵌入。我們現在想在原始嵌入中再添加兩個維度來編碼兩個重要特征。但是由于原始維度很高,我們擔心 MLP 會忽略兩個非常重要的新維度。
因此,我們希望在 MLP 的最后兩層之前添加(連接)兩個新維度。我仍然是 ML 和 PyTorch 的新手,我在網上搜索了很多,但沒有想出方法來做到這一點。
請問我們如何使用 PyTorch 實作這一點?太感謝了!
uj5u.com熱心網友回復:
您可以簡單地創建兩個輸入頭。一個用于嵌入,它通過自己的神經網路,然后一個用于兩個特征。然后將兩個網路的輸出簡單地連接并傳遞到最后一層。因為對于一個輸入頭,只有兩個特征(可能是一個大小為 2 的向量,對嗎?)
您可以像這樣簡單地組合兩個神經網路模塊:
# create a seperate network for your embedding input
class EmbeddingModel(nn.Module):
def __init__(self):
super(EmbeddingModel, self).__init__()
self.layer1 = nn.Linear(...)
. . .
self.layerN = nn.Linear(...)
def forward(self, x):
x = F.activation(self.layer1(x))
. . .
x = F.activation(self.layerN(x))
return x
# create a one layer network for your "two important features"
# use the same activation function as the last layer of the "EmbeddingModel"
class FeaturesModel(nn.Module):
def __init__(self):
super(FeaturesModel, self).__init__()
self.layer1 = nn.Linear(...)
def forward(self, x):
x = F.activation(self.layer1(x))
return x
# finally create your main-model which combines both
class MainModel(nn.Module):
def __init__(self):
super(MainModel, self).__init__()
self.embeddingModel = EmbeddingModel()
self.featuresModel = FeaturesModel()
# the input-dim to this layer has to be the output-dim of the embeddingModel the output-dim of the featureModel
self.outputLayer = nn.Linear(...)
def forward(self, x_embeggings, x_features):
x_embeggings = self.embeddingModel(x_embeggings)
x_features = self.featuresModel(x_features)
x = torch.cat((x_embeddings, x_features), -1)
x = F.activation(self.outputLayer(x))
return x
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/416636.html
標籤:
下一篇:查找長度在特定范圍內的標記
