我正在制作一個機器學習模型來計算不同角色組合的游戲獲勝率。我在使用損失函式的最后一行出錯。我認為這是因為輸入是單熱向量。模型的輸出與目標資料不兼容。因為目標資料只是布林值,贏或輸。請給我建議以解決這個問題。如何使one-hot輸入與非one-hot兼容?
'''for example, when the number of character is 4 and eahc team member is 2.
x_data is [ [[0,0,1,0], [0,1,0,0], [1,0,0,0,],[0,1,0,0]], [game2]...]
team A1, temaA2, temaB1 teamB2
'''
y_data = [[0], [0], [0], [1], [1], [1]] # team blue win: 1, lose : 0
x_train = torch.FloatTensor(x_data)
y_train = torch.FloatTensor(y_data)
class BinaryClassifier(nn.Module):
def __init__(self):
super(BinaryClassifier, self).__init__()
self.layer1 = nn.Sequential(
nn.Linear(in_features=num_characters, out_features=10, bias=True),
nn.ReLU(),
)
self.layer2 = nn.Sequential(
nn.Linear(in_features=10, out_features=1, bias=True),
nn.Sigmoid(),
)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
return torch.sigmoid(x)
model = BinaryClassifier()
optimizer = optim.SGD(model.parameters(), lr=1)
nb_epochs = 1000
for epoch in range(nb_epochs 1):
hypothesis = model(x_train)
cost = nn.BCELoss(hypothesis, y_train)
# RuntimeError: bool value of Tensor with more than one value is ambiguous
uj5u.com熱心網友回復:
首先,您的問題與 One-hot 編碼無關,因為您的模型的輸出是一個數字,而 Y_data 是 0-1,因此它們是兼容的。你的問題是關于實體化損失。因此,您必須實體化損失,然后傳遞引數:
...
model = BinaryClassifier()
optimizer = torch.optim.SGD(model.parameters(), lr=1)
loss = nn.BCELoss()
nb_epochs = 1000
for epoch in range(nb_epochs 1):
hypothesis = model(x_train)
cost = loss(hypothesis, y_train)
關于你的 x_data,如果你的資料是這樣的:
[[0,0,1,0], [0,1,0,0], [1,0,0,0,], [0,1,0,0],...]
在self.layer1你應該in_features用 4指定。
如果 x_data 是這樣的:
[ [[0,0,1,0], [0,1,0,0], [1,0,0,0,], [0,1,0,0]], [[0,0,1,0], [0,1,0,0], [1,0,0,0,], [0,1,0,0]], ...]
并且您想使用線性層,您必須展平每個樣本,因為線性層接受 1-dim 輸入。
例如,上面將是:
[[0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0], [0,0,1,0,0,1,0,0,1,0,0,0,0,1,0,0], ...]
和in_features=16。
對于您的資訊,您可以將 CNN(卷積神經網路)用于 2 維或更多維度的輸入,對于系列輸入,您可以使用 RNN(回圈神經網路)。
希望它可以有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374939.html
