• Hello, everybody! Today I am going to show how you how to convert my model from Pytorch to Pytorch Lightning. Pytorch Lightning is a light-weight deep learning framework built upon Pytorch. It removes a lot of boilerplate code (standard code that can be found in almost any deep learning pipeline) and adds in many functions that helps to interfere training at a specific position.

    Firstly, I import the libraries.

    pip install pytorch-lightning
    import pytorch_lightning as pl

    Pytorch LightningModule resembles nn.Module. Forward function can be defined in a pl class.

    # an nn class can be converted to a pl class by replacing nn with pl
    
    class NeuralNet(nn.Module): 
    # --> class NeuralNet(pl.LightningModule):
        def __init__(self, input_size, num_classes):
            super(NeuralNet, self).__init__()
            self.fc1 = nn.Linear(input_size, 50)
            self.fc2 = nn.Linear(50, num_classes)
    
    # --> specific functions belong to nn class should not be changed!
        def forward(self, x):
            out = self.fc1(x)
            out = torch.sigmoid(out)
            out = self.fc2(out)
            return out

    Pretrained models could be passed into the class through a parameter. Changes to the models such as transfer learning could be made outside.

    class FruitsClassification(pl.LightningModule):
      def __init__(self, model, learning_rate=0.01):
        super(FruitsClassification, self).__init__()
        self.model = model

    Conversion of the training loop requires positional matching of the hooks with the loop.

    For example, a training_step() usually consists of these lines.

    def training_step(self, batch, batch_idx):
            x, y = batch
            y_hat = self(x)
            loss = F.cross_entropy(y_hat, y)
            return loss

    Calculating backwards and updating weights no longer requires as they are automatically integrated under the hood. Declaration of cuda devices follow the same convention, thus can be omitted.

    print(f'Epoch {epoch+1}/{num_epochs}')
    print(f'Step {idx1+1}/{n_iters1}, train Loss = {epoch_loss:.2f},  train Acc = {epoch_acc:.2f}')
    print(f'Step {idx2+1}/{n_iters2}, val loss = {epoch_loss_val:.2f},  val acc = {epoch_acc_val:.2f}')

    Displaying loss and accuracy can be made through the callback functions belonging to the callback module.

    def validation_epoch_end(self, outputs):
        avg_val_loss = torch.tensor([x['val_loss'].item() for x in outputs]).mean()
        avg_val_acc = torch.tensor([x['val_acc'].item() for x in outputs]).mean()
        print(f'Epoch {self.current_epoch + 1} ' \
              f'Val Loss: {avg_val_loss:.3f}, Val Acc: {avg_val_acc:.2f}')
        self.val_loss.append(avg_val_loss.item())
        self.val_acc.append(avg_val_acc.item())
        if avg_val_acc.item() > self.best_acc:
          self.best_acc = avg_val_acc.item()

    It should be noted that Lightning considers a training loop as training and validation. Therefore, displaying metrics of pure training could be made right at the start of validation.

     def on_validation_epoch_start(self, trainer, pl_module):
        avg_train_loss = torch.tensor(pl_module.train_losses).mean()
        avg_train_acc = torch.tensor(pl_module.train_accs).mean()
        pl_module.train_loss.append(avg_train_loss.item())
        pl_module.train_acc.append(avg_train_acc.item())
        print(f'Epoch {pl_module.current_epoch + 1} ' \
              f'Train Loss: {avg_train_loss:.3f}, Train Acc: {avg_train_acc:.2f}')

    Single metrics values could be concatenated through an attribute in the lightning module. Epoch metric values could be displayed on the progress bar.

    class FruitsClassification(pl.LightningModule):
    
      def __init__(self, model, learning_rate=0.01):
        super(FruitsClassification, self).__init__()
        ...
        self.train_losses = list()
        self.train_accs = list()
        self.train_loss = list()
        self.train_acc = list()
        ...
    
      def training_step(self, batch, batch_idx):
        loss, acc = self._shared_eval_step(batch, batch_idx)
        self.train_losses.append(loss.item())
        self.train_accs.append(acc.item())
        metrics = {'loss': loss, 'train_acc': acc}
        pbar = {'train_loss': loss, 'train_acc': acc}
        self.log_dict(pbar, on_epoch=True, on_step=False, prog_bar=True, logger=True)
        return metrics

    The callback hooks could be written within the module class or separately for the sake of readability.

    from pytorch_lightning.callbacks import Callback
    class MyPrintingCallback(Callback):
    
      def __init__(self, cb_dir, test_dir):
        super().__init__()
        self.epoch_start = None
        self.start = None
        ...
    
    
      def on_train_start(self, trainer, pl_module):
        self.start = time.time()
    
      def on_train_epoch_start(self, trainer, pl_module):
        print('In training...')
        self.epoch_start = time.time()

    Accuracy could be calculated conveniently with a built-in function.

    from torchmetrics.functional import accuracy
    def _shared_eval_step(self, batch, batch_idx):
        x, y = batch
        logits = self.model(x)
        loss = self.criterion(logits, y)
        acc = accuracy(logits, y)
        return loss, acc

    It is very efficient to load a model either for resumed training or inference. The epoch would be continued from the last train. Specify the an already trained max_epochs would not initiate training.

    checkpoint_callback = ModelCheckpoint(
        monitor='val_acc',
        mode='max',
        every_n_train_steps=0,
        every_n_epochs=1,
        train_time_interval=None,
        save_on_train_epoch_end=True,
        save_top_k=1,
        dirpath='/content/drive/MyDrive/outputs',
        filename='resumed-sample-fruits-{epoch}-{val_acc:.2f}'                                             
    )

    It should be noted that the callback used for saving checkpoints has the same saved folder as in training. The new checkpoint file name should be different from the old one and the file would be updated.

    Metric loss and accuracy are automatically put up in Tensorboard. However, each pair of metrics either for train or validation does not come up in the same graph. Nonetheless, manual visualization could still be made through the saved parameters in the lightning module during the notebook session. It should be noted that loading those values for inference after the session requires them to be saved.

    def on_train_end(self, trainer, pl_module):
        self.end = time.time()
        duration = self.start - self.end
        print(f'Training completes in -----> {int(duration // 60)}m {int(duration % 60)}s')
        print(f'Best Validation Accuracy is {pl_module.best_acc:.3f}')
        torch.save({
                'train_loss': pl_module.train_loss,
                'train_acc': pl_module.train_acc,
                'val_loss': pl_module.val_loss,
                'val_acc': pl_module.val_acc,
                'best_acc':pl_module.best_acc,
                'targets': self.targets,
                'preds': self.preds,
                'absent_class': self.absent_class,
                'accdict': self.accdict,
                'corrects': self.corrects
                }, self.path)

    Bao Ca Ca

    HCM 27.02.22 5:22 p.m.

    GitHub Page: https://qbaocaca.github.io/fruits_clf_lightning/

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

  • Hello everybody! Today, I will show you an implementation of the binary search tree (BST) class which borrows the structure of a linked list but is a little bit different. The BST has two reference fields (left subtree and right subtree) instead of just only one. Though I have implemented a linked list class before, it has not quite come as an official post. Therefore, if you want to compare between the two, see it for yourself.

    Without further ado, let’s get on!

    struct node
    {
        int info;
        node *left;
        node *right;
    };
    
    class BST
    {
    private:
        node *root;
        void deepcopy(const BST &other);
    
    public:
        // node *search(int);
        // node *search(node *, int);
        BST();
        ~BST();
        BST(int);
        BST(const BST &other);
        BST &operator=(const BST &other);
        void insert(int);
        void insert(node *, int);
    };

    An important concept I have just discovered while implementing this was polymorphism. I remembered my teacher so long ago having said that using polymorphism in writing class was some sort of art so I have decided to study it.

    Polymorphism is the concept of having many forms. This means that many functions can have the same name but different numbers of parameters or different variable types. In this case, we are talking about compile time polymorphism or early binding. In other words, some conditions are bound before the program executes. Run time polymorphism, on the other hand, is bound only during program execution.

    void inorder(node *a)
    {
        if (a != NULL)
        {
            inorder(a->left);
            cout << a->data << " ";
            inorder(a->right);
        }
    }

    Recursion is another piece of knowledge I have found out during my implementation of the BST. What I have found out was that a class method cannot call on recursion on the elements of itself, instead has to be wrapped up in another method of the same name which refers to as ‘polymorphism’. This is what has prompted me to study ‘polymorphism’.

    void BST::inorder(node *t)
    {
        if (t != NULL)
        {
            this->inorder(t->left);
            cout << t->info << " ";
            this->inorder(t->right);
        }
    }
    
    void BST::inorder()
    {
        this->inorder(this->root);
    }

    Like the function above, with polymorphism, I would have two methods. The first method takes in a tree and print out its inorder traversal. The second method wraps the first method by calling it with the element of the tree class instance as an argument. Therefore, an instance who calls this seconds would obtain the inorder traversal of itself.

    Other methods follow the same convention.

    Bao Ca Ca

    HCM 02.05.22 8:50 p.m.

    If you want the code, please refer to them as follows:

    bst.h

    bst_class.cpp

    bst_main.cpp

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

  • Image source: https://zhuanlan.zhihu.com/p/355342722

    Hello everybody! Today, I would like to show you a quick implementation of a string class.

    A string is an array of characters. So, we initialize it with an array of char type and a length.

    char *content;
    int len;

    Next, we initialize a NULL string with a length of zero in the default constructor and an input of an std::string in the parameterized constructor.

    STRING::STRING()
    {
        this->content = NULL;
        this->len = 0;
    }
    
    STRING::STRING(std::string str)
    {
        _allocate(this->content, str.size() + 1);
        for (int i = 0; i < str.size(); i++)
        {
            this->content[i] = str[i];
        }
        this->len = str.size();
    }

    Next, we come to the copy constructor and copy assignment. The copy constructor initializes an object by another object. Rather than pass by reference (two objects pointing to the same array), the copy constructor and copy assignment creates a newly distinct object with the help of the deepcopy function which prevents the alteration of one object affecting another. The copy assignment is, in fact, an equal sign overloaded. Just like when assigning one variable to another, and now one string is assigned to another.

    STRING::STRING(const STRING &other)
    {
        if (this->content != NULL)
            delete[] this->content;
        _allocate(this->content, other.len + 1);
        this->len = other.len;
        this->deepcopy(other);
    }
    
    STRING &STRING::operator=(const STRING &other)
    {
        if (this == &other)
            return *this;
        if (this->content != NULL)
            delete[] this->content;
        _allocate(this->content, other.len + 1);
        this->len = other.len;
        this->deepcopy(other);
        return *this;
    }

    In case a string instance already has some content, make sure you delete it before copy.

    void STRING::input()
    {
        std::string str;
        getline(std::cin, str);
        if (this->content != NULL)
            delete[] this->content;
        _allocate(this->content, str.size() + 1);
        for (int i = 0; i < str.size(); i++)
        {
            this->content[i] = str[i];
        }
        this->len = str.size();
    }
    
    void STRING::output()
    {
        std::string str;
        for (int i = 0; i < this->len; i++)
        {
            str.push_back(this->content[i]);
        }
        cout << str;
    }

    The *input method borrows an std::string, copies the content of the input string to itself using the push_back method letter by letter. Similarly, the output method borrows an std::string, copies the content of itself to the std::string, and prints out the output.

    *Note: the set of length equal to str.size() shouldn’t be forgotten, or else other methods won’t work.

    std::istream &operator>>(std::istream &in, STRING &a)
    {
        std::string str;
        getline(in, str);
        if (a.getWholeContent() != NULL)
            a.deleteContent();
        a.allocateContent(str.size() + 1);
        for (int i = 0; i < str.size(); i++)
        {
            a.setContent(i, str[i]);
        }
        a.setLen(str.size());
        return in;
    }
    
    std::ostream &operator<<(std::ostream &out, STRING a)
    {
        std::string str;
        for (int i = 0; i < a.getLen(); i++)
        {
            str.push_back(a.getContent(i));
        }
        out << str;
        return out;
    }

    The cin and cout operator takes in and outputs a string just like the input and output methods work.

    void STRING::RemoveExtraSpaces()
    {
        this->removeBlankHead();
        this->removeBlankTail();
        for (int i = 0; i < this->len; i++)
        {
            if (this->content[i] == ' ' && this->content[i + 1] == ' ')
            {
                for (int j = i; j < this->len; j++)
                {
                    this->content[j] = this->content[j + 1];
                }
                this->len--;
                i--; // update i!
            }
        }
    }

    There is an extra method provided which removes extra spaces in a string. This includes no blank spaces at the beginning and the end. Only one space is allowed in between words.

    Bao Ca Ca

    HCM 27.04.22 11:34 a.m.

    If you want the code, please refer to them as follows.

    String.h

    string_class.cpp

    string_main.cpp

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

  • The concept of matrix and multidimensional array had always been an intriguing topic for me when I was in programming classes. Since computer memory isn’t organized in tabular form, there should be a way to represent it. Today, I am going to show you how to implement a matrix class with a component of an array. It will simply has some basic operations of matrix such as addition, subtraction, and multiplication.

    Firstly, I will start off with identifying the attributes of the matrix class. It simply consists of a 1D array, a number of rows, and a number of columns.

    Array *A;
    int rows = 0, cols = 0;
    
    void deepcopy(const Matrix &other);

    A default constructor initializing a matrix consists of one row and one column stores the number zero.

    Matrix::Matrix()
    {
        allocate_(this->A, 1, 1);
        this->rows = this->cols = 1;
        this->A[0].setElement(0, 0);
    }

    setElement is a setter from my Array class. It sets a value at an index in an array.

    void Array::setElement(int index, int value)
    {
        this->A[index] = value;
    }

    Next, I define the parameterized constructor taking in the number of rows and columns of the matrix a user desires.

    Matrix::Matrix(int x, int y)
    {
        allocate_(this->A, x, y);
        this->rows = x;
        this->cols = y;
        for (int i = 0; i < this->rows; i++)
        {
            for (int j = 0; j < this->cols; j++)
            {
                this->A[i].setElement(j, 0);
            }
        }
    }

    This method also initializes a matrix with all zeros.

    Now, I would like to input values for the matrix and display it on the screen.

    void Matrix::input()
    {
        for (int i = 0; i < this->rows; i++)
        {
            this->A[i].set_na(this->cols);
            cin >> A[i];
        }
    }
    
    void Matrix::output()
    {
        for (int i = 0; i < this->rows; i++)
        {
            for (int j = 0; j < this->cols; j++)
            {
                cout << this->A[i].getElement(j) << " ";
            }
            cout << endl;
        }
    }

    I could write methods like this and calling them. However, overloading operators seems more professional.

    istream &operator>>(istream &in, Matrix &a)
    {
        for (int i = 0; i < a.view_rows(); i++)
        {
            a.A[i].set_na(a.view_cols());
            in >> a.A[i];
        }
        return in;
    }
    
    ostream &operator<<(ostream &out, Matrix a)
    {
        for (int i = 0; i < a.view_rows(); i++)
        {
            for (int j = 0; j < a.view_cols(); j++)
            {
                out << a.A[i].getElement(j) << " ";
            }
            cout << endl;
        }
        return out;
    }

    Last but not least, I overloaded the addition and subtraction operators.

    Matrix operator+(Matrix m1, Matrix m2)
    {
        Matrix a(m1.view_rows(), m1.view_cols());
        if (m1.view_rows() != m2.view_rows() || m1.view_cols() != m2.view_cols())
        {
            cout << "Mismatched dimensions!" << endl;
        }
        else
        {
            for (int i = 0; i < m1.view_rows(); i++)
            {
                for (int j = 0; j < m1.view_cols(); j++)
                {
                    int temp = m1.getElement(i, j) + m2.getElement(i, j);
                    a.setElement(i, j, temp);
                }
            }
        }
        return a;
    }

    Bao Ca Ca

    HCM 17.04.22 11:40 p.m.

    matrix.h

    matrix_class.cpp

    matrix_main.cpp

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

  • A parameterized constructor initialized an array with a number of elements.

    Array::Array(int num_elements)
    {
        allocate(this->A, num_elements);
        this->na = 0;
        this->capacity_a = num_elements;
    }

    Next, I’ll talk about how to input an array. Elements are inserted one by one until the array is full. Then, a new array of a bigger size is created with an extra space for the newly inserted element. The process repeats every time a element is inserted.

    void Array::insert(int x)
    {
        if (this->na == 0)
        {
            allocate(this->A, 1);
            this->A[0] = x;
            this->na++;
        }
        else if (this->na == this->capacity_a)
        {
            this->capacity_a = 2 * this->na + 1;
            int *B;
            allocate(B, this->capacity_a);
            for (int i = 0; i < this->na; i++)
            {
                B[i] = this->A[i];
            }
            B[this->na] = x;
            delete_(this->A);
            allocate(this->A, this->capacity_a);
            for (int i = 0; i <= this->na; i++)
            {
                this->A[i] = B[i];
            }
            this->na++;
            delete_(B);
        }
        else
        {
            this->A[this->na] = x;
            this->na++;
        }
    }

    Next, I will talk about the copy and assignment constructor. The copy constructor initializes an array based on an existing array. The deep copy function creates a separate array preventing the data from being altered.

    void Array::deepcopy(const Array &a)
    {
        this->na = a.na;
        for (int i = 0; i < this->na; i++)
        {
            this->A[i] = a.A[i];
        }
    }
    
    Array::Array(const Array &other)
    {
        allocate(this->A, other.na);
        this->deepcopy(other);
    }

    Similarly, a copy assignment creates a separate copy of an array but through an assignment operator.

    Array &Array::operator=(const Array &other)
    {
        delete_(this->A);
        allocate(this->A, other.na);
        this->deepcopy(other);
        return *this;
    }

    Next, I will talk about the destructor. The destructor is automatically called to delete an object class instance the program ends. However, when many object classes are still in place, this could pose a problem memory spaces and running time execution.

    Array c;
    for (int i = 0; i < 100000000; i++)
    {
        c = a;
    }

    Array c is initialized by array a a hundred million times. The destructor won’t be called until the program ends. While in the for loop, a lot of memory space is occupied creates a memory space buffer overflow.

    With the presence of a destructor, similar version of arrays get deleted every time it is assigned, thus only the last one is still kept.

    Next, I will come to explain operator overloading. With this technique, an object class instance can use the standard operators as though they are integer or float.

    int a = 5, b = 6;
    cout << "a=" << a << " " << "b=" << b << endl;
    int c = a + b;
    cout << a;
    
    Array c, d, e;
    cin >> c >> d;
    cout << "array c= " << c << endl;
    cout << "array d= " << d << endl;
    e = c + d;
    cout << "array e= " << e << endl;
    friend istream &operator>>(istream &in, Array &a);
    friend ostream &operator<<(ostream &out, Array a);

    A further point of interest is that the input and output operator can ‘make friends’ to the class structure so that they could be written outside.

    Next, I will overload the arithmetic operators. The addition operator, for example, is instead used for a concatenating method of two arrays.

    Array Array::operator+(Array other)
    {
        Array a;
        a.na = this->na + other.na;
        for (int i = 0; i < a.na; i++)
        {
            if (i < this->na)
            {
                a.A[i] = this->A[i];
            }
            else
            {
                a.A[i] = other.A[i - this->na];
            }
        }
        return a;
    }

    Bao Ca Ca

    HCM 19.03.22 9:41 p.m.

    If you want the code, please check out my Github. Thanks!

    array.h

    array_class.cpp

    array_main.cpp

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

  • Image retrieved from https://pediaa.com/what-is-the-difference-between-1d-and-2d-array/

    Object-oriented programming (OOP) is an important knowledge taught in schools and programming classes. It is a concept that relies on the creation of classes and objects which helps coding more efficient with reusable code blocks of well-defined functions. Today, I will show you how to implement a simple 1D array class. Throughout the post, important OOP terminologies and concepts will be discussed for the sake of better understanding.

    Firstly, I will talk about the four basic properties of OOP, namely encapsulation, inheritance, polymorphism, and abstraction. Encapsulation is a property which helps to hide data implementation with three levels of protection in descending order, namely, private, protected, and public. Elements within the public field can be accessed from outside the class. While elements within private field cannot. This prevents data from being altered. For example, a developer accidentally assigns a gilberish value to his pre-defined array. Altering data, however, can be achieved through the accessor methods, which are commonly known as setters and getters.

    int view_na();
    void set_na(int);
    int getElement(int index);
    void setElement(int index, int value);
    

    Before continuing, I would like to set up the coding files for the sake of readability, debugging, and enhancement. I divide my class implementation into three files: header (.h extension), class definition, and main. The header file contains only the class prototypes and some helper functions. The class definition file defines all the prototypes declared in the header file. The main file is used for testing.

    Next, I will talk about two important OOP concepts, namely, attributes and methods. Attributes are variables declared within a class. Likewise, methods are functions declared within a class. “Within” means belonging to. This means that they must be declared inside a class. Methods, however, can be declared outside a class using a scope resolution operator (::, two colons). This is how the method definitions in the class definition file are connected to their prototypes in the header file.

    Now, I will talk about the benefit of dynamic allocation of array. It is said that dynamic allocation of array is better than static allocation of array because it uses the memory more efficiently. By utilizing vacant discontinuous memory spaces and linking them by address than occupying a chuck of continuous spaces, dynamic array will not waste memory if they are not used fully. This is why I have used it as a main class attributes. The other attributes are the maximum number of elements of the array and the number of elements actually persists in the array. A method I always have is deepcopy, which is going to be used for the copy constructor and copy assignment.

    Regarding deepcopy, it is a method that creates a separate copy of an array, which is different with shallow copy that only points to the address of the original array. This also prevents data from being mistakenly altered.

    I am going to talk about the default constructor. The default constructor is an initialization method of a class. It is automatically called when a class instance is created whether or not a developer defines it. Most of the time, I define it. Because without definition, it won’t work in practice. For example, a dynamic array works only if it is initialized with a maximum number of elements.

    void allocate(int *&a, int size)
    {
        a = new int[size];
    }
    
    Array::Array()
    {
        allocate(this->A, 1);
        this->na = 0;
        this->capacity_a = 1;
    }

    In this example, I have a helper function which initializes a dynamic array with a size.

    Bao Ca Ca

    HCM 18.03.22 8:59 p.m.

    If you want the code, please check out my Github. Thanks!

    array.h

    array_class.cpp

    array_main.cpp

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

  • Hello everybody! Today, we will continue with what we left off in the previous blog.

    I first talk about the Tensorboard. Tensorboard is a visualization toolkit of TensorFlow, which is also a machine learning and deep learning framework. Tensorboard can be used for displaying the images in the dataset, drawing loss and accuracy graphs, analyzing the components of a neural network.

    A useful feature of Tensorboard that I learned from Aladdin Persson is hyper-parameter search. It is believed that the success of a machine learning model largely depends on the matching of the batch size and learning rate, since they affect the update of weights, and specifically the gradients of the loss function with respect to those weights. Therefore, we should really have to find a good match.

    What Aladdin Persson taught me was that I should come up with some random batch sizes and learning rates, run a couple of epochs through each pair, see whichever has the most accuracy and lowest loss should be the perfect match.

    ==> batch_size=3, learning_rate=0.1
    Epoch 1/3, Loss = 38.65, Acc = 0.38
    Epoch 2/3, Loss = 30.08, Acc = 0.55
    Epoch 3/3, Loss = 23.80, Acc = 0.69
    
    ==> batch_size=3, learning_rate=0.01
    Epoch 1/3, Loss = 3.81, Acc = 0.35
    Epoch 2/3, Loss = 1.91, Acc = 0.66
    Epoch 3/3, Loss = 2.23, Acc = 0.69
    
    ==> batch_size=3, learning_rate=0.001
    Epoch 1/3, Loss = 1.61, Acc = 0.31
    Epoch 2/3, Loss = 0.80, Acc = 0.66
    Epoch 3/3, Loss = 0.58, Acc = 0.81

    For example, it can be inferred that small batch size matches better with small learning rate. Because they produced more reasonable loss (which should be as close as zero) and higher accuracy. However, this approach is heuristic-based. Aladdin Persson suggested there should be a more scientific way of doing it.

    Let’s talk about the model.

    It is believed that the deeper the model the better performance. However, in practice, this is not entirely true. Since the model gets deeper, the number of parameter increases, hence its complexity. This means that the model is able to learn more complex function; however, with a fixed size of dataset, it should be able to ‘memorize’ the images one by one. In other words, overfitting.

    An important point my lecturer at university always reminds me is that I should not train a deep neural network from scratch. It is because deep learning model requires an enormously large amount of dataset and very strong computational power which should take days or weeks of training. That is why I have chosen to use a pretrained model and on top of that a technique called *transfer learning or fine-tuning to help with the training.

    num_ftrs = model.classifier[6].in_features
    model.classifier[6] = nn.Linear(num_ftrs, 5)

    Speaking of transfer learning, vgg16 was said to be trained on the ImageNet that has 1000 classes. But I have only got 5 classes in my dataset, so I am going to modify the number of out features in the last linear layer of the classifier to 5. For faster training, there is technique called parameter freezing that could freeze all the parameters of the convoluted layers and only trains the classifier (or the fully connected one) which saves a lot of time and increases the accuracy.

    *transfer learning or fine-tuning: a technique for which training is based on the modification of the very last layer. All the weights of the upper layers were provided by the researchers who had probably trained the model on some very large datasets (for example, the ImageNet) which should be very efficient for use.

    ==> Saving new best
    Epoch 1/25
    Step 34/34, train Loss = 1.84,  train Acc = 0.29
    Step 20/20, val loss = 1.58,  val acc = 0.25
    Time spent for this epoch -----> 0m 32s
    
    ==> Saving new best
    Epoch 2/25
    Step 34/34, train Loss = 0.91,  train Acc = 0.63
    Step 20/20, val loss = 1.53,  val acc = 0.43
    Time spent for this epoch -----> 0m 13s
    
    ==> Validation accuracy did not improve.
    Epoch 3/25
    Step 34/34, train Loss = 0.61,  train Acc = 0.82
    Step 20/20, val loss = 1.67,  val acc = 0.27
    Time spent for this epoch -----> 0m 8s

    Now, let’s talk about two problems that might be encountered during training.

    Most of the time, training a deep learning model even with transfer learning and parameter freezing takes up time and exhaust the GPU power. In that case, I might have to start the process all over again which is something I never wanted. Therefore, it is advised to train with checkpoint so that I can continue training at a later time. (Also, to put my computer to rest!)

    Secondly, if I want to load a model whether to continue training or for inference, I put the model to GPU before calling loss and optimization because my model was last trained on the GPU. It’s probably best to send the model to the GPU once again after the model is loaded.

    Let’s talk about loss and accuracy. Here, I visualize them manually or with Tensorboard. With Tensorboard, it is very convenient for me to track the values by dragging the cursor across the graph, or smoothen the graph for a better trend. However, when Tensorboard does not always work, a manual function is the best option.

    Figure 1: Tensorboard results
    Figure 2: manual results

    Overall, there is a huge difference between the values of train and validation. The loss of train is decreasing and the accuracy is increasing. The loss of validation, on the other hand, saw an increase in the general trend. While its accuracy rises slightly in the first 10 epochs, remain almost stable afterwards.

    Test Acc
    Got 11/30 correct samples over 36.67%
    Accuracy of timmy_xu: 25.00%
    Accuracy of corbyn_besson: 50.00%
    Accuracy of keita_machida: 0.00%
    Accuracy of wang_kai: 60.00%
    Accuracy of chau_minh_chi: 60.00%

    In general, Wang Kai and Corbyn are best recognized by the model. They both got 4 correct predictions and only 1 mistaken identity. Timmy Xu and Chau Minh Chi ranked the second with 3 times predicted correctly. In contrast, Keita Machida confused the model the most, getting no correct predictions for himself and mostly be recognized as others.

    Bao Ca Ca

    HCM 14.02.22 05:19 p.m.

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

  • Hello everybody! Today, I will show you how to train a full deep learning pipeline on image classification using Pytorch. For somebody who didn’t know Pytorch, it is a machine learning and deep learning framework similar to Keras or TensorFlow. It is a very fun and cool framework to work with, especially on understanding the structure of a neural network.

    On this assignment, I create a custom dataset of 5 male models and conduct a full training pipeline using Pytorch. I use a pretrained model, transfer learning, and do some hyper-parameter search to help increase the accuracy.

    I first import the libraries.

    import torch
    import torch.nn as nn
    import torchvision.datasets as datasets
    import torchvision.transforms as transforms
    from torch.utils.data import DataLoader, Dataset
    from torch.utils.tensorboard import SummaryWriter
    import torchvision
    import torch.optim as optim
    from torchvision import models
    
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import os
    import time
    import math
    import copy
    from PIL import Image

    These libraries are commonly seen in a usual pytorch training pipeline. They support dataset creation, data augmentation, visualization and many more!

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(device)

    Next, I set the device for training. Here, I set the GPU for faster training. If you don’t have GPU support on your local machine (like me!), I suggest using Google Colab. It’s a free *notebook application developed by Google Research. It provides GPU support *at all times and implements most common libraries ready for use. So, it’s very efficient!

    *the thing I like about notebook application is that the output is displayed after each cell. The values of variables are also kept. There is no need for re-execution that takes time and resources like using a local machine.

    *however, there is a limit on daily usage. Google Colab will inform you when the limit is reached. This is available on the free version only.

    class BoysDataset(Dataset):
    
        def __init__(self, csv_file, root_dir, transform=None):
            self.annotations = pd.read_csv(csv_file)
            self.root_dir = root_dir
            self.transform = transform
    
        def __len__(self):
            return len(self.annotations)
    
        def __getitem__ (self, index):
    
            image = self.annotations.iloc[index, 0] 
            temp = image.split('.')
            folder_name = temp[0]
            folder_name = folder_name[:-3]                # extract the class_name from image_name
            root_directory = os.path.join(self.root_dir, folder_name)
    
            image_path = os.path.join(root_directory, self.annotations.iloc[index, 0])
            image = Image.open(image_path).convert('RGB') 
    # IMPORTANT! A usual image has an extra 'alpha' channel.
    # image imported using PIL alr a PIL image, otherwise
    # you'd have to set them in transforms!
            y_label = torch.tensor(self.annotations.iloc[index, 1])
    
            if self.transform:
                image = self.transform(image)
    
            return (image, y_label)

    Next, I write a custom dataset to import the data in.

    One way to import the images is to import them directly from drive through the torchvision.datasets.ImageFolder. But here, I imported them through a csv file with the image name and its label because I commonly seen people doing it on Kaggle. Anyway, it’s a good practice and I can also be more flexible with future datasets.

    train_dataset = BoysDataset(csv_file = train_csv_file, root_dir = train_dir, transform = trans1)
    
    val_dataset = BoysDataset(csv_file = val_csv_file, root_dir = val_dir, transform = trans2)

    Before calling the dataset, I do some data augmentation. Firstly, to fit the dataset with the model. Most models require images to be of size 224×224. Secondly, to reduce overfitting. Transformation, in other words, ‘by adding slightly modified copies of existing data’, prevents the model from memorizing the data which performs well on the training set but much worse on the testing set.

    trans1 = transforms.Compose([
                                 transforms.Resize((224, 224)),
                                 transforms.RandomHorizontalFlip(p=0.5),
                                 transforms.RandomAdjustSharpness(sharpness_factor=2),
                                 transforms.ToTensor(),
                                 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])
    
    trans2 = transforms.Compose([
                                 transforms.Resize((224, 224)),
                                 transforms.RandomPosterize(bits=2),
                                 transforms.RandomAutocontrast(),
                                 transforms.ToTensor(),
                                 transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ])

    Some points to make. Firstly, the model should require PILImage. There was an occasion when I misspelled the syntax of from torchvision.transforms import transforms, an error occurred saying that the images should be in PIL format to be used in the model. However, when I typed the syntax correctly, everything worked.

    Secondly, I have only chosen very random transformations. There should be a more scientific and heuristic way of doing it. However, Resize() and ToTensor() should be a must because the model requires so.

    Thirdly, mean [0.485, 0.456, 0.406] and standard deviation [0.229, 0.224, 0.225] of normalization are the values people figured out from training the *ImageNet dataset. My teacher said it could be used for a basic and standard image classification task like mine.

    *ImageNet: a dataset consists of 14 millions of images of 1000 different classes of animals and objects.

    val_size = int(len(val_dataset) * 0.6)
    test_size = len(val_dataset) - val_size
    val_dataset, test_dataset = torch.utils.data.random_split(dataset=val_dataset, lengths=[val_size, test_size])

    Next, I split the dataset into three sub-portions (train, validation, and test) because it is another recommended way of reducing overfitting. By using torch.utils.data.random_split, I find it much faster and more convenient to split the data than manually split it myself.

    With regard to the different types of dataset, from my readings, I found that the validation set provides an evaluation of the model after the train set was trained. It is seen within the training phase. The test dataset, on the other hand, is used for checking the model performance only after finished training.

    After finished loading the data, I now come to visualization. Visualization is said to give the a machine learning expert a better context of the data, thus helping him deduce some algorithms or methods to work with. When I started studying image classification, I have always wanted to see how the images in different classes are different. Or just simply to be able to display an image in a notebook feels professional. Anyways, I have found two ways of making visualization. One way is to load a single image via the image path and use either matplotlib, opencv, or PIL to show them. Another way is to load the images in batch and visualize all of them at once.

    Below is how the images are loaded in batch. There are no spaces in between. Titles only look good when there are only few of them. I wasn’t able to fit a title on each image nicely for this method.

    It is clearly shown from the figure that one batch has transforms while the other does not.

    Now, I come to explain the DataLoader mechanism. Normally, we would iterate over all samples of the dataset in an epoch. This doesn’t cause any problem if our dataset is small and doesn’t have many features. However, with images, it’s incredibly a lot of work for the computer to go over as many pixels as the image height and width have, not to mention the channels and the number of thousands an image dataset usually has. Therefore, this is where the Pytorch DataLoader comes in handy. It helps divide the dataset in small batches efficient for training. The user can track the model performance after each batch instead of having to wait till all samples needed to be gone through.

    dataiter = iter(train_loader)
    first_batch = dataiter.next() # without this line, '_SingleProcessDataLoaderIter' object is not subscriptable
    images, labels = first_batch
    print(images.shape, labels.shape)
    # output
    torch.Size([4, 3, 224, 224]) torch.Size([4])
    # (batch_size, no_of_channels, image_height, image_width)
    #  no_of_channels = 3 --> colored image i.e: 'RGB'
    #  no_of_channels = 1 --> gray-scaled image

    An iteration of the DataLoader is a batch of images with a batch size. An image also goes with its label. That’s why I have torch.Size([4]) for the labels of 4 images. Also, both images and labels should be in tensor type because the model requires so.

    Let’s look at a similar snippet of code but with the train dataset.

    first_data = train_dataset[0] # gets one example of the training set
    image, label = first_data
    print(image.shape, label) # label doesn't have shape because it is an integer! # well, should be a tensor!
    image = image.unsqueeze(0)
    print(image.shape)
    torch.Size([3, 224, 224]) tensor(0)
    torch.Size([1, 3, 224, 224])

    Calling iter() and next() on the train dataset is not possible because they belong to the DataLoader mechanism. Therefore, when I want to feed an image to a model, I would have to unsqueeze it to get the extra batch_size dimension.

    Now, let’s have a look at a model training loop.

    n_iters = math.ceil(len(train_dataset) / batch_size)
    for epoch in range(num_epochs):
      for idx, (images, labels) in enumerate(train_loader):
        print(f'Epoch {epoch+1}/{num_epochs}, step {idx+1}/{n_iters}', images.shape, labels.shape)
      print("")
    # output
    Epoch 1/2, step 1/4 torch.Size([30, 3, 224, 224]) torch.Size([30])
    Epoch 1/2, step 2/4 torch.Size([30, 3, 224, 224]) torch.Size([30])
    Epoch 1/2, step 3/4 torch.Size([30, 3, 224, 224]) torch.Size([30])
    Epoch 1/2, step 4/4 torch.Size([9, 3, 224, 224]) torch.Size([9])
    
    Epoch 2/2, step 1/4 torch.Size([30, 3, 224, 224]) torch.Size([30])
    Epoch 2/2, step 2/4 torch.Size([30, 3, 224, 224]) torch.Size([30])
    Epoch 2/2, step 3/4 torch.Size([30, 3, 224, 224]) torch.Size([30])
    Epoch 2/2, step 4/4 torch.Size([9, 3, 224, 224]) torch.Size([9])

    There is a batch size 30 and dataset size 99. This will create 4 iterations per epoch, thus results in only 9 examples left in the last iteration.

    Bao Ca Ca

    HCM 13.02.22 3:32 p.m.

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

    ¶¶¶¶¶

Tạo trang web của bạn, miễn phí trên WordPress.com.Tạo trang web của bạn.
Bắt đầu miễn phí