<?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"><channel><title><![CDATA[Suvrakamal Das]]></title><description><![CDATA[Suvrakamal Das]]></description><link>https://suvrakamaldas.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 01 Sep 2026 22:30:33 GMT</lastBuildDate><atom:link href="https://suvrakamaldas.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Scaling your ML API to One Million Requests per day]]></title><description><![CDATA[Many ML developers focus on making their ML models better, improving it's performance and etc, obviously, there is a lot it, also you don't focus on it because there are solutions like HF spaces to host your ml models on the internet just to share it...]]></description><link>https://suvrakamaldas.hashnode.dev/scaling-your-ml-api-to-one-million-requests-per-day</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/scaling-your-ml-api-to-one-million-requests-per-day</guid><category><![CDATA[rayserve]]></category><category><![CDATA[APIs]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[FastAPI]]></category><category><![CDATA[pytorch]]></category><category><![CDATA[ONNX]]></category><category><![CDATA[Docker]]></category><category><![CDATA[k8s]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[HPA]]></category><category><![CDATA[Load Balancing]]></category><category><![CDATA[YAML]]></category><category><![CDATA[k6]]></category><category><![CDATA[Postman]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Sat, 29 Jun 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/YCIqvvIn55M/upload/b71070a7e58ec26d28f0c608fe0e56c0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Many ML developers focus on making their ML models better, improving it's performance and etc, obviously, there is a lot it, also you don't focus on it because there are solutions like HF spaces to host your ml models on the internet just to share it with the world.</p>
<p>For an ML lifecycle ML Serving is also important and what if there is a way to easily deploy your models on production on the cloud using efficient tools without worrying about vendor lock in?</p>
<p>Today we will be learning how to take a model train it on a dataset and achieve 90% accuracy which is pretty simple.</p>
<p>Also we will then talk about how to create an API Endpoint for it using FastAPI.<br />And we will talk about how to improve it's accuracy and reducing the API latency which is crucial for high volume API request handling.</p>
<p>Finally we will talk about how to scale and API using K8s pods and how to set it up on AWS Amazon Elastic Kubernetes Service.</p>
<p>We will finally test it out and see if this can handle 1 million requests per day and we will do an API testing for it.</p>
<h2 id="heading-so-lets-get-started">So Let's get started ...</h2>
<p>For the sake of training a model we are taking a simple <a target="_blank" href="https://huggingface.co/datasets/stanfordnlp/imdb">Standford IMDB dataset</a> and training a BERT model with this dataset.</p>
<p>I provided an access to a J<a target="_blank" href="https://github.com/rr2203/BERT-Fine-Tune-For-Sentiment-Analysis">upyter Notebook</a> that have achieved a 91% accuracy in on the PyTorch model which means, during inferencing the model will be 91% accurate on the dataset. To be accurate we can use <a target="_blank" href="https://huggingface.co/JiaqiLee/imdb-finetuned-bert-base-uncased">trained models</a> from hugging face itself.</p>
<pre><code class="lang-python"><span class="hljs-comment">#use this code to draw inference from this hugging face model trained on IMDB dataset</span>
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> BertForSequenceClassification, BertTokenizer, TextClassificationPipeline
model_path = <span class="hljs-string">"JiaqiLee/imdb-finetuned-bert-base-uncased"</span>
tokenizer = BertTokenizer.from_pretrained(model_path)
model = BertForSequenceClassification.from_pretrained(model_path, num_labels=<span class="hljs-number">2</span>)
pipeline = TextClassificationPipeline(model=model, tokenizer=tokenizer)
print(pipeline(<span class="hljs-string">"I like the movie, it was awesome"</span>))
</code></pre>
<p>We can simply create a FastAPI endpoint for this, and start deploying it on K8s right?</p>
<h3 id="heading-creating-a-fastapi-endpoint">Creating a FastAPI Endpoint</h3>
<p>So let's do the easiest job in the world.</p>
<pre><code class="lang-python"><span class="hljs-comment">#using huggingface model</span>

<span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI
<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> BertForSequenceClassification, BertTokenizer, TextClassificationPipeline

app = FastAPI()

<span class="hljs-comment"># Load the model and tokenizer</span>
model_path = <span class="hljs-string">"JiaqiLee/imdb-finetuned-bert-base-uncased"</span>
tokenizer = BertTokenizer.from_pretrained(model_path)
model = BertForSequenceClassification.from_pretrained(model_path, num_labels=<span class="hljs-number">2</span>)
pipeline = TextClassificationPipeline(model=model, tokenizer=tokenizer)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TextInput</span>(<span class="hljs-params">BaseModel</span>):</span>
    text: str

<span class="hljs-meta">@app.post("/classify/")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">classify_text</span>(<span class="hljs-params">input: TextInput</span>):</span>
    result = pipeline(input.text)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"label"</span>: result[<span class="hljs-number">0</span>][<span class="hljs-string">'label'</span>], <span class="hljs-string">"score"</span>: result[<span class="hljs-number">0</span>][<span class="hljs-string">'score'</span>]}

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    <span class="hljs-keyword">import</span> uvicorn
    uvicorn.run(app, host=<span class="hljs-string">"0.0.0.0"</span>, port=<span class="hljs-number">8000</span>)
</code></pre>
<p>This code will setup a Fast Api endpoint `<code>/classify</code>` for you. you can try by sending an API request to this endpoint and try for yourself.</p>
<p>I have tested this on postman and the API latency came around 120-160 ms which is very high for serving 1 million requests per day.</p>
<p>So there are a couple methods to reduce to API latency, here are some of the ways we can optimize the API latency time</p>
<ul>
<li><p>Download the Pytorch model instead of calling the HF API</p>
</li>
<li><p>Use <code>BertTokenizerFast</code></p>
</li>
<li><p>Use ONNX (Open Neural Network Exchange) Model</p>
</li>
<li><p>Reduce Model Size (no implementation here)</p>
</li>
<li><p>Use Asynchronous FastAPI (no implementation here)</p>
</li>
</ul>
<p>I have implemented a few methods to reduce API Latency which shows significant reduction in API Response Time.</p>
<h3 id="heading-using-the-downloaded-pytorch-model">Using the downloaded Pytorch Model</h3>
<p>Just download the Pytorch model contents and replace the model path in the previous code to the directory where you saved the model.</p>
<p>This reduced the API latency by 10-12 ms and shows that we are moving in the right direction.</p>
<pre><code class="lang-python"><span class="hljs-comment">#replace the model_path with the directory of your saved model</span>
model_path = <span class="hljs-string">"./model"</span>
</code></pre>
<h3 id="heading-using-berttokenizerfast-for-faster-api-response-times">Using BertTokenizerFast for faster API response times</h3>
<pre><code class="lang-python"><span class="hljs-comment">#rest of the imports </span>
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> BertTokenizerFast
.
.
.
tokenizer = BertTokenizerFast.from_pretrained(model_path)
<span class="hljs-comment">#rest of the code</span>
.
.
</code></pre>
<p>This claims to reduce API latency drastically but in my case this has been successful to a small extent, where the latency reduced around another 10-12 ms bringing down the overall latency to <strong>90 ms.</strong></p>
<h3 id="heading-using-onnx-models">Using ONNX models</h3>
<p>ONNX is so famous that I don't need to introduce you to the world of ONNX, it has integration with Pytorch and you can easily convert a Pytorch Model to an ONNX model. Given below is a code implementation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> BertForSequenceClassification, BertTokenizer
<span class="hljs-keyword">import</span> torch

model_path = <span class="hljs-string">"JiaqiLee/imdb-finetuned-bert-base-uncased"</span>
tokenizer = BertTokenizer.from_pretrained(model_path)
model = BertForSequenceClassification.from_pretrained(model_path, num_labels=<span class="hljs-number">2</span>)

<span class="hljs-comment"># Create a dummy input for tracing</span>
dummy_input = tokenizer(<span class="hljs-string">"This is a dummy input"</span>, return_tensors=<span class="hljs-string">"pt"</span>)

<span class="hljs-comment"># Export the model to ONNX format</span>
torch.onnx.export(model,
                  (dummy_input[<span class="hljs-string">'input_ids'</span>], dummy_input[<span class="hljs-string">'attention_mask'</span>]),
                  <span class="hljs-string">"model.onnx"</span>,
                  input_names=[<span class="hljs-string">"input_ids"</span>, <span class="hljs-string">"attention_mask"</span>],
                  output_names=[<span class="hljs-string">"output"</span>],
                  dynamic_axes={<span class="hljs-string">"input_ids"</span>: {<span class="hljs-number">0</span>: <span class="hljs-string">"batch_size"</span>},
                                <span class="hljs-string">"attention_mask"</span>: {<span class="hljs-number">0</span>: <span class="hljs-string">"batch_size"</span>},
                                <span class="hljs-string">"output"</span>: {<span class="hljs-number">0</span>: <span class="hljs-string">"batch_size"</span>}})

print(<span class="hljs-string">"Model successfully converted to ONNX format and saved as 'model.onnx'."</span>)
</code></pre>
<p>We can use the saved model and run it, and also we can create a similar API endpoint of it using <strong><em><mark>FastAPI</mark></em></strong> and run it.</p>
<p>#running an onnx model .</p>
<pre><code class="lang-python">
<span class="hljs-keyword">import</span> onnxruntime <span class="hljs-keyword">as</span> ort
<span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> BertTokenizer
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np

model_path = <span class="hljs-string">"./model"</span>
tokenizer = BertTokenizer.from_pretrained(model_path)

<span class="hljs-comment"># Load the ONNX model</span>
onnx_model_path = <span class="hljs-string">"model.onnx"</span>
ort_session = ort.InferenceSession(onnx_model_path)

<span class="hljs-comment"># Check the expected sequence length</span>
expected_seq_len = ort_session.get_inputs()[<span class="hljs-number">0</span>].shape[<span class="hljs-number">1</span>]

<span class="hljs-comment"># Define a function to perform inference</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">classify_text</span>(<span class="hljs-params">text</span>):</span>
    inputs = tokenizer(text, return_tensors=<span class="hljs-string">"np"</span>, padding=<span class="hljs-string">'max_length'</span>, truncation=<span class="hljs-literal">True</span>, max_length=expected_seq_len)
    ort_inputs = {k: np.array(v) <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> inputs.items() <span class="hljs-keyword">if</span> k <span class="hljs-keyword">in</span> [<span class="hljs-string">"input_ids"</span>, <span class="hljs-string">"attention_mask"</span>]}
    ort_outs = ort_session.run(<span class="hljs-literal">None</span>, ort_inputs)
    label_id = ort_outs[<span class="hljs-number">0</span>].argmax(axis=<span class="hljs-number">1</span>)[<span class="hljs-number">0</span>]
    labels = [<span class="hljs-string">"NEGATIVE"</span>, <span class="hljs-string">"POSITIVE"</span>]  <span class="hljs-comment"># Assuming binary classification</span>
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"label"</span>: labels[label_id], <span class="hljs-string">"score"</span>: float(ort_outs[<span class="hljs-number">0</span>].max())}

<span class="hljs-comment"># Test the function with a sample input</span>
sample_text = <span class="hljs-string">"The movie was fantastic! I really enjoyed it."</span>
result = classify_text(sample_text)
print(result)

<span class="hljs-comment">#expected output</span>
{<span class="hljs-string">'label'</span>: <span class="hljs-string">'POSITIVE'</span>, <span class="hljs-string">'score'</span>: <span class="hljs-number">2.6588470935821533</span>}
</code></pre>
<p><strong><em><mark>This has reduce the model API latency by a drastic amount of 30-40 ms from 90-100ms which is huge.</mark></em></strong></p>
<p><a target="_blank" href="https://www.postman.com/"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720391570094/07243080-00af-465a-a2b7-ee8d35ee3b95.png" alt class="image--center mx-auto" /></a></p>
<p>We can further optimize the ONNX model or quantize the model(which reduces the performance) to reduce the API response time.</p>
<p>Code for optimizing the model</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> onnx
<span class="hljs-keyword">from</span> onnxruntime.transformers <span class="hljs-keyword">import</span> optimizer

<span class="hljs-comment"># Load the ONNX model</span>
onnx_model_path = <span class="hljs-string">"model.onnx"</span>
onnx_model = onnx.load(onnx_model_path)

<span class="hljs-comment"># Optimize the ONNX model</span>
optimized_model = optimizer.optimize_model(onnx_model, model_type=<span class="hljs-string">'bert'</span>)

<span class="hljs-comment"># Save the optimized model</span>
optimized_model_path = <span class="hljs-string">"model2.onnx"</span>
optimized_model.save_model_to_file(optimized_model_path)

print(<span class="hljs-string">"Model has been further optimized and saved."</span>)
</code></pre>
<p>This will reduce the model response time and API Response time by another 10-12 ms which will finally bring our <strong><em><mark>API response time in around 20-30 ms</mark></em></strong></p>
<p>Here is an awesome repo to help you with optimization , have a look - <a target="_blank" href="https://github.com/ELS-RD/transformer-deploy">https://github.com/ELS-RD/transformer-deploy</a></p>
<p><a target="_blank" href="https://els-rd.github.io/transformer-deploy/">transformer-deploy by Lefebvre Dalloz</a></p>
<p>Now that we have brought down the API response time, let's focus on Model Serving.<br />I have used <a target="_blank" href="https://docs.ray.io/en/latest/serve/index.html"><mark>Ray Serve</mark></a> for my own purpose, which needs a separate introduction of its own but we will continue with simply serving this model with AWS (EKS) and use <a target="_blank" href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Kubernetes Horizontal Pod Autoscaler.</a><br /><strong>The HPA</strong> <strong>automatically scales the number of pods in a deployment or replication controller based on observed CPU utilization (or other select metrics).</strong></p>
<p>Setup your <a target="_blank" href="https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html">AWS EKS</a> and containerize your FastAPI Application and push it on Docker Hub (you can use AWS too or anything else)</p>
<p>You can use my Docker Image for example - <a target="_blank" href="https://hub.docker.com/repository/docker/subhro2084/fastapi-app/general">subhro2084/fastapi-app general | Docker Hub</a></p>
<p>After you dockerize your fastapi image, make sure you get the endpoint right and it works. Only then upload it on dockerhub.</p>
<p>If your EKS cluster is created, fire your AWS cloud shell terminal and get started with these steps, try a little bit doesn't works at one go (it works on my machine 🙂 feelings ....yk)</p>
<h3 id="heading-okay-lets-get-started">OKAY, Let's get started 😊</h3>
<p><img src="https://media.tenor.com/jM6XQto6h_EAAAAC/okay-lets-get-started.gif" alt="Okay Lets Get Started GIF - Okay Lets Get Started Lets Do This ..." class="image--center mx-auto" /></p>
<p>First, have a look around how much is ONE MILLION REQUESTS PER DAY??</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720392470943/077c4259-beaa-4f70-a8b7-21a511c020c5.png" alt class="image--center mx-auto" /></p>
<p>At it's peak you should be able to handle 25 RPS, and you have to keep your pods ready till that. The following infra was tested on <strong>40 RPS</strong> which it handles easily.</p>
<p>Create a file <code>fastapi-app.yaml</code> and add this content:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">fastapi-app</span>
  <span class="hljs-attr">labels:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">fastapi-app</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">replicas:</span> <span class="hljs-number">1</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">matchLabels:</span>
      <span class="hljs-attr">app:</span> <span class="hljs-string">fastapi-app</span>
  <span class="hljs-attr">template:</span>
    <span class="hljs-attr">metadata:</span>
      <span class="hljs-attr">labels:</span>
        <span class="hljs-attr">app:</span> <span class="hljs-string">fastapi-app</span>
    <span class="hljs-attr">spec:</span>
      <span class="hljs-attr">containers:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">fastapi-app</span>
        <span class="hljs-attr">image:</span> <span class="hljs-string">subhro2084/fastapi-app:latest</span> <span class="hljs-comment">#depends on what image you are using</span>
        <span class="hljs-attr">ports:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">8000</span>
        <span class="hljs-attr">resources:</span>
          <span class="hljs-attr">requests:</span>
            <span class="hljs-attr">memory:</span> <span class="hljs-string">"512Mi"</span> <span class="hljs-comment">#depends on the type of machine you have used</span>
            <span class="hljs-attr">cpu:</span> <span class="hljs-string">"250m"</span>
          <span class="hljs-attr">limits:</span>
            <span class="hljs-attr">memory:</span> <span class="hljs-string">"1Gi"</span>
            <span class="hljs-attr">cpu:</span> <span class="hljs-string">"500m"</span>
<span class="hljs-meta">---</span>
<span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Service</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">fastapi-service</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">app:</span> <span class="hljs-string">fastapi-app</span>
  <span class="hljs-attr">type:</span> <span class="hljs-string">LoadBalancer</span>
  <span class="hljs-attr">ports:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">protocol:</span> <span class="hljs-string">TCP</span>
      <span class="hljs-attr">port:</span> <span class="hljs-number">80</span>
      <span class="hljs-attr">targetPort:</span> <span class="hljs-number">8000</span>
<span class="hljs-meta">---</span>
<span class="hljs-attr">apiVersion:</span> <span class="hljs-string">autoscaling/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">HorizontalPodAutoscaler</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">fastapi-app-hpa</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">scaleTargetRef:</span>
    <span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
    <span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">fastapi-app</span>
  <span class="hljs-attr">minReplicas:</span> <span class="hljs-number">1</span>
  <span class="hljs-attr">maxReplicas:</span> <span class="hljs-number">10</span>
  <span class="hljs-attr">targetCPUUtilizationPercentage:</span> <span class="hljs-number">50</span>
</code></pre>
<p>You need to save this YAML file in your AWS Cloudshell and apply the configuration:<br /><code>kubectl apply -f fastapi-app.yaml</code></p>
<p>Verify the deployment using -</p>
<p><code>kubectl get pods</code> Ensure your pods are running <code>kubectl get hpa</code> to monitor the HPA status</p>
<p>Test the Application -&gt;</p>
<p><code>curl -X POST "</code><a target="_blank" href="http:///classify/"><code>http://&lt;EXTERNAL-IP-OF-YOUR-AWS-POD&gt;/classify/</code></a><code>" -H "accept: application/json" -H "Content-Type: application/json" -d '{"text": "I love you"}'</code></p>
<p>You can use K6 which is famous for load testing and run it locally.</p>
<p>Use this <code>script.js</code> file and save it</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'k6/http'</span>;
<span class="hljs-keyword">import</span> { check, sleep } <span class="hljs-keyword">from</span> <span class="hljs-string">'k6'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> options = {
  <span class="hljs-attr">stages</span>: [
    { <span class="hljs-attr">duration</span>: <span class="hljs-string">'5m'</span>, <span class="hljs-attr">target</span>: <span class="hljs-number">40</span> }, <span class="hljs-comment">// Ramp-up to 25 RPS over 5 minutes</span>
    { <span class="hljs-attr">duration</span>: <span class="hljs-string">'8h'</span>, <span class="hljs-attr">target</span>: <span class="hljs-number">40</span> }, <span class="hljs-comment">// Stay at 25 RPS for 8 hours (office hours)</span>
    { <span class="hljs-attr">duration</span>: <span class="hljs-string">'5m'</span>, <span class="hljs-attr">target</span>: <span class="hljs-number">5</span> }, <span class="hljs-comment">// Ramp-down to 5 RPS over 5 minutes</span>
    { <span class="hljs-attr">duration</span>: <span class="hljs-string">'15h'</span>, <span class="hljs-attr">target</span>: <span class="hljs-number">5</span> }, <span class="hljs-comment">// Stay at 5 RPS for 15 hours (non-office hours)</span>
  ],
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> res = http.post(<span class="hljs-string">'http://a4ee008522b7547aaaa5c7a338f1123d-1605357505.ap-south-1.elb.amazonaws.com/classify/'</span>, <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">text</span>: <span class="hljs-string">'I love you'</span> }), {
    <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
  });
  check(res, { <span class="hljs-string">'status was 200'</span>: <span class="hljs-function">(<span class="hljs-params">r</span>) =&gt;</span> r.status === <span class="hljs-number">200</span> });
  sleep(<span class="hljs-number">1</span>);
}
</code></pre>
<p>Run it on your machine using <code>k6 run --out web-dashboard script.js</code></p>
<p>We will get a similar report like this -</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720391802790/427d9c66-bba6-403a-bfd5-cdd24598f2a8.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Iterate and change the number of pods.</p>
</li>
<li><p>Adjust the Horizontal Pod Autoscalers (HPAs).</p>
</li>
<li><p>Use better machines.</p>
</li>
<li><p>Opt for smaller model sizes.</p>
</li>
<li><p>Implement asynchronous API.</p>
</li>
</ul>
<p>These are some of the steps we can take to reduce the API limit, this a work under progress , I will still need to add a wonderful tool called Ray Serve which runs on top of K8s, which changes the game.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720392654497/a2713ef3-b473-4de3-9924-ab31f09db03a.png" alt class="image--center mx-auto" /></p>
<p>Thanks for reading till here❤️❤️, if you like this, please tell how to improve, here are my socials links if you find I made an embarrassing mistake here 😎.</p>
<p><a target="_blank" href="https://x.com/subhrokomol">Twitter</a>🐤 , <a target="_blank" href="https://www.linkedin.com/in/subhrokomol/">Linkedin</a>🫠</p>
]]></content:encoded></item><item><title><![CDATA[Using Kubeflow for Orchestrating ML Workflows]]></title><description><![CDATA[How many of you have tried to build the famous "facial recognition model" in your local machine and felt proud? But imagine you build a software where the same model is being used for facial recognition of thousands of students for automatic attendan...]]></description><link>https://suvrakamaldas.hashnode.dev/using-kubeflow-for-orchestrating-ml-workflows</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/using-kubeflow-for-orchestrating-ml-workflows</guid><category><![CDATA[kubeflow]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Wed, 31 Jan 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1711860666348/6e3bb69d-2cce-4b63-98fa-2c3cbaa47262.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>How many of you have tried to build the famous "facial recognition model" in your local machine and felt proud? But imagine you build a software where the same model is being used for facial recognition of thousands of students for automatic attendance registration in a college or university.</p>
<p>The point being ML code you write on your local machine is just a small part of the whole process it takes to create an enterprise grade software that can actually solve real world problems.</p>
<p>A glimpse of how enterprise production solution looks like -</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711862082890/2fdc14fd-56e2-4c6b-80e2-d16ba7d298c4.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-challenges-enterprise-face-in-deploying-ml-solutions">Challenges Enterprise face in deploying ML solutions</h3>
<ul>
<li><p>Data Collection</p>
</li>
<li><p>Deploying and Reproducing the model in production</p>
</li>
<li><p>Model Monitoring</p>
</li>
<li><p>Keeping model relevant by adopting to changing business scenarios</p>
</li>
<li><p>Communicate and interpret model output to various stakeholders.</p>
</li>
</ul>
<p>Kubeflow allows you to make the deployment of machine learning workflows on Kubernetes simple, composable, portable, and scalable.</p>
<h3 id="heading-how-to-setup-kubeflow-in-windows-subsystem-for-linux-locally">How to setup Kubeflow in Windows Subsystem for Linux Locally</h3>
<p>The official website for Kubeflow currently does not have a clear doc on how to set it up Windows, so I will be discussing it in this blog.</p>
<p>To install Kubeflow locally, you need a few tools.</p>
<p>We’ll assume you have knowledge of Docker, as it is basically a prerequisite for working with Kubernetes. If you are unfamiliar with Docker, check out this tutorial to get you up to speed, then come back here.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711899890494/cbdefcb9-b101-4801-9cab-80b1501e2179.png" alt class="image--center mx-auto" /></p>
<p>Since Kubeflow runs wherever K8s runs, we can just deploy a K8s cluster locally and try to run KubeFlow.<br />Additionally, you’ll need the following tools:</p>
<ul>
<li><p><a target="_blank" href="https://kubernetes.io/docs/reference/kubectl/">kubectl</a>, which is a command-line tool to manage your K8s cluster</p>
</li>
<li><p><a target="_blank" href="https://kustomize.io/">kustomize</a> to configure applications using YAML</p>
</li>
</ul>
<h3 id="heading-minikube-installation"><strong>Minikube Installation</strong></h3>
<p>Minikube will help setup a cluster locally on your machine. In terms of terminology, think of your computer as a single node responsible for housing the pods. These pods are where your application containers operate. The management of these pods is carried out by a deployment, which outlines the ideal condition for your Kubernetes application.</p>
<p>The initial command fetches and downloads the necessary binary, whereas the subsequent command facilitates its installation to the designated location.</p>
<p><code>curl -LO &lt;https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64&gt; sudo install minikube-linux-amd64 /usr/local/bin/minikube</code></p>
<h3 id="heading-what-is-kubectl"><strong>What is kubectl?</strong></h3>
<p><code>kubectl</code> is a versatile command-line utility designed to manage Kubernetes clusters efficiently. Often likened to a "Swiss Army knife" for its multipurpose functionality, it stands as an essential instrument in the administration of cluster resources.</p>
<p><code>sudo snap install kubectl --classic</code></p>
<h3 id="heading-what-is-kustomize">What is Kustomize</h3>
<p>Kubernetes operations are predominantly governed through an extensive array of YAML files. To streamline customization, <code>kustomize</code> offers a powerful solution. This tool enables the modification of raw, template-free YAML files without altering the original documents, ensuring they remain intact and operational as is.</p>
<h3 id="heading-finally">Finally!!</h3>
<p>Now that you have all the prerequisite software and packages installed, it is now time to install Kubeflow.</p>
<p>Follow these steps:</p>
<ol>
<li>Clone the <strong>manifests</strong> repo from the Kubeflow team:</li>
</ol>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> &lt;https://github.com/kubeflow/manifests.git&gt;
</code></pre>
<ol>
<li>Change to the repo directory:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> manifests
</code></pre>
<ol>
<li>Build and apply the YAML files for all Kubeflow components:</li>
</ol>
<pre><code class="lang-bash"><span class="hljs-keyword">while</span> ! kustomize build example | awk <span class="hljs-string">'!/well-defined/'</span> | kubectl apply -f -; <span class="hljs-keyword">do</span> <span class="hljs-built_in">echo</span> <span class="hljs-string">"Retrying to apply resources"</span>; sleep 10; <span class="hljs-keyword">done</span>
</code></pre>
<ol>
<li>Wait for everything to settle out.</li>
</ol>
<p>You can check to see if everything has settled out by running:</p>
<pre><code class="lang-bash">kubectl get pods -A
</code></pre>
<p>This will list all pods across all namespaces.</p>
<pre><code class="lang-bash">NAMESPACE         NAME                                     READY  STATUS    RESTARTS      AGE
auth              dex-7ff46847-sqxzj                       1/1    Running   0             10h
cert-manager      cert-manager-7fb78674d7-nllnn            1/1    Running   0             10h
cert-manager      cert-manager-cainjector-5dfc946d84-m6f7  1/1    Running   0             10h
cert-manager      cert-manager-webhook-8744b7588-cvzzm     1/1    Running   0             10h
istio-system      authservice-0                            1/1    Running   0             10h
istio-system      cluster-local-gateway-675bb7b74-49x27    1/1    Running   0             10h
istio-system      istio-ingressgateway-c7fdd4bf6-z68qt     1/1    Running   0             10h
istio-system      istiod-6995577d4-7h6zv                   1/1    Running   0             10h
knative-eventing  eventing-controller-86647cbc5b-62tl4     1/1    Running   0             10h
knative-eventing  eventing-webhook-6f48bb5f4c-c5ljb        1/1    Running   0             10h
knative-serving   activator-855b695596-zrfrr               2/2    Running   0             10h
knative-serving   autoscaler-7cbddfc9f7-gjckn              2/2    Running   0             10h
knative-serving   controller-6657c556fd-q728z              2/2    Running   0             10h
knative-serving   domain-mapping-544987775c-bffh5          2/2    Running   0             10h
knative-serving   domainmapping-webhook-6b48bdc856-bmllz   2/2    Running   0             10h
knative-serving   net-istio-controller-6fbdbd9959-bmglm    2/2    Running   0             10h
knative-serving   net-istio-webhook-7d4879cd7f-xwsl5       2/2    Running   0             10h
knative-serving   webhook-665c977469-rw6v6                 2/2    Running   0             10h
kube-system       coredns-787d4945fb-mgpsr                 1/1    Running   1 (10h ago)   10h
kube-system       etcd-minikube                            1/1    Running   2 (52s ago)   10h
kube-system       kube-apiserver-minikube                  1/1    Running   1 (10h ago)   10h
kube-system       kube-controller-manager-minikube         1/1    Running   2 (8h ago)    10h
kube-system       kube-proxy-l4tvb                         1/1    Running   1 (10h ago)   10h
kube-system       kube-scheduler-minikube                  1/1    Running   1 (10h ago)   10h
kube-system       nvidia-device-plugin-daemonset-cd6h8     1/1    Running   0             10h
kube-system       storage-provisioner                      1/1    Running   2 (10h ago)   10h
kubeflow          admission-webhook-deployment-6d48f6f745  1/1    Running   53 (10h ago)  10h
kubeflow          cache-server-6b44c46d47-lvcqr            2/2    Running   0             10h
kubeflow          centraldashboard-f966d7897-ltjhn         2/2    Running   0             10h
kubeflow          jupyter-web-app-deployment-795dcd4c9b-r  2/2    Running   0             10h
kubeflow          katib-controller-746969dc99-2fz29        1/1    Running   53 (10h ago)  10h
kubeflow          katib-db-manager-5ddbffd67-w429n         1/1    Running   0             10h
kubeflow          katib-mysql-66c8cdff4f-mrhz9             1/1    Running   0             10h
kubeflow          katib-ui-58b54d465f-kxmv2                2/2    Running   1 (10h ago)   10h
kubeflow          kserve-controller-manager-96b896c66-84v  2/2    Running   0             10h
kubeflow          kserve-models-web-app-9fbcd79f5-xksvx    2/2    Running   0             10h
kubeflow          kubeflow-pipelines-profile-controller-6  1/1    Running   0             10h
kubeflow          metacontroller-0                         1/1    Running   0             10h
kubeflow          metadata-envoy-deployment-7b49bdb748-tn  1/1    Running   0             10h
kubeflow          metadata-grpc-deployment-6d744c66bb-fkt  2/2    Running   3 (10h ago)   10h
kubeflow          metadata-writer-5bfdbf79b7-b5trj         2/2    Running   0             10h
kubeflow          minio-549846c488-x7jj6                   2/2    Running   0             10h
kubeflow          ml-pipeline-86d69497fc-mvtb9             2/2    Running   53 (10h ago)  10h
kubeflow          ml-pipeline-persistenceagent-5789446f9c  2/2    Running   0             10h
kubeflow          ml-pipeline-scheduledworkflow-fb9fbd76b  2/2    Running   0             10h
kubeflow          ml-pipeline-ui-74fcbdddd9-sm7dd          2/2    Running   0             10h
kubeflow          ml-pipeline-viewer-crd-bdf696cb9-97tks   2/2    Running   1 (10h ago)   10h
kubeflow          ml-pipeline-visualizationserver-845d745  2/2    Running   0             10h
kubeflow          mysql-5f968h4688-dlgv4                   2/2    Running   0             10h
kubeflow          notebook-controller-deployment-576df594  2/2    Running   2 (10h ago)   10h
kubeflow          profiles-deployment-7bc6469cdd-r5vzw     3/3    Running   53 (10h ago)  10h
kubeflow          tensorboard-controller-deployment-84954  3/3    Running   1 (10h ago)   10h
kubeflow          tensorboards-web-app-deployment-74bc589  2/2    Running   0             10h
kubeflow          training-operator-7c5456c65-fsqdr        1/1    Running   0             10h
kubeflow          volumes-web-app-deployment-86dddc89d4-8  2/2    Running   0             10h
kubeflow          workflow-controller-56cc57796-gjtd9      2/2    Running   1 (10h ago)   10h
</code></pre>
<h3 id="heading-how-do-i-setup-a-kubeflow-dashboard"><strong>How do I setup a Kubeflow Dashboard?</strong></h3>
<p>The dashboard is accessed via http requests routed through the <code>istio-ingressgateway</code> service in the <code>istio-system</code> namespace. To forward the port, you use <strong>kubectl</strong>:</p>
<pre><code class="lang-bash">kubectl port-forward svc/istio-ingressgateway -n istio-system 8080:80
</code></pre>
<p>This tells your cluster to listen on port <code>8080</code> locally and forward it to the service on port <code>80</code>. You can then reach the dashboard at <a target="_blank" href="http://localhost:8080/">http://localhost:8080</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711902548206/c0863645-8d65-4f24-a0a5-3d54f6da6a2d.png" alt class="image--center mx-auto" /></p>
<p>The default username is <a target="_blank" href="mailto:user@example.com"><em>user@example.com</em></a> and the password is <em>12341234</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1711902525954/1a26cedf-2199-4926-b337-4b7adb849d7f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-how-do-i-stop-minikube"><strong>How do I stop minikube?</strong></h3>
<p>You can stop everything you’re running by stopping <strong>minikube</strong>:</p>
<pre><code class="lang-bash">minikube stop
</code></pre>
<p>If you want to <strong>delete</strong> your Kubeflow cluster, run:</p>
<pre><code class="lang-bash">minikube delete
</code></pre>
<h3 id="heading-congratulations-youve-done-it">Congratulations!! You've done it.</h3>
<p>There will be a lot of errors that you will encounter while setting it up, so please refer to the <a target="_blank" href="https://www.kubeflow.org/docs/">Kubeflow Docs</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Mamba Models a possible replacement for Transformers?]]></title><description><![CDATA[https://twitter.com/subhrokomol/status/1761889215514808587
 
All AI chatbots right now like Bard or ChatGPT are based on a architecture called Transformers. It is really useful thanks to a special mechanism called self attention that helps the models...]]></description><link>https://suvrakamaldas.hashnode.dev/mamba-models</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/mamba-models</guid><category><![CDATA[Mamba]]></category><category><![CDATA[nlp]]></category><category><![CDATA[ML]]></category><category><![CDATA[AI]]></category><category><![CDATA[research paper writing]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Sat, 13 Jan 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1711918770959/357ff327-a3a7-4102-b6c4-891bdacc7e47.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/subhrokomol/status/1761889215514808587">https://twitter.com/subhrokomol/status/1761889215514808587</a></div>
<p> </p>
<p>All AI chatbots right now like Bard or ChatGPT are based on a architecture called <a target="_blank" href="https://blogs.nvidia.com/blog/what-is-a-transformer-model/">Transformers</a>. It is really useful thanks to a special mechanism called <a target="_blank" href="https://arxiv.org/abs/2308.12874">self attention</a> that helps the models to look back into a set of sequential inputs and perform some pretty insane text completion based on the input you feed it.<br />But for these models even counting and basic arithmetic are a big problem.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709486245054/93e30063-0bb4-4f03-af9d-536176cb19cf.jpeg" alt="AI Chatbot developed by Krutrim AI , India" class="image--center mx-auto" /></p>
<p>Also it hallucinated on larger contexts when you can provide really long contexts like PDF documents (research papers). The exact details are missed and these chatbots give you generalized and oversimplified answers.</p>
<p>To address this problem, researchers made MAMBA (Selective Structured State Space Sequence Models) model. It is basically LSTM + Transformers.</p>
<p>The current SOTA AI models like ChatGPT get exponentially more expensive to train and run the bigger they are. Like <a target="_blank" href="https://twitter.com/finkd123456789">Zuck</a> casually mentioned to buy 600,000 H100s GPUs to train LLMs by the end of 2024. And that goes without saying that these models are not suitable for scaling up even more.</p>
<p><strong>This is majorly because of it's own attention mechanism where they need to note the positions of all texts in the whole context which makes longer texts harder to work with.</strong></p>
<p>So some big brain researchers from CMU and Princeton dug up and old architecture called state space models and refine it to create something called the S4 model, short for structured state space sequence models and implemented it into something called Mamba.</p>
<p>First, it not only solves the scaling problem that the transformers have, where the computation doesn't scale exponentially and only linearly, but second, it is not using the attention mechanism and can still recall any details you provided within full precision. For a more technical perspective, it is the <strong>first alternative model</strong> architecture to achieve benchmarks that surpasses the strongest transformer recipe.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709487261238/f5996c8a-5964-47bb-9b2f-1ed8835ffc3b.jpeg" alt="performance of mamba vs transformers" class="image--center mx-auto" /></p>
<p>For example if you are going to a party - everyone needs to meet everyone else, all relations between each other. That's how transformers are working.<br />But think of a situation when you are attending a party and everyone just knows the party host, so you just have to meet the host, as he/she knows everyone and their relations among each other - that's how Mamba works.</p>
<p>Mamba save you so much more time when you increase the amount of people attending the party. Fundamentally the S4 model is a completely different architecture from the transformers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709487662186/d464a495-efd7-4944-9ed1-dc95add5c68d.webp" alt class="image--center mx-auto" /></p>
<p>Mamba is more similar to LSTM and recurrent models. LSTM needs the output from the previous hidden state and the global input to generate the next prediction. Hence every layers needs to wait for it's previous layer to finish it's prediction to proceede, which makes it extremely slow.</p>
<p>In the S4 models Mamba uses, each hidden state is only dependent on the global input, so there's no wasting time waiting for the result from the last layer and whatnot. On top of having non linearity between the hidden states, it makes the calculations insanely fast. We can just finish all the matrix multiplications at once.</p>
<p>This improved the quadratic scaling that the transformers has from</p>
<p>$$from O(n)^2 to O(n)$$</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1709534780123/2ffe2bf6-51ff-44f0-b601-d38e2ba1c350.webp" alt="mamba outperforms in all categories" class="image--center mx-auto" /></p>
<p>Let's talk about similar models like Vision Mamba in another blog, stay tuned.</p>
<p>Refer to this <a target="_blank" href="https://github.com/yyyujintang/Awesome-Mamba-Papers?tab=readme-ov-file">GitHub Repository</a> for latest updates in Mamba Papers</p>
]]></content:encoded></item><item><title><![CDATA[What is Sentiment Analysis?]]></title><description><![CDATA[Hey Siri, how are my emotions today? How am I doing today?
These seem like ridiculous questions but with the advancements in Sentiment Analysis in Machine Learning, our machines are getting closer to answering these questions.
Let's get straight into...]]></description><link>https://suvrakamaldas.hashnode.dev/what-is-sentiment-analysis</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/what-is-sentiment-analysis</guid><category><![CDATA[Sentiment analysis]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Mon, 05 Jun 2023 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/hRdVSYpffas/upload/v1660032108574/OE-lJ5yz8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-hey-siri-how-are-my-emotions-today-how-am-i-doing-today">Hey Siri, how are my emotions today? How am I doing today?</h2>
<p>These seem like ridiculous questions but with the advancements in Sentiment Analysis in Machine Learning, our machines are getting closer to answering these questions.</p>
<h3 id="heading-lets-get-straight-into-examples">Let's get straight into examples!</h3>
<p>If I would have asked you to rate a sentence out of 10, with 0 being negative and 10 being positive. How would you do that?</p>
<p>For example, have a look at these pictures -</p>
<p>Pretty positive right? Let's give it around 10!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660287575891/SgduAaBth.png" alt="image.png" /></p>
<p>Now have a look at this! Positive, but liking a movie is not as great as loving a movie! We know this right?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660287634250/UVCr8x5bu.png" alt="image.png" /></p>
<p>Now here's one more. This clearly states a very negative sentence, so that's totally 0.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660287654679/6b3iHieWq.png" alt="image.png" /></p>
<p>Sentiment Analysis is simply using Machine Learning to teach Computers to do just this! Extract the sentiments out of our sentences or the emotions behind it!</p>
<h2 id="heading-the-most-pressing-question-is-whats-the-use-of-it">The most pressing question is what's the use of it?</h2>
<p>Well, there are many uses of it but one of the major things Sentiment Analysis will be used in is <strong>Controlling the Radicalization of the Internet</strong>. This is a very powerful tool that can be used by democracies around the world to make the internet a safer place! But also, at the same time this can be used to press the voices of some people that the Government doesn't like! So that's a Double Edged sword, you can use it the way you like it. Okay now let's get to Coding!</p>
<h2 id="heading-the-code">The Code!</h2>
<p>We will be using Jupyter Notebooks to build our Machine Learning Model.</p>
<h3 id="heading-installing-and-importing-dependencies">Installing and Importing Dependencies</h3>
<p>Installing PyTorch- To know more about it refer to my next blog</p>
<pre><code class="lang-plaintext">!pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
</code></pre>
<p>Installing some other stuff!</p>
<pre><code class="lang-plaintext">
!pip install transformers requests beautifulsoup4 pandas numpy
</code></pre>
<p><strong>Transformers</strong> helps us to easily import, download and install our NLP model.</p>
<p><strong>Requests</strong> are going to help us in making a request to the site we will be scraping for the testing data.</p>
<p><strong>Beautiful Soup</strong> as you all know is used for web scraping to extract the data that we actually need - is taught in basics of python programming.</p>
<p><strong>Pandas</strong> help us to structure the data in a format that makes it actually easy for us to work with.</p>
<p><strong>NumPy</strong> helps us to work with arrays - we will understand its needs when we deep dive into it.</p>
<h3 id="heading-importing-the-dependencies">Importing the dependencies.</h3>
<pre><code class="lang-plaintext">from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import requests
from bs4 import BeautifulSoup
import re
</code></pre>
<p>Importing the tokenizer from Transformers will help us to pass through a string and convert that into a sequence of numbers that we can pass through our NLP model.</p>
<p>Auto Model for Sequence Classification - This will give us the architecture from transformers to be able to load in our NLP model.</p>
<p>Next, we are importing PyTorch, requests, Beautiful Soup. Re is used for creating a regex function to be able to extract a specific comment we want.</p>
<h3 id="heading-setting-up-the-model">Setting up the Model</h3>
<pre><code class="lang-plaintext">
tokenizer = AutoTokenizer.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment')

model = AutoModelForSequenceClassification.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment')
</code></pre>
<p>In the first line we are loading in our tokenizer and then in the next line we are loading in our model.</p>
<p>So, the first line says about creating a tokenizer that is coming from a pre trained model. The words within quotes are the link of the model that is present in the Hugging Face website.</p>
<p>In the next line we are setting up our model = Auto model Sequence Classification which we imported earlier and we are using the <strong>from pretrained</strong> method to be able to load the pretrained model.</p>
<h3 id="heading-encode-and-calculate-sentiment">Encode and Calculate Sentiment</h3>
<pre><code class="lang-plaintext">tokens = tokenizer. Encode ('I hated this, absolutely the worst', return_tensocould've)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660292215581/xnuIfRX_9.png" alt="image.png" /></p>
<p>So, the Tokenizer has just converted the tokens into numbers.  </p>
<p>I will share more about this in the next blog.</p>
]]></content:encoded></item><item><title><![CDATA[Time Series Forecasting Using Deep AR and Gluton TS]]></title><description><![CDATA[Time series forecasting can be a difficult task for many businesses. But with the help of Deep AR and Gluton TS, you can quickly and accurately make predictions about the future of your business using time series data. Read on to find out more about ...]]></description><link>https://suvrakamaldas.hashnode.dev/time-series-forecasting-using-deep-ar-and-gluton-ts</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/time-series-forecasting-using-deep-ar-and-gluton-ts</guid><category><![CDATA[time series]]></category><category><![CDATA[machine learning models]]></category><category><![CDATA[Deep Learning]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Tue, 03 Jan 2023 17:16:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/5b289bce394a7f0582e6b73b606ec8d6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Time series forecasting can be a difficult task for many businesses. But with the help of Deep AR and Gluton TS, you can quickly and accurately make predictions about the future of your business using time series data. Read on to find out more about how these two powerful tools can help you make important decisions about your future.</p>
<h2 id="heading-introduction-to-time-series-forecasting">Introduction to Time Series Forecasting</h2>
<p>Time Series Forecasting Using Deep AR and Gluton TS</p>
<p>In this blog article, we will introduce you to time series forecasting using two deep learning architectures: DeepAR and GluonTS. We will cover the basics of each approach and show you how to get started with each one.</p>
<p>DeepAR is a neural network architecture for time series forecasting that is based on recurrent neural networks (RNNs). DeepAR has been shown to outperform other traditional time series forecasting methods, such as autoregressive moving average (ARMA) models, in terms of accuracy.</p>
<p>GluonTS is a deep learning toolkit that makes it easy to build time series models. GluonTS provides ready-to-use components that can be used to build complex models with minimal effort. In addition, GluonTS comes with pre-trained models that can be fine-tuned for your specific problem.</p>
<p>So, let's get started with our introduction to time series forecasting using DeepAR and GluonTS!</p>
<h2 id="heading-bias-variance-tradeoff-and-overfitting">Bias-Variance Tradeoff and Overfitting</h2>
<p>Bias-variance tradeoff is a fundamental problem in machine learning. It occurs when our models are too simple (high bias) or too complex (high variance). This tradeoff is often referred to as the “dilemma” because we can never have both low bias and low variance.</p>
<p>Overfitting occurs when our models are too complex. This causes them to learn the noise in the data rather than the signal. Overfitting is a major problem in machine learning because it leads to poor generalization performance on out-of-sample data.</p>
<p>The goal of any machine learning algorithm is to find a balance between bias and variance so that we can minimize both and achieve good generalization performance. However, this is often easier said than done. In practice, we usually have to sacrifice one for the other. For example, if we want low bias, we might have to accept high variance. Or if we want low variance, we might have to accept high bias.</p>
<p>The deep AR model proposed by Google DeepMind addresses this issue by using a deep neural network to automatically learn the appropriate level of complexity for the time series data. This results in a model with much lower variance and better generalization performance.</p>
<p>Gluton TS is another approach that tries to address the issue of overfitting in time series forecasting. It does this by first training a base model on the data and then training a second model that learns how to correct the errors made by the</p>
<h2 id="heading-fixed-effect-model">Fixed Effect Model</h2>
<p>A fixed effect model is a statistical model that estimates the effects of one or more variables on a response variable. The model includes a fixed intercept and slope for each predictor variable. Fixed effect models are used when the predictor variables are fixed, such as in an experiment.</p>
<p>In time series forecasting, a fixed effect model can be used to identify the trend and seasonality in the data. The model can also be used to forecast future values of the response variable.</p>
<h2 id="heading-arma-model">ARMA Model</h2>
<p>An ARMA model is a statistical model that combines an autoregressive (AR) model with a moving average (MA) model. These models are used to forecast future values of time series data, such as stock prices, based on past values.</p>
<p>The ARMA model is a generalization of the AR and MA models, which are both special cases of the ARMA model. The ARMA model is also known as the Box-Jenkins model, after the statisticians who developed it.</p>
<p>The ARMA model is specified by two parameters: the order of the AR part of the model, and the order of the MA part of the model. For example, an ARMA(1,1) model would be an autoregressivemodel with one lag and a moving average model with one lag.</p>
<p>The coefficients in an ARMA model are estimated using maximum likelihood estimation (MLE). Once estimated, the fitted values from the model can be used to forecast future values of the time series data.</p>
<h2 id="heading-autoregressive-neural-network-ar-method-for-arma-models">Autoregressive Neural Network (AR) Method for ARMA Models</h2>
<p>The autoregressive neural network (AR) model is a type of artificial neural network that can be used for time series forecasting. The AR model is based on the idea that the past values of a time series can be used to predict future values.</p>
<p>The AR model can be used to forecast time series data such as stock prices, economic indicators, and weather patterns. The AR model is a type of recurrent neural network (RNN), which means that it can handle data with temporal dependencies.</p>
<p>The AR model is trained using a training dataset, which contains historical data points. The model then makes predictions for future data points based on the patterns it has learned from the training dataset.</p>
<p>Gluton TS is a deep learning platform that can be used to train autoregressive models. Gluton TS offers an easy-to-use interface and powerful tools for data preprocessing, model training, and prediction tuning.</p>
<h2 id="heading-glutonts-for-ar-models">GlutonTS for AR Models</h2>
<p>If you're looking to get started with time series forecasting using deep learning, then you'll want to check out GlutonTS. GlutonTS is a library for training and deploying autoregressive (AR) models.</p>
<p>AR models are a type of neural network that are well-suited for time series data. They are able to capture the dependencies between successive timesteps in a series, making them ideal for forecasting tasks.</p>
<p>GlutonTS makes it easy to train and deploy AR models. It provides a simple API for building models and training on time series data. It also includes support for popular machine learning frameworks such as TensorFlow and PyTorch.</p>
<p>If you're interested in time series forecasting, then you should definitely check out GlutonTS. It's a great way to get started with deep learning for this task. Happy learning!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We've discussed how deep AR and Gluton TS can be used for time series forecasting. Deep AR is a powerful tool which allows us to model complex non-linear relations, while Gluton TS helps make the process of data preparation and feature engineering easier. Together, these two tools provide a powerful combination for accurate predictions in time series forecasting applications. We hope this article has shown you just how useful they can be in helping you achieve reliable forecasts.</p>
]]></content:encoded></item><item><title><![CDATA[Uncovering the Magic of Image Detection with Python, OpenCV, & TensorFlow!]]></title><description><![CDATA[As a developer, you may be familiar with the term "image detection." Image detection is a process in which a computer can detect objects in an image or video. This process is becoming increasingly popular in the field of computer vision, as it allows...]]></description><link>https://suvrakamaldas.hashnode.dev/uncovering-the-magic-of-image-detection-with-python-opencv-tensorflow</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/uncovering-the-magic-of-image-detection-with-python-opencv-tensorflow</guid><category><![CDATA[object detection ]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[opencv]]></category><category><![CDATA[TensorFlow]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Tue, 03 Jan 2023 12:00:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672766378034/da3e39bb-d4f0-4f79-ae38-38b8de84ce56.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672746907181/4032a054-fa8f-4d7b-a5ed-8ffec66401cb.png" alt class="image--center mx-auto" /></p>
<p>As a developer, you may be familiar with the term "image detection." Image detection is a process in which a computer can detect objects in an image or video. This process is becoming increasingly popular in the field of computer vision, as it allows machines to identify objects in images or videos with great accuracy.</p>
<p>In this article, I'm going to take you on a journey to uncover the magic of image detection with Python, OpenCV, and TensorFlow. We'll start with a brief introduction to image detection and then delve into the overviews of OpenCV, TensorFlow, object detection, and the various object detection algorithms. Then, we'll discuss how to use Python for image detection and explore deep learning and object detection. Finally, we'll look at some of the object detection models and algorithms and explore the various applications of object detection in the real world.</p>
<h2 id="heading-introduction-to-object-detection">Introduction to Object Detection</h2>
<p>Image detection is the process of detecting objects in an image or video. It is an important part of computer vision, a field of artificial intelligence that deals with understanding images and videos. Image detection can be used for a variety of purposes, such as security, medical imaging, and autonomous vehicles.</p>
<p>Image detection involves identifying objects in an image or video. The objects can be anything, from cars and people to animals and buildings. The first step in the process is to extract the features (edges, contours, etc.) of the objects in the image. Then, a machine learning algorithm is used to identify the objects in the image.</p>
<p>The main types of image detection algorithms are classification, localization, and object detection. Classification algorithms are used to classify objects in an image into different categories. Localization algorithms are used to locate the position of an object in an image. Finally, object detection algorithms are used to identify objects and their locations in an image.</p>
<h2 id="heading-overview-of-opencv">Overview of OpenCV</h2>
<p>OpenCV (Open Source Computer Vision Library) is a popular library for image processing and computer vision. It is open source and has been around since 2000. It is written in C++, but can be used with Python, Java, and other programming languages.</p>
<p>OpenCV is used for a variety of tasks, such as facial recognition, object tracking, and object detection. It has a large collection of algorithms and tools for image processing and computer vision. It also has a good set of tutorials and documentation which makes it easier to learn and use.</p>
<h2 id="heading-overview-of-object-detection">Overview of Object Detection</h2>
<p>Object detection is the process of identifying objects in an image or video. It is a form of computer vision which is used to detect objects in images or videos. It is an important part of artificial intelligence as it allows machines to recognize and locate objects in images and videos.</p>
<p>Object detection algorithms can be used for a variety of tasks, such as facial recognition, object tracking, and autonomous vehicle navigation. There are various object detection algorithms, such as classification, localization, and object detection. Classification algorithms are used to classify objects in an image into different categories. Localization algorithms are used to locate the position of an object in an image. Finally, object detection algorithms are used to identify objects and their locations in an image.</p>
<h2 id="heading-types-of-object-detection-algorithms">Types of Object Detection Algorithms</h2>
<p>There are various types of object detection algorithms, each of which has its own advantages and disadvantages. Some of the most popular object detection algorithms are:</p>
<ul>
<li><p>Haar-Cascade: This is an old algorithm which uses a cascade of Haar features to detect objects in an image. It is used for facial recognition and object detection.</p>
</li>
<li><p>HOG (Histogram of Oriented Gradients): This is a feature descriptor which is used to detect objects in an image. It is used in object detection and facial recognition.</p>
</li>
<li><p>SSD (Single Shot Detection): This is a deep learning-based algorithm which uses a single neural network to detect objects in an image. It is used for object detection and facial recognition.</p>
</li>
<li><p>YOLO (You Only Look Once): This is a deep learning-based algorithm which uses a single neural network to detect objects in an image. It is used for object detection and facial recognition.</p>
</li>
<li><p>R-CNN (Region-based Convolutional Neural Network): This is a deep learning-based algorithm which uses a region-based convolutional neural network to detect objects in an image. It is used for object detection and facial recognition.</p>
</li>
<li><p>Fast R-CNN: This is a deep learning-based algorithm which uses a region-based convolutional neural network to detect objects in an image. It is used for object detection and facial recognition.</p>
</li>
<li><p>Faster R-CNN: This is a deep learning-based algorithm which uses a region-based convolutional neural network to detect objects in an image. It is used for object detection and facial recognition.</p>
</li>
</ul>
<p>One of the main challenges in object detection is the large variability in object appearance and scale. To handle this, many object detection models use feature pyramids, which allow the model to detect objects at multiple scales.</p>
<p>In TensorFlow, the Object Detection API provides a collection of pre-trained models that are trained on the COCO dataset (Common Objects in Context) and are able to detect a wide range of objects. To use one of these models, you will need to install the Object Detection API and download the model checkpoint file.</p>
<p>Here is an example of how to use the Object Detection API to detect objects in an image:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">from</span> object_detection.utils <span class="hljs-keyword">import</span> label_map_util
<span class="hljs-keyword">from</span> object_detection.utils <span class="hljs-keyword">import</span> visualization_utils <span class="hljs-keyword">as</span> vis_util

<span class="hljs-comment"># Load the label map</span>
label_map = label_map_util.load_labelmap(<span class="hljs-string">'path/to/label_map.pbtxt'</span>)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=<span class="hljs-number">90</span>, use_display_name=<span class="hljs-literal">True</span>)
category_index = label_map_util.create_category_index(categories)

<span class="hljs-comment"># Load the model</span>
detection_model = tf.keras.models.load_model(<span class="hljs-string">'path/to/model.h5'</span>)

<span class="hljs-comment"># Load the image</span>
image = tf.keras.preprocessing.image.load_img(<span class="hljs-string">'path/to/image.jpg'</span>)
image_np = tf.keras.preprocessing.image.img_to_array(image)

<span class="hljs-comment"># Expand the dimensions of the image</span>
image_np_expanded = np.expand_dims(image_np, axis=<span class="hljs-number">0</span>)

<span class="hljs-comment"># Perform object detection</span>
output_dict = detection_model(image_np_expanded)

<span class="hljs-comment"># Get the detections</span>
detections = output_dict[<span class="hljs-string">'detection_boxes'</span>]
scores = output_dict[<span class="hljs-string">'detection_scores'</span>]

<span class="hljs-comment"># Visualize the detections</span>
vis_util.visualize_boxes_and_labels_on_image_array(
    image_np,
    detections,
    scores,
    category_index,
    instance_masks=output_dict.get(<span class="hljs-string">'detection_masks'</span>),
    use_normalized_coordinates=<span class="hljs-literal">True</span>,
    min_score_thresh=<span class="hljs-number">0.8</span>,
    max_boxes_to_draw=<span class="hljs-number">20</span>
)

<span class="hljs-comment"># Display the image</span>
plt.figure(figsize=(<span class="hljs-number">12</span>, <span class="hljs-number">8</span>))
plt.imshow(image_np)
plt.show()
</code></pre>
<h2 id="heading-object-detection-applications">Object Detection Applications</h2>
<p>Object detection is used for a variety of applications, such as facial recognition, object tracking, and autonomous vehicle navigation. It is also used for security purposes, such as detecting intruders in a building or detecting suspicious behavior in a crowd.</p>
<p>Object detection can also be used to create object recognition applications, such as a smartphone app that can recognize objects in an image. It can also be used to create medical imaging applications, such as an application which can detect tumors in an X-ray or MRI scan.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, I have taken you on a journey to uncover the magic of image detection with Python, OpenCV, and TensorFlow. We started with an introduction to image detection and then discussed the overviews of OpenCV, TensorFlow, object detection, and the various object detection algorithms. Then, we discussed how to use Python for image detection and explored deep learning and object detection. Finally, we looked at some of the object detection models and algorithms and explored the various applications of object detection in the real world.</p>
<p>Object detection is an important part of computer vision and artificial intelligence. It is a powerful tool which can be used for a variety of tasks, such as facial recognition, object tracking, and autonomous vehicle navigation. With the help of Python, OpenCV, and TensorFlow, image detection can be used to solve real-world problems.</p>
<p>So, if you're looking to get started with image detection, then this article has provided you with the necessary information to get started. Now, all you have to do is take the plunge and start exploring the magic of image detection with Python, OpenCV, and TensorFlow!</p>
<p>CTA: Real time object detection computer vision</p>
]]></content:encoded></item><item><title><![CDATA[Reaching New Heights with Image Classification and Deep Learning!]]></title><description><![CDATA[Image classification and deep learning are two powerful tools that can help you reach new heights in data science. By combining these two technologies, you can create powerful and accurate models that can solve complex problems. In this blog, we’ll d...]]></description><link>https://suvrakamaldas.hashnode.dev/reaching-new-heights-with-image-classification-and-deep-learning</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/reaching-new-heights-with-image-classification-and-deep-learning</guid><category><![CDATA[image classification]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Tue, 03 Jan 2023 11:19:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672766336702/82732116-37ee-484a-b1a6-c476485c7829.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672743299580/163c2682-9d1e-4351-b444-df337bb1c550.png" alt class="image--center mx-auto" /></p>
<p>Image classification and deep learning are two powerful tools that can help you reach new heights in data science. By combining these two technologies, you can create powerful and accurate models that can solve complex problems. In this blog, we’ll discuss what image classification is, the benefits of image classification, image classification with deep learning, and best practices for image classification.</p>
<h3 id="heading-what-is-image-classification">What is Image Classification</h3>
<p>Image classification is a computer vision technique that uses machine learning algorithms to identify and classify objects in an image. It can be used for a wide range of applications, from facial recognition to medical diagnosis. Image classification utilizes a variety of algorithms, including convolutional neural networks (CNNs), support vector machines (SVMs), and random forests.</p>
<p>In image classification, images are presented to a computer algorithm, which then performs a series of computations to identify objects in the image. The algorithm then assigns a label or class to each object in the image. For example, an algorithm may be trained to recognize cats, dogs, and birds in a given image.</p>
<p>The process of image classification can be broken down into two parts: feature extraction and classification. Feature extraction is the process of extracting the objects in an image that are relevant to the task at hand. This involves identifying edges, lines, shapes, and other features that can be used to identify an object. The classification process is the process of assigning labels to the extracted features. This can be done manually or with the help of a machine learning algorithm.</p>
<h3 id="heading-benefits-of-image-classification">Benefits of Image Classification</h3>
<p>Image classification has many benefits, including:</p>
<ul>
<li><p>Improved accuracy: Image classification algorithms can be more accurate than human annotators, as they are trained to recognize specific features.</p>
</li>
<li><p>Faster processing: Image classification algorithms can process images faster than humans, as they don’t need to manually search for objects in an image.</p>
</li>
<li><p>Cost savings: Automated image classification algorithms can save companies time and money by eliminating the need for manual annotation.</p>
</li>
<li><p>Automation: Image classification algorithms can be used to automate tasks such as facial recognition, object detection, and medical diagnosis.</p>
</li>
<li><p>Scalability: Image classification algorithms can be scaled to process large amounts of data quickly and accurately.</p>
</li>
</ul>
<h3 id="heading-tensorflow-transfer-learning">Tensorflow Transfer Learning</h3>
<p>TensorFlow is a popular open-source machine learning library that can be used for image classification. It provides a variety of tools and algorithms that can be used to train and deploy image classification models. One of the most powerful tools available in TensorFlow is transfer learning.</p>
<p>Transfer learning is a technique that allows you to take a model that has already been trained on a large dataset and fine-tune it for your own dataset. This can be useful if you don’t have access to a large dataset, or if you want to improve the accuracy of your model. Transfer learning can also save you time, as you don’t have to train a new model from scratch.</p>
<h3 id="heading-image-classification-with-deep-learning-tools">Image Classification with Deep Learning Tools</h3>
<p>There are a variety of deep learning tools available that can be used for image classification. These tools make it easy to train and deploy image classification models without having to write your own code. Some of the most popular deep learning tools include TensorFlow, Keras, Caffe, and PyTorch.</p>
<p>TensorFlow is a popular open-source machine learning library that can be used for image classification. It provides a variety of tools and algorithms that can be used to train and deploy image classification models.</p>
<p>Keras is another popular deep learning library that can be used for image classification. It provides a high-level API that makes it easy to train and deploy image classification models.</p>
<p>Caffe is a deep learning framework that can be used for image classification. It provides a flexible architecture that makes it easy to deploy and scale image classification models.</p>
<p>PyTorch is a popular deep learning library that can be used for image classification. It provides a library of algorithms and tools that make it easy to train and deploy image classification models.</p>
<h3 id="heading-demonstration">Demonstration</h3>
<p>To start, we will need to install TensorFlow 2 and any other required libraries. You can install TensorFlow by running the following command:</p>
<pre><code class="lang-python">
pip install tensorflow
</code></pre>
<p>Next, we will need to download and extract a pre-trained model. TensorFlow provides a number of pre-trained models in its <a target="_blank" href="https://www.tensorflow.org/hub"><strong>TensorFlow Hub</strong></a> library. For this example, we will use the MobileNetV2 model, which has been trained on the ImageNet dataset. You can download and extract the model by running the following code:</p>
<pre><code class="lang-python">
<span class="hljs-keyword">import</span> tensorflow <span class="hljs-keyword">as</span> tf
<span class="hljs-keyword">import</span> tensorflow_hub <span class="hljs-keyword">as</span> hub

model = tf.keras.Sequential([
    hub.KerasLayer(<span class="hljs-string">"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"</span>,
                   input_shape=(<span class="hljs-number">224</span>, <span class="hljs-number">224</span>, <span class="hljs-number">3</span>))
])
</code></pre>
<p>Next, we will need to download and prepare our dataset. For this example, we will use the <a target="_blank" href="https://www.kaggle.com/c/dogs-vs-cats"><strong>Cats vs Dogs</strong></a> dataset from Kaggle. This dataset contains 25,000 images of cats and dogs, split into training and validation sets.</p>
<p>After downloading and extracting the dataset, we can use the following code to load the images and prepare them for training:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt

<span class="hljs-comment"># Load the images</span>
X = []
Y = []
<span class="hljs-keyword">for</span> filename <span class="hljs-keyword">in</span> os.listdir(<span class="hljs-string">"train"</span>):
    label = filename.split(<span class="hljs-string">"."</span>)[<span class="hljs-number">0</span>]
    <span class="hljs-keyword">if</span> label == <span class="hljs-string">"cat"</span>:
        Y.append(<span class="hljs-number">0</span>)
    <span class="hljs-keyword">else</span>:
        Y.append(<span class="hljs-number">1</span>)
    image = plt.imread(<span class="hljs-string">"train/"</span> + filename)
    X.append(image)
X = np.array(X)
Y = np.array(Y)

<span class="hljs-comment"># Split the data into train and validation sets</span>
<span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split
X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=<span class="hljs-number">0.2</span>)
</code></pre>
<h3 id="heading-heres-another-example">Here's another example!</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> keras.applications <span class="hljs-keyword">import</span> VGG16
<span class="hljs-keyword">from</span> keras.preprocessing.image <span class="hljs-keyword">import</span> ImageDataGenerator
<span class="hljs-keyword">from</span> keras.layers <span class="hljs-keyword">import</span> Dense, Dropout, Flatten
<span class="hljs-keyword">from</span> keras <span class="hljs-keyword">import</span> Model
<span class="hljs-keyword">from</span> keras <span class="hljs-keyword">import</span> optimizers

<span class="hljs-comment"># Load the VGG16 model</span>
base_model = VGG16(weights=<span class="hljs-string">'imagenet'</span>, include_top=<span class="hljs-literal">False</span>, input_shape=(<span class="hljs-number">224</span>, <span class="hljs-number">224</span>, <span class="hljs-number">3</span>))

<span class="hljs-comment"># Add a new classifier layer on top of the base model</span>
x = base_model.output
x = Flatten()(x)
x = Dense(<span class="hljs-number">1024</span>, activation=<span class="hljs-string">'relu'</span>)(x)
x = Dropout(<span class="hljs-number">0.5</span>)(x)
predictions = Dense(<span class="hljs-number">10</span>, activation=<span class="hljs-string">'softmax'</span>)(x)
model = Model(inputs=base_model.input, outputs=predictions)

<span class="hljs-comment"># Freeze the base model layers</span>
<span class="hljs-keyword">for</span> layer <span class="hljs-keyword">in</span> base_model.layers:
    layer.trainable = <span class="hljs-literal">False</span>

<span class="hljs-comment"># Compile the model</span>
model.compile(optimizer=optimizers.SGD(lr=<span class="hljs-number">0.0001</span>, momentum=<span class="hljs-number">0.9</span>), loss=<span class="hljs-string">'categorical_crossentropy'</span>, metrics=[<span class="hljs-string">'accuracy'</span>])

<span class="hljs-comment"># Train the model using the ImageDataGenerator</span>
train_datagen = ImageDataGenerator(rescale=<span class="hljs-number">1.</span>/<span class="hljs-number">255</span>,
                                   shear_range=<span class="hljs-number">0.2</span>,
                                   zoom_range=<span class="hljs-number">0.2</span>,
                                   horizontal_flip=<span class="hljs-literal">True</span>)

test_datagen = ImageDataGenerator(rescale=<span class="hljs-number">1.</span>/<span class="hljs-number">255</span>)

train_generator = train_datagen.flow_from_directory(
        <span class="hljs-string">'data/train'</span>,
        target_size=(<span class="hljs-number">224</span>, <span class="hljs-number">224</span>),
        batch_size=<span class="hljs-number">32</span>,
        class_mode=<span class="hljs-string">'categorical'</span>)

validation_generator = test_datagen.flow_from_directory(
        <span class="hljs-string">'data/val'</span>,
        target_size=(<span class="hljs-number">224</span>, <span class="hljs-number">224</span>),
        batch_size=<span class="hljs-number">32</span>,
        class_mode=<span class="hljs-string">'categorical'</span>)

model.fit_generator(
        train_generator,
        steps_per_epoch=<span class="hljs-number">100</span>,
        epochs=<span class="hljs-number">10</span>,
        validation_data=validation_generator,
        validation_steps=<span class="hljs-number">50</span>)
</code></pre>
<h3 id="heading-tips-for-image-classificatoin">Tips for Image Classificatoin</h3>
<p>There are a few tips that can help you improve the accuracy of your image classification models:</p>
<ul>
<li><p>Use data augmentation: Data augmentation is a technique that can be used to increase the amount of data available for training. This can be useful if you don’t have access to a large dataset.</p>
</li>
<li><p>Utilize transfer learning: Transfer learning is a powerful technique that can be used to improve the accuracy of your model.</p>
</li>
<li><p>Use a balanced dataset: It’s important to use a balanced dataset when training your model. This means that the dataset should contain an equal number of samples for each class.</p>
</li>
<li><p>Use a large dataset: The larger the dataset, the better the accuracy of your model.</p>
</li>
</ul>
<h3 id="heading-best-practices-for-image-classification">Best Practices for Image Classification</h3>
<p>When it comes to creating accurate image classification models, there are a few best practices that you should follow:</p>
<ul>
<li><p>Choose the right algorithm: Not all algorithms are suitable for all tasks. Make sure to choose an algorithm that is suitable for your task.</p>
</li>
<li><p>Use a balanced dataset: As mentioned above, it’s important to use a balanced dataset when training your model.</p>
</li>
<li><p>Utilize transfer learning: Transfer learning can be a powerful tool for improving the accuracy of your model.</p>
</li>
<li><p>Use data augmentation: Data augmentation can be used to increase the amount of data available for training.</p>
</li>
<li><p>Tune your hyperparameters: Hyperparameters are parameters that control the behaviour of your model. Tuning these parameters can help you improve the accuracy of your model.</p>
</li>
</ul>
<h3 id="heading-challenges-of-image-classification">Challenges of Image Classification</h3>
<p>Image classification is a complex task that can be difficult to get right. Some of the challenges that you may face when creating an image classification model include:</p>
<ul>
<li><p>Overfitting: Overfitting occurs when the model starts to learn the noise in the data instead of the underlying patterns. This can lead to poor performance on new data.</p>
</li>
<li><p>Unbalanced datasets: Unbalanced datasets can lead to biased models that don’t generalize well.</p>
</li>
<li><p>Poorly labeled data: Poorly labeled data can lead to inaccurate models.</p>
</li>
<li><p>Poorly chosen algorithms: Choosing the wrong algorithm for your task can lead to poor performance.</p>
</li>
<li><p>Lack of data: If you don’t have access to enough data, it can be difficult to train an accurate model.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Image classification and deep learning can be powerful tools for solving complex problems. By combining these two technologies, you can create powerful and accurate models that can identify objects in an image with high accuracy. In this blog, we discussed what image classification is, the benefits of image classification, image classification with deep learning, and best practices for image classification. We also discussed some of the challenges that you may face when creating an image classification model.</p>
<p>If you’re looking to create an accurate image classification model, it’s important to choose the right algorithm, use a balanced dataset, and utilize transfer learning. And remember to use data augmentation to increase the amount of data available for training. With these tips, you can create powerful and accurate image classification models that can solve complex problems.</p>
<p>Image classification and deep learning are two powerful tools that can help you reach new heights in data science. So, what are you waiting for? Start experimenting with image classification and deep learning today and see what you can create!</p>
]]></content:encoded></item><item><title><![CDATA[Basics of Machine Learning]]></title><description><![CDATA[So, what is Machine Learning and where is it used in real life?
Let me start with a very familiar example. It's Google Search!
Have you seen the Documentary The Social Dilemma in Netflix? Go watch it! 

The documentary tells you the story about how b...]]></description><link>https://suvrakamaldas.hashnode.dev/basics-of-machine-learning</link><guid isPermaLink="true">https://suvrakamaldas.hashnode.dev/basics-of-machine-learning</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[basics]]></category><category><![CDATA[Reinforcement Learning]]></category><category><![CDATA[Supervised learning]]></category><category><![CDATA[Unsupervised learning]]></category><dc:creator><![CDATA[Suvrakamal Das]]></dc:creator><pubDate>Thu, 28 Jul 2022 09:41:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/SyzQ5aByJnE/upload/v1659001185156/hZ8HgoRIL.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-so-what-is-machine-learning-and-where-is-it-used-in-real-life">So, what is Machine Learning and where is it used in real life?</h1>
<h3 id="heading-let-me-start-with-a-very-familiar-example-its-google-search">Let me start with a very familiar example. It's Google Search!</h3>
<p>Have you seen the Documentary <strong>The Social Dilemma</strong> in <strong>Netflix</strong>? Go watch it! </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658994838448/mukiiHGO_.jpg" alt="the-social-dilemma-1601892855.jpg" /></p>
<p>The documentary tells you the story about how big tech companies collect data from you and use it to show you advertisements. But this is just the tip of Ice Berg. They predict your next move! 
When you go to google and type "climate change is" you will see the results are different for different people across the world.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658995203944/9y2tr-ChV.png" alt="image.png" /></p>
<p>Your <strong>Twitter, LinkedIn and Instagram</strong> feed are different from mine! And that's okay because you and I may not like the same thing. 
Well, but how did Instagram or LinkedIn learn that? <strong>Well, that's Machine Learning! </strong>
They learnt from your previous actions and the accounts you followed, the number of times you chatted with someone or the amount of time you took to look in a certain post. Everything is tracked and recorded!</p>
<h2 id="heading-what-is-machine-learning-made-off">What is Machine Learning made off??</h2>
<p>Well Machine Learning, as the name suggests, is a computer program that is made up of a number of algorithms which predict the next move based on the previous data given to it. </p>
<h3 id="heading-lets-start-with-an-example">Let's start with an example!</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658996027618/HD5_bUDN5.jpg" alt="32f24381b05fcf53d8088c98963fe326.jpg" /></p>
<p>Suppose somehow, I built a Machine Learning Model to predict <strong>Cats</strong>. The model is 70% accurate i.e. If I show the model a picture of a cat, it will be able to tell me with 70% accuracy whether the image is of a cat or not! 
So, I train the model a bit more and it learns from the data I feed to it. Now the model is 99% accurate and now it can detect a cat from any image. This is just a small example of how ML models work. </p>
<p>In real life, ML models have a variety of use cases. It can be used to <strong>predict new chemical combinations for new medicines, stock prices, you next search in google, or the next post you're going to see in Instagram</strong></p>
<h2 id="heading-now-lets-talk-about-types-of-machine-learning">Now let's talk about types of Machine Learning</h2>
<h3 id="heading-they-are-generally-of-3-types">They are generally of 3 types...</h3>
<ol>
<li>Supervised Learning</li>
<li>Unsupervised Learning</li>
<li>Reinforcement Learning</li>
</ol>
<p>Well, there can be a lot of types that can be mentioned like Semi-Supervised or Inductive Learning, but that requires a separate blog to talk about, hence I am not mentioning them here.</p>
<h3 id="heading-so-coming-up-with-supervised-learning-what-is-it">So, coming up with Supervised Learning! What is it?</h3>
<p>So Supervised Learning as the name suggests is Machine Learning under supervision. Which means the ML model is trained under labelled data which contains correct inputs and its desired output. The ML model learns over time to predict the correct results. <strong>Remember, it knows what is correct only on the basis of the fact that we teach them what is right and what is wrong. If I teach slapping is Good and Loving is Bad, it will learn that! The ML model will later classify slapping as a good act! And that's Supervised Learning</strong></p>
<h3 id="heading-example-of-supervised-learning">Example of Supervised Learning:</h3>
<p>Your Outlook or Gmail account that detects and puts certain emails into the spam folder is an example of Supervised Learning. It has been trained previously and it further learns from the Spam emails that get filtered out. It's a continuous process.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658998764170/ca9-jvCqh.png" alt="spam-folder-icon-200.png" /></p>
<h3 id="heading-next-is-unsupervised-learning">Next is Unsupervised Learning</h3>
<p>So Unsupervised Learning is based on Machine Learning Algorithms that clusters data sets which are generally unlabeled and hence this does not require any human intervention, hence <strong>"Unsupervised Machine Learning</strong>.</p>
<h3 id="heading-lets-take-an-example">Let's Take an Example</h3>
<p>If I give my ML model some images of a cat, and on the basis of the algorithm in it, the model predicts that the cat has a tail, 4 legs and 2 eyes. And they discovered it without any human intervention!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659000464217/yNGFYP_Um.jpg" alt="shutterstock_707431309-e1554172878508.jpg" /></p>
<h3 id="heading-finally-we-have-reinforcement-learning">Finally, we have Reinforcement Learning</h3>
<p>RL is an algorithm to train ML models to make a sequence of decisions. The whole process is generally based on a reward-based system where we give a reward to if it takes the right decision and we punish it if they take some wrong decision.</p>
<h3 id="heading-example">Example:</h3>
<p>This is a very famous example of RL where we teach a rocket to land perfectly. It gets a reward for every small step it performs and the final goal is to reach maximum reward and land the rocket in the desired position.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659000956754/NNAWYFFM6.gif" alt="153222406-af5ce6f0-4696-4a24-a683-46ad4939170c.gif" /></p>
]]></content:encoded></item></channel></rss>