Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 派托克火车公司;评估不同的样本量_Python_Pytorch - Fatal编程技术网

Python 派托克火车公司;评估不同的样本量

Python 派托克火车公司;评估不同的样本量,python,pytorch,Python,Pytorch,我正在学习pytorch,并有以下(缩写)代码用于建模: # define the model class for a neural net with 1 hidden layer class myNN(nn.Module): def __init__(self, D_in, H, D_out): super(myNN, self).__init__() self.lin1 = nn.Linear(D_in,H) self.lin2 = n

我正在学习pytorch,并有以下(缩写)代码用于建模:

# define the model class for a neural net with 1 hidden layer
class myNN(nn.Module):
    def __init__(self, D_in, H, D_out):
        super(myNN, self).__init__()
        self.lin1 = nn.Linear(D_in,H)
        self.lin2 = nn.Linear(H,D_out)
    def forward(self,X):
        return torch.sigmoid(self.lin2(torch.sigmoid(self.lin1(x))))

# now make the datasets & dataloaders
batchSize = 5
# Create the data class
class Data(Dataset):
    def __init__(self, x, y):
        self.x = torch.FloatTensor(x)
        self.y = torch.Tensor(y.astype(int))
        self.len = self.x.shape[0]
        self.p = self.x.shape[1]
    def __getitem__(self, index):      
        return self.x[index], self.y[index]
    def __len__(self):
        return self.len
trainData = Data(trnX, trnY)
trainLoad = DataLoader(dataset = trainData, batch_size = batchSize)
testData = Data(tstX, tstY)
testLoad = DataLoader(dataset = testData, batch_size = len(testData))

# define the modeling objects
hiddenLayers = 30
learningRate = 0.1
model = myNN(p,hiddenLayers,1)
print(model)
optimizer = torch.optim.SGD(model.parameters(), lr = learningRate)
loss = nn.BCELoss()
使用
trnX.shape=(70,2)
trnY.shape=(70,)
tstX.shape=(30,2)
,以及
tstY.shape=(30,)
。培训代码为:

# train!
epochs = 1000
talkFreq = 0.2
trnLoss = [np.inf]*epochs
tstLoss = [np.inf]*epochs
for i in range(epochs):
    # train with minibatch gradient descent
    for x, y in trainLoad:
        # forward step
        yhat = model(x)
        # compute loss (not storing for now, will do after minibatching)
        l = loss(yhat, y)
        # backward step
        optimizer.zero_grad()
        l.backward()
        optimizer.step()
    # evaluate loss on training set
    yhat = model(trainData.x)
    trnLoss[i] = loss(yhat, trainData.y)
    # evaluate loss on testing set
    yhat = model(testData.x)
    tstLoss[i] = loss(yhat, testData.y)
数据集
trainData
testData
分别有70和30个观察值。这可能只是一个新手问题,但当我运行训练单元时,它会在
trnLoss[I]=loss(yhat,trainData.y)
行上出现错误

ValueError: Target and input must have the same number of elements. target nelement (70) != input nelement (5)
当我检查
yhat=model(trainData.x)
行的输出时,我看到
yhat
是一个带有
batchSize
元素的张量,尽管
trainData.x.shape=torch.Size([70,2])

如何使用小批量梯度下降迭代训练模型,然后使用该模型计算完整训练集和测试集上的损失和精度?我尝试在小批量迭代之前设置
model.train()
,然后在求值代码之前设置
model.eval()
,但没有效果。

myNN.forward()
中,将小写字母
x
作为输入传递给
self.lin1
,而函数的输入参数命名为大写字母
x
。小写
x
是在for循环中为
trainload
定义的一种全局变量,因此您不会得到任何语法错误,但您要传递的值不会传递给
self.lin1


我也建议你应该考虑使用<代码>模型>()(<)/代码>和<代码>用Trask.NOEGRADE()/<代码>为您的测试代码。这不是绝对必要的,但会更有意义。

model=myNN(p,hiddenLayers,1)
中什么是
p
?还保留
model.eval()
之前的
yhat=model(trainData.x)
model.train()
之前的
用于x,y
我有
p=2
。我目前在您建议的位置调用了
model.train()
model.eval()
。(我说的“当前”,是指我已经添加了这些行,但仍然出错…)谢谢,将
X
修改为
X
解决了问题。模型的
forward()
评估将
x
的最新值读取为“全局”变量,这一事实解释了为什么
yhat
具有长度
batchSize
,尽管有输入。关于你的最后一点,我应该把我所有的评估代码(从
model.eval()
到循环的末尾)放在
里面,用torch.no_grade()
,对吗?最后一个问题,我应该写
model.eval()
,还是像我在网上看到的那样写
model=model.eval()
。谢谢1:是的,通常使用torch在
中编写所有评估代码是一个好的做法。no_grad()
块,因为我们不希望在评估期间计算梯度。2:调用
model.eval()
就足够了。确保在“循环的历元”开始时调用
model.train()
,以便在循环
trainLoad
之前将模型设置为列车模式。