当数据集的维度为[64 x 25088]时,`nn.Linear(1024, 256)`应该设置什么值?

我在pytorch中一直遇到错误,说我输入的大小不对:

RuntimeError: size mismatch, m1: [64 x 25088], m2: [1024 x 256] at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THC/generic/THCTensorMathBlas.cu:249

如果我将nn.Linear设置为64 x 25088,我会得到类似的错误:

RuntimeError: size mismatch, m1: [64 x 25088], m2: [64 x 25088] at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THC/generic/THCTensorMathBlas.cu:249

这是怎么回事?

这是产生错误的代码:

model = models.vgg16(pretrained=True)# Freeze parameters so we don't backprop through themfor param in model.parameters():    param.requires_grad = Falsemodel.classifier = nn.Sequential(nn.Linear(64, 25088),                                 nn.ReLU(),                                 nn.Dropout(0.2),                                 nn.Linear(256, 2),                                 nn.LogSoftmax(dim=1))criterion = nn.NLLLoss()# Only train the classifier parameters, feature parameters are frozenoptimizer = optim.Adam(model.classifier.parameters(), lr=0.003)# Use GPU if it's availabledevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device);epochs = 1steps = 0running_loss = 0print_every = 5with active_session():    for epoch in range(epochs):        for inputs, labels in trainloader:            steps += 1            # Move input and label tensors to the default device            inputs, labels = inputs.to(device), labels.to(device)            optimizer.zero_grad()            logps = model.forward(inputs)            loss = criterion(logps, labels)            loss.backward()            optimizer.step()            running_loss += loss.item()            if steps % print_every == 0:                test_loss = 0                accuracy = 0                model.eval()                with torch.no_grad():                    for inputs, labels in testloader:                        inputs, labels = inputs.to(device), labels.to(device)                        logps = model.forward(inputs)                        batch_loss = criterion(logps, labels)                        test_loss += batch_loss.item()                        # Calculate accuracy                        ps = torch.exp(logps)                        top_p, top_class = ps.topk(1, dim=1)                        equals = top_class == labels.view(*top_class.shape)                        accuracy += torch.mean(equals.type(torch.FloatTensor)).item()                print(f"Epoch {epoch+1}/{epochs}.. "                      f"Train loss: {running_loss/print_every:.3f}.. "                      f"Test loss: {test_loss/len(testloader):.3f}.. "                      f"Test accuracy: {accuracy/len(testloader):.3f}")                running_loss = 0                model.train()

回答:

在nn.Linear()中,第一个参数是输入的大小,第二个参数是输出的尺寸。如果你的数据尺寸是64 x 25088,那么你需要设置nn.Linear(64*25088, 输出尺寸)。

然而,这一层将会非常大,所以你应该尝试减小你的数据尺寸。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注