0
0
PyTorchml~10 mins

First PyTorch computation - ML Experiment: Train & Evaluate

Choose your learning style9 modes available
Experiment - First PyTorch computation
Problem:You want to perform a simple computation using PyTorch tensors to understand how PyTorch works.
Current Metrics:No metrics yet because no computation or model training has been done.
Issue:You are new to PyTorch and need to learn how to create tensors and perform basic operations.
Your Task
Create two tensors, add them, and print the result. Then multiply the result by 2 and print it.
Use PyTorch tensors only.
Do not use NumPy or other libraries for the computation.
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch

# Create two tensors
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])

# Add tensors
z = x + y
print(f"Sum of tensors: {z}")

# Multiply the result by 2
result = z * 2
print(f"Result after multiplication by 2: {result}")
Created two 1D tensors x and y with values [1, 2, 3] and [4, 5, 6].
Added the tensors using the + operator.
Multiplied the sum tensor by 2 using the * operator.
Printed both intermediate and final results.
Results Interpretation

Before: No computation done, no output.

After: Successfully created tensors, added them, and multiplied the result. Output shows correct tensor values.

This experiment shows how to create tensors and perform basic arithmetic operations in PyTorch, which is the foundation for building machine learning models.
Bonus Experiment
Try creating two 2D tensors (matrices), perform matrix multiplication, and print the result.
💡 Hint
Use torch.matmul() or the @ operator for matrix multiplication.