Quick Start with PyTorch
PyTorch is an open-source machine learning framework developed by Facebook AI Research. It is based on the Torch library and is primarily used for building deep neural networks.
Here's a step-by-step guide to getting started with PyTorch:
pip install torch torchvision
2. Import PyTorch: After installing PyTorch, you can import it in your Python code using the following command:
import torch
3. Create a tensor: Tensors are the fundamental data structure in PyTorch. They are similar to NumPy arrays but can be run on a GPU for faster computation. Here's an example of how to create a tensor:
x = torch.tensor([[1, 2], [3, 4]])
import torch.nn as nn
class NeuralNet(nn.Module):
??def __init__(self):
????super(NeuralNet, self).__init__()
????self.fc1 = nn.Linear(2, 10) # input layer to hidden layer
????self.fc2 = nn.Linear(10, 1) # hidden layer to output layer
??def forward(self, x):
????x = torch.relu(self.fc1(x))
????x = self.fc2(x)
????return x
4. Define a loss function: The loss function measures how well the neural network is performing. In PyTorch, you can define a loss function using the nn module. Here's an example of how to define the mean squared error (MSE) loss function:
领英推荐
loss_fn = nn.MSELoss()
5. Define an optimizer: The optimizer adjusts the parameters of the neural network to minimize the loss function. In PyTorch, you can define an optimizer using the optim module. Here's an example of how to define the stochastic gradient descent (SGD) optimizer:
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
6. Train the neural network: To train the neural network, you need to feed the input data through the network, compute the loss, backpropagate the error, and update the parameters using the optimizer. Here's an example of how to train the neural network for 100 epochs:
for epoch in range(100):
??# Forward pass
??y_pred = model(x)
??# Compute loss
??loss = loss_fn(y_pred, y)
??# Zero gradients
??optimizer.zero_grad()
??# Backward pass
??loss.backward()
??# Update parameters
??optimizer.step()
7. Once you have trained your neural network model in PyTorch, you can use it to make predictions on new data. Here's an example of how to use the trained model to predict the output for a new input:
# Create a new input tensor
new_input = torch.tensor([[5, 6]])
# Make a prediction
with torch.no_grad():
??output = model(new_input)
# Print the predicted output
print(output)