我正在学习Pythorch,并有以下(缩写)代码来设置建模:
# 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)
、和{
数据集trainData
和{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
元素的张量,尽管{
我该如何迭代地用小批量梯度下降训练模型,然后使用该模型计算完整训练和测试集的损失和精确度?我尝试在小批量迭代之前设置model.train()
,然后在计算代码之前设置model.eval()
,但没有成功。在
我想你想要的是:
您可能还希望这些文件可以通过系统属性进行配置。您可以使用
@Value
注释,使用PropertyPlaceholderConfigurer
和${}
语法读取系统属性为此,可以在
@Value
注释中使用不同的String
值:但在系统属性中也需要这些属性:
相关问题 更多 >
编程相关推荐