Thursday, May 7, 2026
HomeLanguagesPython Pytorch ones() method

Python Pytorch ones() method

PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.

The function torch.ones() returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.

Syntax: torch.ones(size, out=None)

Parameters:
size: a sequence of integers defining the shape of the output tensor
out (Tensor, optional): the output tensor

Return type: A tensor filled with scalar value 1, of same shape as size.

Code #1:




# Importing the PyTorch library
import torch
  
  
# Applying the ones function and
# storing the resulting tensor in 't'
a = torch.ones([3, 4])
print("a = ", a)
  
b = torch.ones([1, 5])
print("b = ", b)
  
c = torch.ones([5, 1])
print("c = ", c)
  
d = torch.ones([3, 3, 2])
print("d = ", d)


Output:

a =  tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
b =  tensor([[1., 1., 1., 1., 1.]])
c =  tensor([[1.],
        [1.],
        [1.],
        [1.],
        [1.]])
d =  tensor([[[1., 1.],
         [1., 1.],
         [1., 1.]],

        [[1., 1.],
         [1., 1.],
         [1., 1.]],

        [[1., 1.],
         [1., 1.],
         [1., 1.]]])


 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6891 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12105 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6962 POSTS0 COMMENTS