<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by mor40 on Medium]]></title>
        <description><![CDATA[Stories by mor40 on Medium]]></description>
        <link>https://medium.com/@mor40?source=rss-669b53f21044------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gCiMlUdY99f2hu-2_A6PzQ.jpeg</url>
            <title>Stories by mor40 on Medium</title>
            <link>https://medium.com/@mor40?source=rss-669b53f21044------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:13:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mor40/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Quantization of custom PyTorch model made easy]]></title>
            <link>https://medium.com/@mor40/quantization-of-custom-pytorch-model-made-easy-3a9521571efa?source=rss-669b53f21044------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a9521571efa</guid>
            <category><![CDATA[quantization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[model-quantization]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[mor40]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 18:05:42 GMT</pubDate>
            <atom:updated>2023-09-05T12:07:18.186Z</atom:updated>
            <content:encoded><![CDATA[<p>Pytorch has had up until recently only one way of doing qunatization and that is called “eager mode qunatization”, which involved a lot of steps and challenges you had to go through to quantize your model and often produced weird errors, that were hard to resolve. That is why PyTorch has a new form of qunatization called “fx-graph-mode-qunatization”, which is much easier to work with. From Pytorch themselfs have described the downsides of eager mode qunatization in this article here: <a href="https://pytorch.org/tutorials/prototype/fx_graph_mode_ptq_static.html#motivation-of-fx-graph-mode-quantization">https://pytorch.org/tutorials/prototype/fx_graph_mode_ptq_static.html#motivation-of-fx-graph-mode-quantization</a> and have explained the theory behind, why one is different from the other and what are the advantages of the new method for quantization, so if you are interested in the theory behind quantization in pytorch, you can check out also this page: <a href="https://pytorch.org/docs/stable/quantization.html">https://pytorch.org/docs/stable/quantization.html</a>, but in this tutorial I will focus more on the practical side of it and show you how easy it is and what gains we can make for our model. The notebook for this tutorial you can find here: <a href="https://colab.research.google.com/drive/1TxShumEnZ46z5m4PndBwidEgHh7RORv3?usp=sharing">https://colab.research.google.com/drive/1TxShumEnZ46z5m4PndBwidEgHh7RORv3?usp=sharing</a></p><p>I will be using CIFAR 10 and a custom AlexNet model that I have modified for efficiency, so lets’s first load the data. <strong>Make sure that the device is set to cpu because cuda is still not supported </strong>and upgrade PyTroch to the newest version possible.</p><pre>import os<br>import cv2<br>import time<br>import torch<br>import numpy as np<br>import torchvision<br>from PIL import Image<br>import torch.nn as nn<br>import matplotlib.pyplot as plt<br>from torchvision import transforms<br>from torchvision import datasets, models, transforms<br><br>device = &quot;cpu&quot;<br><br>print(device)<br>transform = transforms.Compose([<br>    transforms.Resize(224),<br>    transforms.ToTensor(),<br>    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])<br>    ])<br><br>batch_size = 8<br><br>trainset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=True,<br>                                        download=True, transform=transform)<br><br>testset = torchvision.datasets.CIFAR10(root=&#39;./data&#39;, train=False,<br>                                       download=True, transform=transform)<br><br>trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,<br>                                          shuffle=True, num_workers=2)<br><br>testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,<br>                                         shuffle=False, num_workers=2)<br><br>def print_model_size(mdl):<br>    torch.save(mdl.state_dict(), &quot;tmp.pt&quot;)<br>    print(&quot;%.2f MB&quot; %(os.path.getsize(&quot;tmp.pt&quot;)/1e6))<br>    os.remove(&#39;tmp.pt&#39;)</pre><p>And the model (feel free to use any model, it is not relevant):</p><pre>from torch.nn import init<br>class mAlexNet(nn.Module):<br>    def __init__(self, num_classes=2):<br>        super().__init__()<br>        self.input_channel = 3<br>        self.num_output = num_classes<br>        <br>        self.layer1 = nn.Sequential(<br>            nn.Conv2d(in_channels=self.input_channel, out_channels= 16, kernel_size= 11, stride= 4),<br>            nn.ReLU(inplace=True),<br>            nn.MaxPool2d(kernel_size=3, stride=2)<br>        )<br>        init.xavier_uniform_(self.layer1[0].weight,gain= nn.init.calculate_gain(&#39;conv2d&#39;))<br><br>        self.layer2 = nn.Sequential(<br>            nn.Conv2d(in_channels= 16, out_channels= 20, kernel_size= 5, stride= 1),<br>            nn.ReLU(inplace=True),<br>            nn.MaxPool2d(kernel_size=3, stride=2)<br>        )<br>        init.xavier_uniform_(self.layer2[0].weight,gain= nn.init.calculate_gain(&#39;conv2d&#39;))<br><br>        self.layer3 = nn.Sequential(<br>            nn.Conv2d(in_channels= 20, out_channels= 30, kernel_size= 3, stride= 1),<br>            nn.ReLU(inplace=True),<br>            nn.MaxPool2d(kernel_size=3, stride=2)<br>        )<br>        init.xavier_uniform_(self.layer3[0].weight,gain= nn.init.calculate_gain(&#39;conv2d&#39;))<br>       <br><br>        self.layer4 = nn.Sequential(<br>            nn.Linear(30*3*3, out_features=48),<br>            nn.ReLU(inplace=True)<br>        )<br>        init.kaiming_normal_(self.layer4[0].weight, mode=&#39;fan_in&#39;, nonlinearity=&#39;relu&#39;)<br><br>        self.layer5 = nn.Sequential(<br>            nn.Linear(in_features=48, out_features=self.num_output)<br>        )<br>        init.kaiming_normal_(self.layer5[0].weight, mode=&#39;fan_in&#39;, nonlinearity=&#39;relu&#39;)<br><br><br>    def forward(self, x):<br>        x = self.layer1(x)<br>        x = self.layer2(x)<br>        x = self.layer3(x)<br>        <br>        # Squeezes or flattens the image, but keeps the batch dimension<br>        x = x.reshape(x.size(0), -1)<br>        x = self.layer4(x)<br>        logits= self.layer5(x)<br>        return logits<br><br>model = mAlexNet(num_classes= 10).to(device)</pre><p>Now let’s do a quick training loop with the basic float-precission model to get a baseline:</p><pre>import torch.optim as optim <br><br>def train_model(model):<br>  criterion =  nn.CrossEntropyLoss()<br>  optimizer = optim.SGD(model.parameters(), lr=0.001, momentum = 0.9)<br><br>  for epoch in range(2):<br>    running_loss =0.0<br>    <br>    for i, data in enumerate(trainloader,0):<br>      <br>      inputs, labels = data<br>      inputs, labels = inputs.to(device), labels.to(device)<br><br>      optimizer.zero_grad()<br>      outputs = model(inputs)<br>      loss = criterion(outputs, labels)<br>      loss.backward()<br>      optimizer.step()<br><br>      # print statistics<br>      running_loss += loss.item()<br>      if i % 1000 == 999:<br>        print(f&#39;[Ep: {epoch + 1}, Step: {i + 1:5d}] loss: {running_loss / 2000:.3f}&#39;)<br>        running_loss = 0.0<br>  <br>  return model<br><br>model = train_model(model)<br>PATH = &#39;./float_model.pth&#39;<br>torch.save(model.state_dict(), PATH)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*PmYPDbzCwNCjt6LumnCqsQ.png" /><figcaption>Log messages</figcaption></figure><p>Now comes the interesting part - the quantization. I will be doing all three types of quantiztion possible:</p><p>1. <strong>Dynamic qunatization</strong> — makes the weights integer (after training)</p><p>2. <strong>Static quantization</strong> — makes the weights and activations integers (after training)</p><p>3. <strong>Quantization aware training </strong>— training the model from the begining with integer precission</p><p>So let’s start first with<strong> Dynamic qunatization:</strong></p><pre>import torch<br>from torch.ao.quantization import (<br>  get_default_qconfig_mapping,<br>  get_default_qat_qconfig_mapping,<br>  QConfigMapping,<br>)<br>import torch.ao.quantization.quantize_fx as quantize_fx<br>import copy<br><br># Load float model<br>model_fp = mAlexNet(num_classes= 10).to(device)<br>model_fp.load_state_dict(torch.load(&quot;./float_model.pth&quot;, map_location=device))<br><br># Copy model to qunatize<br>model_to_quantize = copy.deepcopy(model_fp).to(device)<br>model_to_quantize.eval()<br>qconfig_mapping = QConfigMapping().set_global(torch.ao.quantization.default_dynamic_qconfig)<br><br># a tuple of one or more example inputs are needed to trace the model<br>example_inputs = next(iter(trainloader))[0]<br><br># prepare<br>model_prepared = quantize_fx.prepare_fx(model_to_quantize, qconfig_mapping, <br>                  example_inputs)<br># no calibration needed when we only have dynamic/weight_only quantization<br># quantize<br>model_quantized_dynamic = quantize_fx.convert_fx(model_prepared)</pre><p>This is all we have to do to quantize our weights, as you can see we only need to pass one example input through the model to calibrate the qunatization layers. And let’s see the gains:</p><pre>print_model_size(model)<br>print_model_size(model_quantized_dynamic)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*V1RBzCrqyYJcsl4VcnooGg.png" /><figcaption>Model sizes</figcaption></figure><p>As you can see we get 0.03 MB from this, but we can make it even smaller with <strong>Static Mode Quantization</strong>:</p><pre>model_to_quantize = copy.deepcopy(model_fp)<br>qconfig_mapping = get_default_qconfig_mapping(&quot;qnnpack&quot;)<br>model_to_quantize.eval()<br># prepare<br>model_prepared = quantize_fx.prepare_fx(model_to_quantize, qconfig_mapping, example_inputs)<br># calibrate <br>with torch.no_grad():<br>    for i in range(20):<br>        batch = next(iter(trainloader))[0]<br>        output = model_prepared(batch.to(device))</pre><p>This is quite similiar, for now we just have to pass more batches of data to calibrate the model better, in order not to lose accuracy.</p><p>Let’s take a look at how these steps have affected the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*zHPyAWoacNkbEDkj6skVxA.png" /></figure><p>We can see that there is quite a lot going on behind the scenes, but fortunatelly everything is abstracted from us and we can focus on the functionallity. Now the last step after preparing the model is the following:</p><pre># quantize<br>model_quantized_static = quantize_fx.convert_fx(model_prepared)</pre><p>After which the <strong>model_quantized_static </strong>looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZ1FySHz9EuJH1ixN6Ciew.png" /></figure><p>We can see what is going on much clearer now. The Conv2d and Relu Layers have been fused and substituted with their quantized coounterparts which are calibrated accordingly. Let’s compare these models to our original one:</p><pre>print_model_size(model)<br>print_model_size(model_quantized_dynamic)<br>print_model_size(model_quantized_static)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*A_yBoob1ZSDC4pmDCRUqbQ.png" /><figcaption>Model sizes</figcaption></figure><p>Wow! The quantized model is 3 times smaller than the original one.</p><p>Now let’s also see how we can train the model with quantization in mind.</p><pre>model_to_quantize = mAlexNet(num_classes= 10).to(device)<br>qconfig_mapping = get_default_qat_qconfig_mapping(&quot;qnnpack&quot;)<br>model_to_quantize.train()<br># prepare<br>model_prepared = quantize_fx.prepare_qat_fx(model_to_quantize, qconfig_mapping, example_inputs)<br><br># training loop <br>model_trained_prepared = train_model(model_prepared)<br><br># quantize<br>model_quantized_trained = quantize_fx.convert_fx(model_trained_prepared)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*IN8c-_SD4_Q0156ymh2NnQ.png" /></figure><p>Now let’s compare the sizes of all of the models we trained so far.</p><pre>print(&quot;Regular floating point model: &quot; )<br>print_model_size( model_fp)<br>print(&quot;Weights only qunatization: &quot;)<br>print_model_size( model_quantized_dynamic)<br>print(&quot;Weights/Activations only qunatization: &quot;)<br>print_model_size(model_quantized_static)<br>print(&quot;Qunatization aware trained: &quot;)<br>print_model_size(model_quantized_trained)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*Om3y-2XD5DQnuhCQ47JwLA.png" /></figure><p>As we can see training with quantization in mind, does not do anything for the size of the model, but does it improove accuracy?</p><pre>def get_accuracy(model):<br>  correct = 0<br>  total = 0<br>  with torch.no_grad():<br>      for data in testloader:<br>          images, labels = data<br>          images, labels = images, labels<br>          outputs = model(images)<br>          _, predicted = torch.max(outputs.data, 1)<br>          total += labels.size(0)<br>          correct += (predicted == labels).sum().item()<br><br>      return 100 * correct / total<br><br>fp_model_acc = get_accuracy(model)<br>dy_model_acc = get_accuracy(model_quantized_dynamic)<br>static_model_acc = get_accuracy(model_quantized_static)<br>q_trained_model_acc = get_accuracy(model_quantized_trained)<br><br><br>print(&quot;Acc on fp_model:&quot; ,fp_model_acc)<br>print(&quot;Acc weigths only quantization:&quot;, dy_model_acc)<br>print(&quot;Acc weigths/activations quantization&quot; ,static_model_acc)<br>print(&quot;Acc on qunatization awere trained model:&quot; ,q_trained_model_acc)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*A0MohnfoYg9aEYEXT_TpSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*kPD5hykeqGj9udLzrqPvPg.png" /></figure><p>The accuracy of the quantization aware training model is slightly worse but that is in the realm of the standard deviation, so it is not a problem and sometimes it can get better than the floating point one.</p><p>We can see that the model has about the same accuracy with or without quantization, but with a dramatically decreased model size, which is crucial when we want to deploy it to a server or on a low-power device.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a9521571efa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting car prices using XGBBoostRegressor with enable_categorical option]]></title>
            <link>https://medium.com/@mor40/predicting-car-prices-using-xgbboostregressor-with-enable-categorical-option-2c4bfc6b6cc4?source=rss-669b53f21044------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c4bfc6b6cc4</guid>
            <category><![CDATA[tabular-model]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[mor40]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 16:13:10 GMT</pubDate>
            <atom:updated>2023-07-27T16:19:13.524Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial I am going to analyze, clean and build a model with data about second hand cars using the XGBBoost model. I am going to use the newly build-in enable_categorical option in XGBBoost 1.6 and later, in order to encode the categorical variables in the data. To get the data I have scraped the bulgarian website for second hand cars: cars.bg .</p><p>You can get the data from here: <a href="https://drive.google.com/file/d/1OambTNh3qwCai20Zz5KxC8e29MdGv3nO/view?usp=sharing">https://drive.google.com/file/d/1OambTNh3qwCai20Zz5KxC8e29MdGv3nO/view?usp=sharing</a></p><p>First let’s import the required libraries</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import xgboost as xgb<br>from sklearn.model_selection import train_test_split<br>from xgboost import XGBRegressor<br>from sklearn.model_selection import cross_val_score<br><br># Increase size of plot in jupyter<br>plt.rcParams[&quot;figure.figsize&quot;] = (10,7)</pre><p>Load the data from the path that you stored the file in and then remove id column.</p><pre>#Load data<br>data = pd.read_csv(&#39;/content/cars-data3.csv&#39;, index_col=None)<br><br># Remove Id column<br>data = data.drop([&#39;id&#39;],axis=&#39;columns&#39;)</pre><p>Let’s see how the data looks like:</p><pre>print(data.shape)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FAiHnQSnNmpna7dInOWJA.png" /></figure><p>We can see that we have brand and model of the car, the year that it is manufactured, the type of fuel that it uses which has the following mapping: ‘d’: “diesel”, ‘p’: “petrol”, ‘g’: “gas/lpg”, ‘h’: “hybrid”, ‘m’: ‘methane’, ‘e’: “electric”. <strong>“kms”</strong> column are the kilometers that the car has recorded, <strong>“transmission” </strong>is 1 if automatic and 0 if manual, <strong>“2door”</strong> is 1 for car with 2 doors and 0 otherwise, <strong>“hp”</strong> is the horsepower. <strong>“euro”</strong> is the euro emissions rating of the car. and <strong>“price”</strong> is the target column that we will predict.</p><p>Lets now see some key properties of the data:</p><pre>def summary(df):<br>    print(f&#39;data shape: {df.shape}&#39;)<br>    summ = pd.DataFrame(df.dtypes, columns=[&#39;data type&#39;])<br>    summ[&#39;#unique&#39;] = df.nunique().values<br>    desc = pd.DataFrame(df.describe(include=&#39;all&#39;).transpose())<br>    summ[&#39;min&#39;] = desc[&#39;min&#39;].values<br>    summ[&#39;max&#39;] = desc[&#39;max&#39;].values<br>    summ[&#39;average&#39;] = desc[&#39;mean&#39;].values<br>    summ[&#39;standard_deviation&#39;] = desc[&#39;std&#39;].values<br>    summ[&#39;missing&#39;] = df.isna().sum()<br><br><br>    return summ<br><br>summary(data).style.background_gradient(cmap=&#39;YlOrBr&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwxrR3beVr7XYTUHGYNTjA.png" /></figure><p>From this table we can extract some import information. Firstly we can see that the <strong>model</strong> column has many unique values, so we can try to redcuce them. We can also see that the <strong>kms</strong>, <strong>displacement</strong> and <strong>hp</strong> columns have some pretty extreme values which will have to be removed. Also the <strong>euro</strong>, <strong>hp</strong> and <strong>diplacement</strong> columns have a lot of missing values.</p><p>For the <strong>euro</strong> column I have decided to remove it entirely since a large portion of it is missing and is largely correlated to the year column so it is not of much use, but feel free to impute it if you want to keep it. And generally in this project I didn’t impute missing values, since I didn’t see any performance imporoovment and also to keeps things simple.</p><pre>print(&quot;Before dropping NA: &quot;,data.shape)<br>data.drop(&#39;euro&#39;,axis=1 ,inplace= True)<br>data = data.dropna()<br>print(&quot;After dropping NA: &quot;,data.shape)<br><br>Before dropping NA:  (25670, 13)<br>After dropping NA:  (21961, 12)</pre><p>We can see that we have approximatly 4 thousand less examples and 1 less column.</p><p>Now let’s do some cleaning.</p><p>First thing that I noticed is that the model column for the bmw brand is too granular so I take only the first character from the model column. When the model is for example 330, 218,523 it becomes -&gt; 3, 2, 5, so that we reduce the possible values.</p><pre>data.loc[data[&#39;brand&#39;] == &#39;BMW&#39;, [&#39;brand&#39;,&#39;model&#39;]][:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHoyY_42pNFaOJTHm1FrQw.png" /></figure><p>And lets do some further cleaning:</p><pre># Remove brands that are seen less than 200 times<br>data = data.groupby(&#39;brand&#39;).filter(lambda x :len(x)&gt;200)<br><br>#Format BMW model<br>def format_bmw_model(model_name):<br>  if &#39;X&#39; in model_name or &#39;i&#39; in model_name:<br>    return model_name<br>  return model_name[0]<br><br># Trim model to just 1 letter except if it is X or i ex.(318 to 3)<br>data.loc[data[&#39;brand&#39;] == &#39;BMW&#39;, [&#39;model&#39;]] = data[data.brand == &#39;BMW&#39;].model.apply(lambda x: format_bmw_model(x))<br><br># Remove models that are met less than 20 times<br>data = data.groupby(&#39;model&#39;).filter(lambda x :len(x)&gt;20)<br><br># Remove cars from years that are met less than 10 times<br>data = data.groupby(&#39;year&#39;).filter(lambda x :len(x)&gt;10)<br><br>Shape after cleaning: (18661, 12)</pre><p>Now let’s see what are the types of the columns of the dataset and check if everything is right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TR3anNKlbD60MOrZP0Sm6A.png" /></figure><p>Let’s see the values for the <strong>boolean columns</strong>.</p><pre>data[[&quot;transmission&quot;, &quot;2door&quot;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQ3AKP6iBgHL22Kgjjs_2A.png" /></figure><p>We can see that they are either 0 or 1, so lets make them int64.</p><pre>data[[&quot;transmission&quot;,&quot;2door&quot;]] = data[[&quot;transmission&quot;,&quot;2door&quot;]].astype(&#39;int64&#39;)</pre><p>Let’s see what is the distribution for the other numerical columns:</p><pre># Select columns with &#39;float64&#39; dtype  <br>float64_cols = list(data.select_dtypes(include=&#39;float64&#39;))<br><br>data[float64_cols].hist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pD2Slspnm9Dr-nCuCZSlA.png" /></figure><p>We can clearly see that they are extreme outliers in each of them so let’s remove them.</p><pre>#Trim outliers<br>print(&quot;Old Shape before trimming: &quot;, data.shape)<br>data = data[(data.hp &gt;30) &amp; (data.hp &lt; 480)]<br>data = data[(data.price &gt;100) &amp; (data.price &lt; 60000)]<br>data = data[(data.displacement &gt;100) &amp; (data.displacement &lt; 8000)]<br>data = data[(data.kms &gt;100) &amp; (data.kms &lt; 1000000)]<br>print(&quot;New Shape after trimming: &quot;, data.shape)<br><br># Turn from float64 to float32 for performance<br>data[float64_cols] = data[float64_cols].astype(&#39;float32&#39;)<br><br>print(data[float64_cols].describe())<br><br>data[float64_cols].hist()<br><br>Old Shape before trimming:  (18661, 12)<br>New Shape after trimming:  (18371, 12)</pre><p>Now the distribution looks a lot better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mL3Kscbq3vbMwr9yLew2FA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xm2cHZqm935SN-R_Y0z1yQ.png" /></figure><p>Feel free to also further normalize the data with log transformations or any other method.</p><p>Another modification that can be done is making bins out of the <strong>kms</strong> column, because information from that column comes more from the difference in the hundreds of thousands , so for example a value of 255 000 and value of 266 000 does not make any difference to the final price. People would set the value based on the psycological difference in numbers like 200 thousand or 600 thousand kilometers so we will discretisize this column into 10 discrete categories.</p><pre># get maximum value of kms column<br>maximum_kms = int(data.kms.max())<br><br>def make_buckets(df):<br>  bins = [0,50000, 100000, 150000,200000,250000,300000,400000,500000,600000,maximum_kms]<br>  labels = [1,2,3,4,5,6,7,8,9,10]<br>  df[&#39;kms&#39;] = pd.cut(x = df[&#39;kms&#39;], <br>                     bins = bins,<br>                     labels = labels,<br>                     include_lowest = True)<br>  return df<br><br>data = make_buckets(data)<br><br># Making it int because pd.cut makes it category type<br>data[&quot;kms&quot;] = data[&quot;kms&quot;].astype(&#39;int32&#39;)<br><br>data.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZ59BlcOs43nwH3MGWsbYQ.png" /></figure><p>Now the types look better. Usually at this point we will have to use sklearn Label Encoders to encode the object columns into numeric ones, but since xgbboost 1.6 we can pass category columns to it and it will deal with the encodings. You can read more about it here: <a href="https://xgboost.readthedocs.io/en/stable/tutorials/categorical.html">https://xgboost.readthedocs.io/en/stable/tutorials/categorical.html</a></p><p>The only thing we have to do is to turn the type of the object columns to category:</p><pre>categorical_cols = list(data.select_dtypes(include=&#39;object&#39;))<br>data[categorical_cols] = data[categorical_cols].astype(&#39;category&#39;)<br>data.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTsRHYzxWcB26l3PsNITqg.png" /></figure><p>Now we are ready for training:</p><pre># Train set without price variable<br>X = data.copy()<br><br># Label<br>y = X.pop(&#39;price&#39;)<br><br># Divide into train and test<br>X_train, X_test, y_train, y_test = train_test_split(<br>      X, y, test_size=0.20, random_state=42, shuffle = True)<br><br># max_cat_to_onehot is a threshlod value for one-hot encoding features<br># if a feature has less than the specified threshold it gets one-hot encoded<br># otherwise it is ordinal encoded<br>model = XGBRegressor(random_state=42,<br>                     tree_method=&quot;hist&quot;, <br>                     eval_metric=&quot;mae&quot; , <br>                     max_depth=5,<br>                     enable_categorical=True,<br>                    max_cat_to_onehot=21,  <br>)<br><br># color, type, fuel will be one-hot encoded<br># fit model<br>model.fit(X_train, y_train,eval_set=[(X_test, y_test)], verbose=False)</pre><p>Now lets see the performance:</p><pre># Calculate error <br>mae_train = -1 * cross_val_score(model, X_train, y_train,<br>                                  cv=3,<br>                                  scoring=&#39;neg_mean_absolute_error&#39;)<br><br><br>mae_test = -1 * cross_val_score(model, X_test, y_test,<br>                                  cv=3,<br>                                  scoring=&#39;neg_mean_absolute_error&#39;)<br><br># Supress scientific notation<br>pd.options.display.float_format = &#39;{:.10f}&#39;.format<br><br>print(&quot;Mean absolute error CV train: &quot;, mae_train.mean())<br><br>print(&quot;Mean absolute error CV test: &quot;, mae_test.mean())</pre><p>Mean absolute error CV train: 1760.41</p><p>Mean absolute error CV test: 2173.80</p><p>And let’s see feature importances:</p><pre>fis = zip(X.columns.to_list(),list(model.feature_importances_))<br>for col, fi in fis:<br>  print(col,&quot; &quot;, fi)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwErAHuZtGPWpMntYMKH8g.png" /></figure><p>From the results we can conclude that the model has overfitted a little bit, so we can do further hyperparameter tuning and some of the features have very little feature imporance (fuel, color,kms), so we can do more feature enginnering, but this will be covered in different article. Here I have demonstrated how much easier is to train a xgbboost model with the new enable_categorical option.</p><p>The notebook used to make this article is here: <a href="https://colab.research.google.com/drive/1BU3mQuDbHv7xCK2HYc2qYb8PKx_8RE4S?usp=sharing">https://colab.research.google.com/drive/1BU3mQuDbHv7xCK2HYc2qYb8PKx_8RE4S?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c4bfc6b6cc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>