簡體   English   中英

類型錯誤:forward() 缺少 1 個必需的位置參數:'negative'

[英]TypeError: forward() missing 1 required positional argument: 'negative'

我想利用深度神經網絡對高光譜圖像進行分類。 但是每次我運行這段代碼時,它都會給我這個錯誤“TypeError: forward() missing 1 required positional argument: 'negative'”。 代碼如下(未完成):

import numpy as np
import scipy.io as sio
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import math

REBUILD_DATA = True

讀取數據:

class DATA():
    # 讀取樣本和標簽,並轉換為numpy數組格式
    Pavia = sio.loadmat('G:\研究生\Matlab_code\dataset\Classification\paviaU.mat')
    PaviaGT = sio.loadmat('G:\研究生\Matlab_code\dataset\Classification\paviaU_GT.mat')
    # print(sorted(Pavia.keys()))   返回字典中的鍵值key()
    # print(sorted(PaviaGT.keys())) 

    Sample = Pavia['data']
    Sample = np.array(Sample, dtype = np.int32)

    Label = PaviaGT['groundT']
    Label = np.array(Label, dtype = np.int32)

    # 將樣本每一維度的數值存到a,b,c中,以便后續使用
    [a,b,c]=Sample.shape

    # 將數據reshape成matlab中的格式
    SampleT = Sample.transpose(1, 0, 2)
    SampleX = SampleT.reshape(-1,103)
    """ sio.savemat('G:\研究生\Sample.mat',{'dataX':SampleX})  """
    LabelT = Label.transpose(1,0)
    Label = LabelT.reshape(-1,1)
    # 如何將樣本和標簽合並,輸入神經網絡的數據為[-1,band]
    """ sio.savemat('G:\研究生\Label.mat',{'LabelX':Label}) """
    totalcount = np.zeros((10,1),dtype = np.int32)
    trainset = []
    testset = []

    # 將樣本和標簽合並
    def integrated_data(self):
        rebuilddata = []
        for i in range(0,self.a*self.b):
            rebuilddata.append([np.array(self.SampleX[i]),np.array(self.Label[i])])
            for j in range(0,10):
                if self.Label[i] == j:  
                    self.totalcount[j] += 1
        rebuilddata = np.array(rebuilddata)
        return rebuilddata

    # 並制作訓練和測試數據
    def make_trainset_and_testset(self, rebuilddata, ratio):
        TrainIndex = []
        TestIndex = []

        # 取出每一類的訓練集和測試集坐標
        for i in range(1,np.max(self.Label)+1):
            class_coor = np.argwhere(self.Label == i)
            index = class_coor[:,0].tolist()
            np.random.shuffle(index)
            VAL_SIZE = int(np.floor(len(index)*ratio))
            ClassTrainIndex = index[:VAL_SIZE]
            ClassTestIndex = index[-VAL_SIZE:]
            TrainIndex += ClassTrainIndex
            TestIndex += ClassTestIndex

        # 返回訓練集和測試集樣本        
        TrainSample = rebuilddata[TrainIndex]
        TestSample = rebuilddata[TestIndex]
        return TrainIndex,TestIndex,TrainSample,TestSample

這是我的 dnn 模塊:

class DNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(103, 500)
        self.fc2 = nn.Linear(500, 256)
        self.fc3 = nn.Linear(256, 9)

    def forward(self,x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return F.softmax(x,dim=1)

訓練和測試功能:

def train(dnn):
    BATCH_SIZE = 100
    EPOCHS = 3
    for epoch in range(EPOCHS):
        for i in tqdm(range(0, len(train_X), BATCH_SIZE)):
            batch_X = train_X[i:i+BATCH_SIZE]
            batch_y = train_y[i:i+BATCH_SIZE]

            dnn.zero_grad()
            outputs = dnn(batch_X)
            loss = loss_function(outputs, batch_y)
            loss.backward()
            optimizer.step()
        print(loss)

 def test(net):
     correct = 0
     total = 0
     with torch.no_grad():
         for i in tqdm(range(len(test_X))):
             real_class = torch.argmax(test_y[i]).to(device)
             net_out = dnn(test_X[i].view(-1, 1, 50, 50).to(device))[0]

             predicted_class = torch.argmax(net_out)
             if predicted_class == real_class:
                 correct += 1
             total += 1
     print("Accuracy:", round(correct/total,3))

if REBUILD_DATA:
    Data = DATA()
    datay = Data.integrated_data()
    Trainindex, Testindex, TrainSet, TestSet = Data.make_trainset_and_testset(rebuilddata=datay,ratio=0.1)

train_X = torch.Tensor([i[0] for i in TrainSet])
train_y = torch.Tensor([i[1] for i in TrainSet])
train_X = train_X/3000
test_X = torch.Tensor([i[0] for i in TestSet])
test_y = torch.Tensor([i[1] for i in TestSet])

print(train_X[0])
dnn = DNN()
optimizer = optim.SGD(dnn.parameters(), lr = 0.001)
loss_function = nn.TripletMarginLoss()
train(dnn)

您正在使用nn.TripletMarginLoss()作為您的損失函數。
這個特定的損失函數需要三個輸入來計算損失: anchorpositivenegative
您的代碼只傳遞兩個參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM