BatchNorm1d needs 2d input?PyTorch Linear layer input dimension mismatchHow does one create a data set in pytorch and save it into a file to later be used?Binary classifier always returns 0.5Highlighting important words in a sentence using Deep Learningscikit-learn regression prediction results are too good. What did I mess up?TensorFlow InvalidArgumentError/Value error occurs with small change of codeExpected tensor for argument #1 'input' to have the same dimensionValueError: expected 2D or 3D input (got 1D input) PyTorchPyTorch Experience Replay with multiple inputsNeed help understanding the label input in a CGAN

Command to Search for Filenames Exceeding 143 Characters?

How can I find where certain bash function is defined?

How do you say “buy” in the sense of “believe”?

Why are C64 games inconsistent with which joystick port they use?

Does this degree 12 genus 1 curve have only one point over infinitely many finite fields?

Why is this Simple Puzzle impossible to solve?

Dictionary size reduces upon increasing one element

How to convert to standalone document a matrix table

What is the largest (size) solid object ever dropped from an airplane to impact the ground in freefall?

Ticket sales for Queen at the Live Aid

Are there situations when self-assignment is useful?

I think I may have violated academic integrity last year - what should I do?

Under what law can the U.S. arrest International Criminal Court (ICC) judges over war crimes probe?

How did early x86 BIOS programmers manage to program full blown TUIs given very few bytes of ROM/EPROM?

Is CD audio quality good enough for the final delivery of music?

How can people dance around bonfires on Lag Lo'Omer - it's darchei emori?

Full backup on database creation

Why is desire the root of suffering?

Employer demanding to see degree after poor code review

What do different value notes on the same line mean?

If a person had control of every single cell of their body, would they be able to transform into another creature?

Mother abusing my finances

How strong are Wi-Fi signals?

How bitcoin nodes update UTXO set when their latests blocks are replaced?



BatchNorm1d needs 2d input?


PyTorch Linear layer input dimension mismatchHow does one create a data set in pytorch and save it into a file to later be used?Binary classifier always returns 0.5Highlighting important words in a sentence using Deep Learningscikit-learn regression prediction results are too good. What did I mess up?TensorFlow InvalidArgumentError/Value error occurs with small change of codeExpected tensor for argument #1 'input' to have the same dimensionValueError: expected 2D or 3D input (got 1D input) PyTorchPyTorch Experience Replay with multiple inputsNeed help understanding the label input in a CGAN






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I want to fix problem in PyTorch.
I wrote the following code that is learning sine functions as tutorial.



import torch
from torch import nn
from torch import optim
from torch.autograd import Variable as V
from torch.utils.data import TensorDataset, DataLoader
import numpy as np

# y=sin(x1)
numTrain = 512
numTest = 128
noiseScale = 0.01
PI2 = 3.1415 * 2
X_train = np.random.rand(numTrain,1) * PI2
y_train = np.sin(X_train) + np.random.randn(numTrain,1) * noiseScale + 1.5
X_test = np.random.rand(numTest,1) * PI2
y_test = np.sin(X_test) + np.random.randn(numTest,1) * noiseScale

# Construct DataSet
X_trainT = torch.Tensor(X_train)
y_trainT = torch.Tensor(y_train)
X_testT = torch.Tensor(X_test)
y_testT = torch.Tensor(y_test)
ds_train = TensorDataset(X_trainT, y_trainT)
ds_test = TensorDataset(X_testT, y_testT)

# Construct DataLoader
loader_train = DataLoader(ds_train, batch_size=64, shuffle=True)
loader_test = DataLoader(ds_test, batch_size=64, shuffle=False)

# Construct network
net = nn.Sequential(
nn.Linear(1,10),
nn.ReLU(),
nn.BatchNorm1d(10),
nn.Linear(10,5),
nn.ReLU(),
nn.BatchNorm1d(5),
nn.Linear(5,1),
)
optimizer = optim.Adam(net.parameters())
loss_fn = nn.SmoothL1Loss()

# Training
losses = []
net.train()
for epoc in range(100):
for data, target in loader_train:
y_pred = net(data)
loss = loss_fn(target,y_pred)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.data)


# evaluation
%matplotlib inline
from matplotlib import pyplot as plt

#plt.plot(losses)
plt.scatter(X_train, y_train)

net.eval()
sinsX = []
sinsY = []
for t in range(128):
x = t/128 * PI2
output = net(V(torch.Tensor([x])))
sinsX.append(x)
sinsY.append(output.detach().numpy())
plt.scatter(sinsX,sinsY)


Training is done without error, But the next line caused an error, "expected 2D or 3D input (got 1D input)"



output = net(V(torch.Tensor([x])))


This error doesn't occur if it is without BatchNorm1d().
I feel strange because the input is 1D.



How to fix it?



Thanks.



Update: How did I fix



arr = np.array([x])
output = net(V(torch.Tensor(arr[None,...])))









share|improve this question
























  • You should take a look at the Documentation, there you can see what kind of input BatchNorm1d expects. pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d

    – blue-phoenox
    Mar 24 at 7:03

















1















I want to fix problem in PyTorch.
I wrote the following code that is learning sine functions as tutorial.



import torch
from torch import nn
from torch import optim
from torch.autograd import Variable as V
from torch.utils.data import TensorDataset, DataLoader
import numpy as np

# y=sin(x1)
numTrain = 512
numTest = 128
noiseScale = 0.01
PI2 = 3.1415 * 2
X_train = np.random.rand(numTrain,1) * PI2
y_train = np.sin(X_train) + np.random.randn(numTrain,1) * noiseScale + 1.5
X_test = np.random.rand(numTest,1) * PI2
y_test = np.sin(X_test) + np.random.randn(numTest,1) * noiseScale

# Construct DataSet
X_trainT = torch.Tensor(X_train)
y_trainT = torch.Tensor(y_train)
X_testT = torch.Tensor(X_test)
y_testT = torch.Tensor(y_test)
ds_train = TensorDataset(X_trainT, y_trainT)
ds_test = TensorDataset(X_testT, y_testT)

# Construct DataLoader
loader_train = DataLoader(ds_train, batch_size=64, shuffle=True)
loader_test = DataLoader(ds_test, batch_size=64, shuffle=False)

# Construct network
net = nn.Sequential(
nn.Linear(1,10),
nn.ReLU(),
nn.BatchNorm1d(10),
nn.Linear(10,5),
nn.ReLU(),
nn.BatchNorm1d(5),
nn.Linear(5,1),
)
optimizer = optim.Adam(net.parameters())
loss_fn = nn.SmoothL1Loss()

# Training
losses = []
net.train()
for epoc in range(100):
for data, target in loader_train:
y_pred = net(data)
loss = loss_fn(target,y_pred)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.data)


# evaluation
%matplotlib inline
from matplotlib import pyplot as plt

#plt.plot(losses)
plt.scatter(X_train, y_train)

net.eval()
sinsX = []
sinsY = []
for t in range(128):
x = t/128 * PI2
output = net(V(torch.Tensor([x])))
sinsX.append(x)
sinsY.append(output.detach().numpy())
plt.scatter(sinsX,sinsY)


Training is done without error, But the next line caused an error, "expected 2D or 3D input (got 1D input)"



output = net(V(torch.Tensor([x])))


This error doesn't occur if it is without BatchNorm1d().
I feel strange because the input is 1D.



How to fix it?



Thanks.



Update: How did I fix



arr = np.array([x])
output = net(V(torch.Tensor(arr[None,...])))









share|improve this question
























  • You should take a look at the Documentation, there you can see what kind of input BatchNorm1d expects. pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d

    – blue-phoenox
    Mar 24 at 7:03













1












1








1








I want to fix problem in PyTorch.
I wrote the following code that is learning sine functions as tutorial.



import torch
from torch import nn
from torch import optim
from torch.autograd import Variable as V
from torch.utils.data import TensorDataset, DataLoader
import numpy as np

# y=sin(x1)
numTrain = 512
numTest = 128
noiseScale = 0.01
PI2 = 3.1415 * 2
X_train = np.random.rand(numTrain,1) * PI2
y_train = np.sin(X_train) + np.random.randn(numTrain,1) * noiseScale + 1.5
X_test = np.random.rand(numTest,1) * PI2
y_test = np.sin(X_test) + np.random.randn(numTest,1) * noiseScale

# Construct DataSet
X_trainT = torch.Tensor(X_train)
y_trainT = torch.Tensor(y_train)
X_testT = torch.Tensor(X_test)
y_testT = torch.Tensor(y_test)
ds_train = TensorDataset(X_trainT, y_trainT)
ds_test = TensorDataset(X_testT, y_testT)

# Construct DataLoader
loader_train = DataLoader(ds_train, batch_size=64, shuffle=True)
loader_test = DataLoader(ds_test, batch_size=64, shuffle=False)

# Construct network
net = nn.Sequential(
nn.Linear(1,10),
nn.ReLU(),
nn.BatchNorm1d(10),
nn.Linear(10,5),
nn.ReLU(),
nn.BatchNorm1d(5),
nn.Linear(5,1),
)
optimizer = optim.Adam(net.parameters())
loss_fn = nn.SmoothL1Loss()

# Training
losses = []
net.train()
for epoc in range(100):
for data, target in loader_train:
y_pred = net(data)
loss = loss_fn(target,y_pred)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.data)


# evaluation
%matplotlib inline
from matplotlib import pyplot as plt

#plt.plot(losses)
plt.scatter(X_train, y_train)

net.eval()
sinsX = []
sinsY = []
for t in range(128):
x = t/128 * PI2
output = net(V(torch.Tensor([x])))
sinsX.append(x)
sinsY.append(output.detach().numpy())
plt.scatter(sinsX,sinsY)


Training is done without error, But the next line caused an error, "expected 2D or 3D input (got 1D input)"



output = net(V(torch.Tensor([x])))


This error doesn't occur if it is without BatchNorm1d().
I feel strange because the input is 1D.



How to fix it?



Thanks.



Update: How did I fix



arr = np.array([x])
output = net(V(torch.Tensor(arr[None,...])))









share|improve this question
















I want to fix problem in PyTorch.
I wrote the following code that is learning sine functions as tutorial.



import torch
from torch import nn
from torch import optim
from torch.autograd import Variable as V
from torch.utils.data import TensorDataset, DataLoader
import numpy as np

# y=sin(x1)
numTrain = 512
numTest = 128
noiseScale = 0.01
PI2 = 3.1415 * 2
X_train = np.random.rand(numTrain,1) * PI2
y_train = np.sin(X_train) + np.random.randn(numTrain,1) * noiseScale + 1.5
X_test = np.random.rand(numTest,1) * PI2
y_test = np.sin(X_test) + np.random.randn(numTest,1) * noiseScale

# Construct DataSet
X_trainT = torch.Tensor(X_train)
y_trainT = torch.Tensor(y_train)
X_testT = torch.Tensor(X_test)
y_testT = torch.Tensor(y_test)
ds_train = TensorDataset(X_trainT, y_trainT)
ds_test = TensorDataset(X_testT, y_testT)

# Construct DataLoader
loader_train = DataLoader(ds_train, batch_size=64, shuffle=True)
loader_test = DataLoader(ds_test, batch_size=64, shuffle=False)

# Construct network
net = nn.Sequential(
nn.Linear(1,10),
nn.ReLU(),
nn.BatchNorm1d(10),
nn.Linear(10,5),
nn.ReLU(),
nn.BatchNorm1d(5),
nn.Linear(5,1),
)
optimizer = optim.Adam(net.parameters())
loss_fn = nn.SmoothL1Loss()

# Training
losses = []
net.train()
for epoc in range(100):
for data, target in loader_train:
y_pred = net(data)
loss = loss_fn(target,y_pred)
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.append(loss.data)


# evaluation
%matplotlib inline
from matplotlib import pyplot as plt

#plt.plot(losses)
plt.scatter(X_train, y_train)

net.eval()
sinsX = []
sinsY = []
for t in range(128):
x = t/128 * PI2
output = net(V(torch.Tensor([x])))
sinsX.append(x)
sinsY.append(output.detach().numpy())
plt.scatter(sinsX,sinsY)


Training is done without error, But the next line caused an error, "expected 2D or 3D input (got 1D input)"



output = net(V(torch.Tensor([x])))


This error doesn't occur if it is without BatchNorm1d().
I feel strange because the input is 1D.



How to fix it?



Thanks.



Update: How did I fix



arr = np.array([x])
output = net(V(torch.Tensor(arr[None,...])))






machine-learning deep-learning pytorch






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 6:59









Shai

71.6k23140253




71.6k23140253










asked Mar 24 at 5:00









qqqqqq

83




83












  • You should take a look at the Documentation, there you can see what kind of input BatchNorm1d expects. pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d

    – blue-phoenox
    Mar 24 at 7:03

















  • You should take a look at the Documentation, there you can see what kind of input BatchNorm1d expects. pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d

    – blue-phoenox
    Mar 24 at 7:03
















You should take a look at the Documentation, there you can see what kind of input BatchNorm1d expects. pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d

– blue-phoenox
Mar 24 at 7:03





You should take a look at the Documentation, there you can see what kind of input BatchNorm1d expects. pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d

– blue-phoenox
Mar 24 at 7:03












1 Answer
1






active

oldest

votes


















0














When working with 1D signals, pyTorch actually expects a 2D tensors: the first dimension is the "mini-batch" dimension. Therefore, you should evaluate your net on a batch with one 1D signal:



output - net(V(torch.Tensor([x[None, ...]]))


Make sure you set your net to "eval" mode before evaluating it:



net.eval()





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320883%2fbatchnorm1d-needs-2d-input%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    When working with 1D signals, pyTorch actually expects a 2D tensors: the first dimension is the "mini-batch" dimension. Therefore, you should evaluate your net on a batch with one 1D signal:



    output - net(V(torch.Tensor([x[None, ...]]))


    Make sure you set your net to "eval" mode before evaluating it:



    net.eval()





    share|improve this answer



























      0














      When working with 1D signals, pyTorch actually expects a 2D tensors: the first dimension is the "mini-batch" dimension. Therefore, you should evaluate your net on a batch with one 1D signal:



      output - net(V(torch.Tensor([x[None, ...]]))


      Make sure you set your net to "eval" mode before evaluating it:



      net.eval()





      share|improve this answer

























        0












        0








        0







        When working with 1D signals, pyTorch actually expects a 2D tensors: the first dimension is the "mini-batch" dimension. Therefore, you should evaluate your net on a batch with one 1D signal:



        output - net(V(torch.Tensor([x[None, ...]]))


        Make sure you set your net to "eval" mode before evaluating it:



        net.eval()





        share|improve this answer













        When working with 1D signals, pyTorch actually expects a 2D tensors: the first dimension is the "mini-batch" dimension. Therefore, you should evaluate your net on a batch with one 1D signal:



        output - net(V(torch.Tensor([x[None, ...]]))


        Make sure you set your net to "eval" mode before evaluating it:



        net.eval()






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 24 at 7:22









        ShaiShai

        71.6k23140253




        71.6k23140253





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320883%2fbatchnorm1d-needs-2d-input%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현