Pythorch列车和评估不同样本大小

2024-04-25 12:38:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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)、和{}。培训守则是:

^{pr2}$

数据集trainData和{}分别有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元素的张量,尽管{}事实上。在

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


Tags: theselfdatamodellenreturninitdef
1条回答
网友
1楼 · 发布于 2024-04-25 12:38:57

我想你想要的是:

@Component
public class MyBean {
    private String xmlFile;
    private String xsdFile;

    @Autowired
    public MyBean(@Value("$MYDIR/myfile.xml") final String xmlFile,
            @Value("$MYDIR/myfile.xsd") final String xsdFile) {
        this.xmlFile = xmlFile;
        this.xsdFile = xsdFile;
    }

    //methods
}

您可能还希望这些文件可以通过系统属性进行配置。您可以使用@Value注释,使用PropertyPlaceholderConfigurer${}语法读取系统属性

为此,可以在@Value注释中使用不同的String值:

@Value("${my.xml.file.property}")
@Value("${my.xsd.file.property}")

但在系统属性中也需要这些属性:

my.xml.file.property=$MYDIR/myfile.xml
my.xsd.file.property=$MYDIR/myfile.xsd

相关问题 更多 >

    热门问题