【问题标题】:Pytorch: How to format data before execution of machine learningPytorch:如何在执行机器学习之前格式化数据
【发布时间】:2018-05-20 07:08:24
【问题描述】:

我正在学习如何使用 pytorch,并且能够掌握 ML 模型的构建和执行的整个过程。但是,我无法掌握的是如何在执行模型之前“格式化”或“重塑”数据。我不断收到以下错误:

RuntimeError:大小不匹配,m1:[1 x 700],m2:[1 x 1] 在 c:\programdata\miniconda3\conda-bld\pytorch_1524543037166\work\aten\src\th\generic/THTensorMath.c :2033

或者,

预期变量类型为变量 [torch.DoubleTensor] 的对象,但为参数 #1 ‘mat2’找到变量类型 [torch.FloatTensor]

所以,我有一个名为“train.csv”的 csv 文件,其中包含名为“x”和“y”的属性,其中有 700 个样本,我想对数据执行简单的线性回归,然后解析数据从它使用熊猫,我如何格式化或重塑数据,使其能够顺利执行? pytorch 是如何遍历输入数据的?

我最近执行的代码是:

import torch
import torch.nn as nn
from torch.autograd import Variable
import pandas as pd

class Linear_Reg(nn.Module):
    def __init__(self, inp_sz, out_sz):    
        super(Linear_Reg, self).__init__()
        self.linear = nn.Linear(inp_sz, out_sz)

    def forward(self, x):
        out = self.linear(x)
        return out

train = pd.read_csv('C:\\Users\\hgstr\\Jupyter_Files\\Data_Sets\\linear_regression\\train.csv')
test = pd.read_csv('C:\\Users\\hgstr\\Jupyter_Files\\Data_Sets\\linear_regression\\test.csv')

x_train = torch.Tensor(train['x'])
y_train = torch.Tensor(train['y'])

x_test = torch.Tensor(test['x'])
y_test = torch.Tensor(test['y'])

x_train = torch.Tensor(x_train)
x_train = x_train.view(1,-1)

#================================
input_sz = 1;
output_sz = 1
epochs = 60
learning_rate = 0.001
#================================

model = Linear_Reg(input_sz, output_sz)
crit = nn.MSELoss()
opt = torch.optim.SGD(model.parameters(), learning_rate)

for e in range(epochs):

    opt.zero_grad()
    out = model(x_train)

    loss = crit(out, y_train)
    loss.backward()
    opt.step()

    print('epoch {}, loss {}'.format(e,loss.data[0]))

它给出了以下内容:

RuntimeError:大小不匹配,m1:[1 x 700],m2:[1 x 1] 在 c:\programdata\miniconda3\conda-bld\pytorch_1524543037166\work\aten\src\th\generic/THTensorMath.c :2033

解决方案?

【问题讨论】:

    标签: python machine-learning linear-regression pytorch


    【解决方案1】:

    根据错误,我认为您的数据格式不正确。张量的格式应该是[700, 2] (batch x data),而你的格式是[1, 700] (data x batch)。这使模型“认为”您只添加一个条目作为具有 700 个特征的训练,而不是仅添加 1 个特征的 700 个条目。

    重塑x_train 变量应该可以使代码正常工作。只需删除行x_train = x_train.view(1,-1)

    关于第二个错误,可能是在将 .csv 读入变量后,其类型为 Double(由于 pd.read_csv),而在 pytorch 中,默认情况下,张量创建为浮点数。我认为在将输入数据提供给模型之前将其转换就足够了:model(x_train.float()) 或在张量创建部分 x_train = torch.FloatTensor(train['x']) 中指定它。请注意,您应该转换所有不是浮点数的张量。

    编辑:这段代码对我有用

    import torch
    import torch.nn as nn
    import pandas as pd
    
    class Linear_Reg(nn.Module):
        def __init__(self, inp_sz, out_sz):
            super(Linear_Reg, self).__init__()
            self.linear = nn.Linear(inp_sz, out_sz)
    
        def forward(self, x):
            out = self.linear(x)
            return out
    
    
    train = pd.read_csv('yourpath')
    test = pd.read_csv('yourpath')
    
    x_train = torch.Tensor(train['x']).to(torch.float).view(700, 1)
    y_train = torch.Tensor(train['y']).to(torch.float).view(700, 1)
    
    x_test = torch.Tensor(test['x']).to(torch.float).view(300, 1)
    y_test = torch.Tensor(test['y']).to(torch.float).view(300, 1)
    
    # ================================
    input_sz = 1;
    output_sz = 1
    epochs = 60
    learning_rate = 0.001
    # ================================
    
    model = Linear_Reg(input_sz, output_sz)
    crit = nn.MSELoss()
    opt = torch.optim.SGD(model.parameters(), learning_rate)
    
    for e in range(epochs):
        opt.zero_grad()
        out = model(x_train)
    
        loss = crit(out, y_train)
        loss.backward()
        opt.step()
    
        print('epoch {}, loss {}'.format(e, loss.data[0]))
    

    【讨论】:

    • y_train 呢?我们需要做出任何改变吗?
    • 我不知道y_train 的形状是什么,所以我无法猜测第一个错误的结果。对于第二个,您可能需要强制转换为浮动。尝试运行代码,看看会发生什么。
    • 形状也是 700,我在问题中提到有 700 个 x 和 y 值样本,我将它们都提取出来并实现了“查看”操作来重塑它们
    • 您是否尝试使用我评论的内容更改代码?如果你这样做了,输出是什么?
    • 我得到了 -> 'torch.dtype' 对象不可调用
    猜你喜欢
    • 2017-12-26
    • 2019-10-15
    • 2021-03-08
    • 2022-12-03
    • 2017-05-23
    • 2019-12-07
    • 1970-01-01
    • 2015-06-02
    • 2017-03-26
    相关资源
    最近更新 更多