Learn practical skills, build real-world projects, and advance your career

Assignment 1 of Pytorch: zero to GANs

import torch
import numpy as np
# .solve function
# example 1
df = torch.tensor([[6, 4.],
                   [4, 0]], dtype=torch.float32).t()
b = torch.tensor([[0, -2.]], dtype=torch.float32).t()
x, lu = torch.solve(b, df)
print(df, b, x, sep='\n')
# example 2
df = torch.tensor([[6, 4, 2],
                   [4, 0, 1],
                   [2, 5, 0.]], dtype=torch.float32).t()
b = torch.tensor([[0, -2., 4]], dtype=torch.float32).t()
x, lu = torch.solve(b, df)
print(df, b, x, sep='\n')
# example not working
df = torch.tensor([[6, 0, 4.],
                   [4, 1, 0]], dtype=torch.float32).t()
b = torch.tensor([[0, -2.]], dtype=torch.float32).t()
x, lu = torch.solve(b, df)
print(df, b, x, sep='\n')
tensor([[6., 4.], [4., 0.]]) tensor([[ 0.], [-2.]]) tensor([[-0.5000], [ 0.7500]]) tensor([[6., 4., 2.], [4., 0., 5.], [2., 1., 0.]]) tensor([[ 0.], [-2.], [ 4.]]) tensor([[ 4.2222], [-4.4444], [-3.7778]])
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-51-02657424936b> in <module> 17 [4, 1, 0]], dtype=torch.float32).t() 18 b = torch.tensor([[0, -2.]], dtype=torch.float32).t() ---> 19 x, lu = torch.solve(b, df) 20 print(df, b, x, sep='\n') RuntimeError: A must be batches of square matrices, but they are 2 by 3 matrices
.solve applies the matrix equation AX = b and there should be the same number of rows and columns in matrix A, df in this case.
# .eig function
# example 1
H = torch.tensor([[0, 1, 0],
                  [1, 0, 0],
                  [0, 0, 6.]], dtype=torch.float32)
eigpairs = torch.eig(H, eigenvectors=True)
print(H, eigpairs, sep='\n')
# example 2
H = torch.tensor([[1, 0, 0],
                  [0, 1, 0],
                  [0, 0, 1.]], dtype=torch.float32)
eigpairs = torch.eig(H, eigenvectors=True)
print(H, eigpairs, sep='\n')
# example not working
H = torch.tensor([[0, 1, 0],
                  [1, 0, 0],
                  [0, 0, 6]], dtype=torch.int32)
eigpairs = torch.eig(H, eigenvectors=True)
print(H, eigpairs, sep='\n')
tensor([[0., 1., 0.], [1., 0., 0.], [0., 0., 6.]]) torch.return_types.eig( eigenvalues=tensor([[ 1., 0.], [-1., 0.], [ 6., 0.]]), eigenvectors=tensor([[ 0.7071, -0.7071, 0.0000], [ 0.7071, 0.7071, 0.0000], [ 0.0000, 0.0000, 1.0000]])) tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) torch.return_types.eig( eigenvalues=tensor([[1., 0.], [1., 0.], [1., 0.]]), eigenvectors=tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]))
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-52-54418a1b1eb1> in <module> 16 [1, 0, 0], 17 [0, 0, 6]], dtype=torch.int32) ---> 18 eigpairs = torch.eig(H, eigenvectors=True) 19 print(H, eigpairs, sep='\n') RuntimeError: _th_eig not supported on CPUType for Int