Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Creating a Simple Neural Network | Neural Networks
Neural Networks with PyTorch
course content

Contenido del Curso

Neural Networks with PyTorch

Neural Networks with PyTorch

1. PyTorch Basics
2. Preparing for Neural Networks
3. Neural Networks

book
Creating a Simple Neural Network

In this chapter, we will build a basic PyTorch neural network using the wine quality dataset, a classic dataset in machine learning. The goal of this task is to predict wine quality (target) based on its physicochemical properties (features). We will focus on defining a Model class for the neural network using PyTorch's nn.Module.

Dataset Overview

The wine quality dataset contains information about red or white wine samples. Each sample has physicochemical properties such as acidity, sugar content, and pH as features, along with a target variable indicating the quality score (classified as an integer from 0 to 10).

1234
import pandas as pd wine_df = pd.read_csv("winequality.csv") print(wine_df.head())
copy

Implementation Steps

  1. Import Libraries: We'll begin by importing the required PyTorch modules (torch, nn, F) and loading the dataset using pandas.

  2. Define the Model Class: Create a PyTorch model class that:

    • Inherits from nn.Module.
    • Contains fully connected layers for input, hidden layers, and output.
    • Implements the forward propagation logic.
  3. Define Model Architecture:

    • Input layer: Matches the number of features in the dataset (e.g., 11 for wine quality).
    • Hidden layers: Use arbitrary neuron counts (e.g., 16 and 12).
    • Output layer: Matches the number of classes (e.g., wine quality classes, which are typically 6).
  4. Manual Seed for Reproducibility: Set a manual seed to ensure the model's weights and biases are initialized identically for reproducibility.

Code Implementation

123456789101112131415161718192021222324252627282930313233343536373839404142434445
# Step 1: Import Libraries import torch import torch.nn as nn import torch.nn.functional as F import pandas as pd # Step 2: Load the Dataset # Assuming the dataset file is named "winequality.csv" wine_df = pd.read_csv("winequality.csv") # Extract features and target features = wine_df.drop(columns=["quality"]).values target = wine_df["quality"].values # Step 3: Define the Model Class class WineQualityModel(nn.Module): def __init__(self, input_features, hidden1, hidden2, output_classes): super(WineQualityModel, self).__init__() # Define the layers self.fc1 = nn.Linear(input_features, hidden1) # Input to first hidden layer self.fc2 = nn.Linear(hidden1, hidden2) # First hidden to second hidden layer self.out = nn.Linear(hidden2, output_classes) # Second hidden to output layer def forward(self, x): # Pass data through layers with activation functions x = F.relu(self.fc1(x)) # First hidden layer with ReLU x = F.relu(self.fc2(x)) # Second hidden layer with ReLU x = self.out(x) # Output layer (no activation for raw scores) return x # Step 4: Define Model Parameters input_features = features.shape[1] # Number of features in the dataset hidden1 = 16 # Number of neurons in the first hidden layer hidden2 = 12 # Number of neurons in the second hidden layer output_classes = len(wine_df["quality"].unique()) # Number of unique classes in the target # Step 5: Initialize the Model # Set manual seed for reproducibility torch.manual_seed(42) # Create an instance of the model model = WineQualityModel(input_features, hidden1, hidden2, output_classes) # Display the model structure print(model)
copy

Explanation of Code:

  1. Model Initialization:

    • self.fc1, self.fc2, and self.out define fully connected layers.
    • nn.Linear connects input, hidden, and output layers.
  2. Forward Method:

    • Activates layers using the ReLU function for non-linearity.
    • Passes the input tensor sequentially through all layers.
    • Returns raw output scores, which can later be processed (e.g., with Softmax for probabilities).
  3. Model Parameters:

    • Input Features: Matches the number of columns in the feature matrix.
    • Hidden Layers: Arbitrarily chosen neuron counts (16 and 12).
    • Output Classes: Equals the number of unique wine quality labels.

Next Steps:

  • Prepare the dataset using PyTorch’s TensorDataset and DataLoader.
  • Split the data into training and testing sets.
  • Train the neural network on the wine quality data.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 1
We're sorry to hear that something went wrong. What happened?
some-alt