Skip to content

Commit

Permalink
setup Anaconda, Spyder, did first couple tutorials, pytorch working i…
Browse files Browse the repository at this point in the history
…n environment
  • Loading branch information
Dylan-Riley committed Jul 2, 2021
1 parent 40dc855 commit 6301ae2
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
22 changes: 22 additions & 0 deletions gentle_intro_to_autograd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import torch, torchvision

# Load a pretrained resnet18 model
model = torchvision.models.resnet18(pretrained=True)

# Random tensor data to represent an image with three channels and height/width of 64
data = torch.rand(1,3,64,64)
# Image's label init'd to some random values
labels = torch.rand(1,1000)

# Run the input data through the model to make a prediction
prediction = model(data) # forward pass

# Calculate the error and backpropagate through the network
loss = (prediction - labels).sum()
loss.backward() # backward pass

# Load an optimizer with a learning rate of 0.01 and momentum of 0.9
optim = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.9)

# Initiate gradient descent
optim.step() # gradient descent
49 changes: 49 additions & 0 deletions tensors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import torch
import numpy as np

# Examples of Tensors being initialized
data = [[1,2],[3,4]]

# Directly from data, data type is inferred
xData = torch.tensor(data)

# From a NumPy array
npArray = np.array(data)
xNP = torch.from_numpy(npArray)

# From another tensor, retaining properties of the original
xOnes = torch.ones_like(xData)
print(f"Ones Tensor: \n {xOnes} \n")

# From another tensor, overriding the datatype
xRand = torch.rand_like(xData, dtype=torch.float)
print(f"Random Tensor: \n {xRand} \n")

# shape defines the tensor dimensions
shape = (2,3,)
randomTensor = torch.rand(shape)
onesTensor = torch.ones(shape)
zerosTensor = torch.zeros(shape)

print(f"Random Tensor: \n {randomTensor} \n")
print(f"Ones Tensor: \n {onesTensor} \n")
print(f"Zeros Tensor: \n {zerosTensor} \n")

# Tensors have attributes for their shape, datatype, and device
attrDemoTensor = torch.rand(3,4)
print(f"Shape: {attrDemoTensor.shape}")
print(f"Datatype: {attrDemoTensor.dtype}")
print(f"Device: {attrDemoTensor.device} \n")

# Torch has a ton of tensor operations buil-in, apparently similar to NumPy
tensor = torch.ones(4,4)
print(f"{tensor} \n")
tensor[:,1] = 0
print(f"{tensor} \n")

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(f"{t1} \n")

# Operations with a _ suffix are performed in-place
tensor.add_(5)
print(tensor)
6 changes: 6 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import torch

print("Hello World!")

x = torch.rand(5,3)
print(x)

0 comments on commit 6301ae2

Please sign in to comment.