import numpy as np
import math
import torch
import tensorflow as tf
import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'torch'
April 30, 2022
References: 1. https://github.com/jonkrohn/ML-foundations
ModuleNotFoundError: No module named 'torch'
Pytorch tensors can be used for operations on the GPU or CPU, unlike numpy arrays, by casting the tensor to a CUDA data type.
Tensorflow tensors are also immutable, and created using wrappers.
x = np.array([[5,6,7]]) #Need extra brackets else shape will be (,3) (1D, not 2D)
print(f"x = {x} \nShape = {x.shape}")
x = [[5 6 7]]
Shape = (1, 3)
x transposed:
[[5]
[6]
[7]]
Shape = (3, 1)
x = tensor([5, 6, 7])
Shape = torch.Size([3])
[[ 5 3]
[ 6 8]
[ 2 10]]
Shape: (3, 2) Size: 6
tensor([[ 5, 3],
[ 6, 8],
[ 2, 10]])
Shape: torch.Size([3, 2])
X*2 =
[[10 6]
[12 16]
[ 4 20]]
X+2 =
[[ 7 5]
[ 8 10]
[ 4 12]]
If tensors have the same size, operations can be aplied elementwise, this is the Hadamard product: \boldsymbol X \odot \boldsymbol Y It produces a tensor that is the same shape as the input, unlike the dot product which will produce a scalar value.
print(X.sum(), torch.sum(torch.tensor([[5,3],[6,8],[2,10]])))
print(tf.reduce_sum(tf.constant([[5,3],[6,8],[2,10]])))
print(X.sum(axis=0), X.sum(axis=1)) #along specific axes
print(torch.sum(torch.tensor([[5,3],[6,8],[2,10]]),0))
print(torch.sum(torch.tensor([[5,3],[6,8],[2,10]]),1))
print(tf.reduce_sum(tf.constant([[5,3],[6,8],[2,10]]),0))
print(tf.reduce_sum(tf.constant([[5,3],[6,8],[2,10]]),1))
34 tensor(34)
tf.Tensor(34, shape=(), dtype=int32)
[13 21] [ 8 14 12]
tensor([13, 21])
tensor([ 8, 14, 12])
tf.Tensor([13 21], shape=(2,), dtype=int32)
tf.Tensor([ 8 14 12], shape=(3,), dtype=int32)
The vectors must be of the same length or shape for the element-wise multiplication to occurr.
tensor(272)
A = np.array([[3,4],[5,6],[7,8]])
b = np.array([1,2])
print(np.dot(A,b)) #infers dot product vs matrix multiplication based on shape
C = torch.tensor([[3,4],[5,6],[7,8]])
d = torch.tensor([1,2])
print(torch.matmul(C,d))
E = tf.constant([[3,4],[5,6],[7,8]])
f = tf.constant([1,2])
print(tf.linalg.matvec(E,f))
tensor([11, 17, 23])
tf.Tensor([11 17 23], shape=(3,), dtype=int32)
A = np.array([[3,4],[5,6],[7,8]])
b = np.array([[1,9],[2,0]])
print(np.dot(A,b))
C = torch.tensor([[3,4],[5,6],[7,8]])
d = torch.tensor([[1,9],[2,0]])
print(torch.matmul(C,d))
E = tf.convert_to_tensor(A)
f = tf.convert_to_tensor(b)
print(tf.matmul(E,f))
[[11 27]
[17 45]
[23 63]]
tensor([[11, 27],
[17, 45],
[23, 63]])
tf.Tensor(
[[11 27]
[17 45]
[23 63]], shape=(3, 2), dtype=int64)