Python 派托克火车公司;评估不同的样本量
我正在学习pytorch,并有以下(缩写)代码用于建模: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
# 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
之前将模型设置为列车模式。