2023-05-13 12:55:04 +02:00
# numpy for loading dataset
2023-05-13 12:45:54 +02:00
import numpy as np
2023-05-13 12:55:04 +02:00
# pytorch for deep learning models
2023-05-13 12:45:54 +02:00
import torch
2023-05-13 13:33:48 +02:00
# nn like neural network
2023-05-13 12:45:54 +02:00
import torch . nn as nn
import torch . optim as optim
2023-05-13 13:33:48 +02:00
# Pima indians describes patient medical data and whether they had diabetes for last 5 years
2023-05-13 12:55:04 +02:00
# It is binary classification (they could either have diabetes 1 or not 0)
# load the file as a matrix of numbers,
2023-05-13 12:45:54 +02:00
dataset = np . loadtxt ( ' pima-indians-diabetes.csv ' , delimiter = ' , ' )
2023-05-13 13:26:38 +02:00
input_columns = 8
2023-05-13 12:55:04 +02:00
# split into input (X) -> in this case everything beside info whether patient had diabetes or not is input
2023-05-13 13:33:48 +02:00
# We are splitting data into two subsets by using NumPy slice operator : and choose first 8 columns using 0:8 slice
2023-05-13 13:26:38 +02:00
X = dataset [ : , 0 : input_columns ]
2023-05-13 12:55:04 +02:00
# and output (y) variables -> in this case we are only interested whether patient had diabetes or not as an output
# you can simplify that y = f(X)
2023-05-13 13:33:48 +02:00
# We are splitting the data by using slice operator : and choosing last column
2023-05-13 13:26:38 +02:00
y = dataset [ : , input_columns ]
2023-05-13 12:45:54 +02:00
2023-05-13 12:55:04 +02:00
# we need to convert this data to pytorch tensors
2023-05-13 13:33:48 +02:00
# Pytorch usually operates on 32-bit floating point and NumPy by default uses 64 bit floating point
2023-05-13 12:45:54 +02:00
X = torch . tensor ( X , dtype = torch . float32 )
2023-05-13 12:55:04 +02:00
# We can also correct the shape to fit what PyTorch would expect (here we are converting n vectors to n x 1 matrix)
# This simplifies handling matrix multiplication operations (which are the basis of deep learning models)
# reshape is converting the output variable y from a 1-dimensional NumPy array to a 2-dimensional PyTorch tensor with a shape of (n, 1), where n is the number of samples in the dataset.
2023-05-13 12:45:54 +02:00
y = torch . tensor ( y , dtype = torch . float32 ) . reshape ( - 1 , 1 )
# define the model
2023-05-13 13:26:38 +02:00
# this class is a subclass of nn.Module -> base class provided by PyTorch for building neural network models.
2023-05-13 12:45:54 +02:00
class PimaClassifier ( nn . Module ) :
def __init__ ( self ) :
super ( ) . __init__ ( )
2023-05-13 13:26:38 +02:00
# There are 3 (fully connected) layers in class, each with their activation function
# creates Linear layer, it maps input to a hidden layer of 12 neurons
2023-05-13 13:33:48 +02:00
# input features have a size of 8 (same number as number of features in pima indians diabetes dataset)
2023-05-13 13:26:38 +02:00
first_output_neurons = 12
self . hidden1 = nn . Linear ( input_columns , first_output_neurons )
# This creates ReLU (rectified linear unit) activation function applied after first hidden layer
self . act1 = nn . ReLU ( )
2023-05-13 13:33:48 +02:00
# This maps the output of first layer (which was 12 neurons) to new hidden layer of 8 neurons
2023-05-13 13:26:38 +02:00
second_output_neurons = 8
self . hidden2 = nn . Linear ( first_output_neurons , second_output_neurons )
# ReLU activation function applied after second hidden layer
2023-05-13 12:45:54 +02:00
self . act2 = nn . ReLU ( )
2023-05-13 13:26:38 +02:00
# We map output of second layer to a single output neuron -> which will represent the predicted
# probability of a sample having diabetes
self . output = nn . Linear ( second_output_neurons , 1 )
# sigmoid function forces output to be either 0 or 1
2023-05-13 12:45:54 +02:00
self . act_output = nn . Sigmoid ( )
2023-05-13 13:26:38 +02:00
# forward pass is computation of output based on input 'x'
2023-05-13 12:45:54 +02:00
def forward ( self , x ) :
2023-05-13 13:26:38 +02:00
# Applies first hidden layer (and then ReLU activation) to input x
2023-05-13 12:45:54 +02:00
x = self . act1 ( self . hidden1 ( x ) )
2023-05-13 13:26:38 +02:00
# Applies second hidden layer (and then ReLU activation) to input x
2023-05-13 12:45:54 +02:00
x = self . act2 ( self . hidden2 ( x ) )
2023-05-13 13:26:38 +02:00
# Applies output layer (and then Sigmoid activation) to input x
2023-05-13 12:45:54 +02:00
x = self . act_output ( self . output ( x ) )
2023-05-13 13:26:38 +02:00
# returns final output (0 or 1)
2023-05-13 12:45:54 +02:00
return x
2023-05-13 13:26:38 +02:00
# Create object from model class
2023-05-13 12:45:54 +02:00
model = PimaClassifier ( )
print ( model )
# train the model
2023-05-13 13:26:38 +02:00
# first we need to specify what is the goal of training
# we have input X and output y and we want the model to be as close to y as possible
# Since this is binary classification problem we will use "binary cross entropy" to measure the distance between
# our prediction and y
2023-05-13 12:45:54 +02:00
loss_fn = nn . BCELoss ( ) # binary cross entropy
2023-05-13 13:26:38 +02:00
# Optimizer adjust model weights to produce better output
# Its described as being able to tune itself to a lot of problems
# inputs are:
# parameters which it will optimize (from the model)
# and lr (learning rate) which is step size of each iteration
2023-05-13 12:45:54 +02:00
optimizer = optim . Adam ( model . parameters ( ) , lr = 0.001 )
2023-05-13 13:26:38 +02:00
# epoch is the entire training dataset passed to a model once
2023-05-13 12:45:54 +02:00
n_epochs = 100
2023-05-13 13:26:38 +02:00
# batch is one or more sample passed to model
# number of epochs and the size of a batch can be chosen experimentally by trial and error.
# a lot of epochs and big size of batch means more time and more memory consumption but more accurate results
2023-05-13 12:45:54 +02:00
batch_size = 10
2023-05-13 13:26:38 +02:00
# We split dataset into batches and pass batches one by one into a model to training loop
# after using all batches we finish one epoch and can start over again to refine the model
2023-05-13 13:33:48 +02:00
# we use two nested for loops for training, one is for epochs
2023-05-13 12:45:54 +02:00
for epoch in range ( n_epochs ) :
2023-05-13 13:26:38 +02:00
# and one for batches
2023-05-13 12:45:54 +02:00
for i in range ( 0 , len ( X ) , batch_size ) :
2023-05-13 13:26:38 +02:00
# Split X data into a batch with the size from batch_size
2023-05-13 12:45:54 +02:00
Xbatch = X [ i : i + batch_size ]
2023-05-13 13:26:38 +02:00
# run the model on the batch and return "batched" output
2023-05-13 12:45:54 +02:00
y_pred = model ( Xbatch )
2023-05-13 13:26:38 +02:00
# Split y data into a batch with the size from batch_size
2023-05-13 12:45:54 +02:00
ybatch = y [ i : i + batch_size ]
2023-05-13 13:26:38 +02:00
# Compare loss
2023-05-13 12:45:54 +02:00
loss = loss_fn ( y_pred , ybatch )
2023-05-13 13:26:38 +02:00
# optimize model
2023-05-13 12:45:54 +02:00
optimizer . zero_grad ( )
2023-05-13 13:33:48 +02:00
# calculate the inaccuracy
2023-05-13 12:45:54 +02:00
loss . backward ( )
2023-05-13 13:26:38 +02:00
# optimizer takes next step
2023-05-13 12:45:54 +02:00
optimizer . step ( )
2023-05-13 13:26:38 +02:00
# compute final accuracy
2023-05-13 12:45:54 +02:00
y_pred = model ( X )
accuracy = ( y_pred . round ( ) == y ) . float ( ) . mean ( )
print ( f " Accuracy { accuracy } " )
# make class predictions with the model
predictions = ( model ( X ) > 0.5 ) . int ( )
for i in range ( 5 ) :
print ( ' %s => %d (expected %d ) ' % ( X [ i ] . tolist ( ) , predictions [ i ] , y [ i ] ) )