Setting Up PyTorch on Windows and Training Your First Model: A Complete Step-by-Step Guide
In this tutorial, we'll walk you through setting up Python and PyTorch on Windows and training your first model.
Setup Python and PyTorch
python --version
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
PyTorch - Explanation
python -c "import torch; print(torch.__version__)"
Project setup and development
import torch
import torch.nn as nn
import torch.optim as optim
Data preparation for heart disease prediction.
X = torch.tensor([
[63, 145, 233, 150], # Example 1
[37, 130, 250, 187], # Example 2
[41, 130, 204, 172], # Example 3
[56, 140, 236, 178], # Example 4
[57, 120, 354, 163] # Example 5
], dtype=torch.float32)
y = torch.tensor([[1], [0], [0], [1], [1]], dtype=torch.float32)
Simple Neural Network
领英推荐
class HeartDiseaseNN(nn.Module):
def __init__(self):
super(HeartDiseaseNN, self).__init__()
self.fc1 = nn.Linear(4, 16)
self.fc2 = nn.Linear(16, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return self.sigmoid(x)
model = HeartDiseaseNN()
Loss function and Optimizer
criterion = nn.BCELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
Train and test the model
for epoch in range(100):
model.train()
outputs = model(X)
loss = criterion(outputs, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 10 == 0:
print(f"Epoch [{epoch+1}/100], Loss: {loss.item():.4f}")
Test the model:
test_data = torch.tensor([[50, 140, 220, 160]], dtype=torch.float32) # Age, BP, Chol, Max HR
predicted_prob = model(test_data)
predicted_class = 1 if predicted_prob.item() > 0.5 else 0
print(f"Predicted Class (1 = Disease, 0 = No Disease): {predicted_class}")
python filename.py
Output:
Output explanation: