Learn practical skills, build real-world projects, and advance your career
Updated 4 years ago
Assignment - 1
5 Functions in pytorch
import torch
# as_stride function
#first example
x = torch.tensor([[1.,2,3],[4.,5,6],[7.,8,9]])
y = torch.as_strided(x,(3,2),(3,1))
print(y)
# second example
y = torch.as_strided(x,(2,3),(1,2))
print(y)
#not working case
y = torch.as_strided(x,(2,2),(1,9))
print(y)
tensor([[1., 2.],
[4., 5.],
[7., 8.]])
tensor([[1., 3., 5.],
[2., 4., 6.]])
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-6-dbe762cef27d> in <module>
8 print(y)
9 #not working case
---> 10 y = torch.as_strided(x,(2,2),(1,9))
11 print(y)
RuntimeError: setStorage: sizes [2, 2], strides [1, 9], and storage offset 0 requiring a storage size of 11 are out of bounds for storage with numel 9
as_stride function displays the tensor in a different shape and with values based on the specified parameters.
it takes 3 parameters. the tensor itself , the shape in which to be displayed and the difference in position of the element adjacent to it in the columnwise and also row wise as a tuple.
# the eye function
#example 1
a = 3*torch.eye(5)
print(a)
#example 2
a = 4*torch.eye(8)
print(a)
#not working case
a = torch.eye(-1)
print(a)
tensor([[3., 0., 0., 0., 0.],
[0., 3., 0., 0., 0.],
[0., 0., 3., 0., 0.],
[0., 0., 0., 3., 0.],
[0., 0., 0., 0., 3.]])
tensor([[4., 0., 0., 0., 0., 0., 0., 0.],
[0., 4., 0., 0., 0., 0., 0., 0.],
[0., 0., 4., 0., 0., 0., 0., 0.],
[0., 0., 0., 4., 0., 0., 0., 0.],
[0., 0., 0., 0., 4., 0., 0., 0.],
[0., 0., 0., 0., 0., 4., 0., 0.],
[0., 0., 0., 0., 0., 0., 4., 0.],
[0., 0., 0., 0., 0., 0., 0., 4.]])
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-9-b288c7f44d99> in <module>
7 print(a)
8 #not working case
----> 9 a = torch.eye(-1)
10 print(a)
RuntimeError: n must be greater or equal to 0, got -1