<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Karanveer Singh on Medium]]></title>
        <description><![CDATA[Stories by Karanveer Singh on Medium]]></description>
        <link>https://medium.com/@karanveersingh05?source=rss-6c36802ab9b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8T7rYmJLYu3K_x5YoaWwdA@2x.jpeg</url>
            <title>Stories by Karanveer Singh on Medium</title>
            <link>https://medium.com/@karanveersingh05?source=rss-6c36802ab9b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:29:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karanveersingh05/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Is AI Really Taking Our Jobs? Let’s Talk About the Reality]]></title>
            <link>https://karanveersingh05.medium.com/is-ai-really-taking-our-jobs-lets-talk-about-the-reality-3f4df51fdec8?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f4df51fdec8</guid>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[tech-jobs]]></category>
            <category><![CDATA[getting-fired]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-vs-humans]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 11:20:27 GMT</pubDate>
            <atom:updated>2026-09-16T11:20:27.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*Q6iyi9eobIhGPG6I6b6h7A.png" /></figure><p>Whenever Artificial Intelligence is discussed today, one question appears again and again:</p><p><strong>“Will AI take our jobs?”</strong></p><p>Some people say AI will replace millions of workers.</p><p>Others say AI will simply become another tool, like computers or the internet.</p><p>The truth lies somewhere between these two extremes.</p><p>AI is already affecting jobs.</p><p>But in many cases, it is not simply removing an entire profession overnight.</p><p>Instead, it is changing <strong>what humans do inside that profession, how many people are required to do the work, and what skills companies are willing to pay for.</strong></p><p>And that distinction matters.</p><h3>AI Is More Likely to Replace Tasks Before It Replaces Entire Jobs</h3><p>Think about the work performed by an employee during an eight-hour day.</p><p>A job is usually made up of many different tasks.</p><p>For example, a customer-service employee may:</p><ul><li>Answer common questions</li><li>Look up customer information</li><li>Write emails</li><li>Handle complaints</li><li>Calm an angry customer</li><li>Make decisions about unusual cases</li><li>Coordinate with another department</li></ul><p>AI may be able to automate the first three or four tasks very effectively.</p><p>But handling an emotional customer or making an unusual business decision may still require a human.</p><p>This is why the International Labour Organization found that around <strong>one in four jobs worldwide has some exposure to generative AI</strong>, while emphasizing that transformation of jobs is currently more likely than complete replacement.</p><p>So the better question may not be:</p><p><strong>“Will AI replace my job?”</strong></p><p>It may be:</p><p><strong>“Which parts of my job can AI already perform?”</strong></p><h3>And Yes, Some Jobs Will Disappear</h3><p>We should also avoid pretending that nobody will lose a job because of AI.</p><p>That would not reflect reality.</p><p>When a company can perform the same amount of work with fewer people, there is an economic incentive to reduce hiring or headcount.</p><p>Routine digital work is particularly exposed.</p><p>Examples include:</p><ul><li>Basic customer support</li><li>Data entry</li><li>Simple content creation</li><li>Basic translation</li><li>Routine reporting</li><li>Administrative work</li><li>Repetitive research</li><li>Some junior programming tasks</li></ul><p>The World Economic Forum’s Future of Jobs Report 2025 estimated that major economic and technological trends could create <strong>170 million jobs while displacing 92 million by 2030</strong>.</p><p>Importantly, these numbers represent several global trends — not AI alone — but they show how significant the coming labour-market transition could be.</p><h3>A Real Example From India: Wipro</h3><p>This is where the discussion becomes real.</p><p>In September 2026, Wipro’s Chief Technology Officer told Reuters that AI-related productivity improvements had freed capacity equivalent to approximately <strong>20,000 employees</strong>.</p><p>But those employees were not simply removed.</p><p>Wipro said they had been <strong>redeployed into other roles</strong>, while the company had trained more than <strong>100,000 employees in advanced AI skills</strong>.</p><p>Think about what this means.</p><p>Previously:</p><p><strong>100 people → X amount of work</strong></p><p>With better AI tools:</p><p><strong>Fewer working hours → same X amount of work</strong></p><p>The remaining capacity can then be:</p><ul><li>Used for additional projects</li><li>Moved to higher-value work</li><li>Used to serve more customers</li><li>Or, in some companies, eventually reduce the need for hiring</li></ul><p>That is the real impact of AI.</p><p>Sometimes it means layoffs.</p><p>Sometimes it means redeployment.</p><p>Sometimes it means the company simply <strong>stops hiring</strong> as many people as it used to.</p><h3>Another Reality Check: India’s Customer-Service Industry</h3><p>India is particularly interesting because millions of jobs have historically been connected to IT services, outsourcing and customer support.</p><p>Reuters reported in 2025 that AI-powered customer-service systems were already allowing some Indian companies to handle considerably more customer queries with fewer employees.</p><p>For example, AI startup LimeChat said its systems could dramatically reduce the number of human workers required for high-volume customer queries.</p><p>Reuters also reported examples of Indian businesses replacing some sales and call-centre functions with AI agents.</p><p>This is not a theoretical prediction about 2040.</p><p>It is already happening.</p><p>And this creates a particular challenge for younger workers.</p><p>Entry-level jobs traditionally teach people:</p><p><strong>Junior → Experience → Senior → Expert</strong></p><p>But what happens when AI can perform many of the simpler tasks that were previously given to juniors?</p><p>That is one of the more serious questions around AI and employment.</p><p>The ILO’s 2026 research has highlighted concerns about <strong>weakening</strong> opportunities for younger workers in some <strong>entry-level jobs</strong>.</p><h3>But Here Is the Other Side of the Story</h3><p>If AI were simply better than humans at everything, companies would already be removing entire departments.</p><p>That hasn’t happened.</p><p>AI still has serious limitations.</p><p>It can:</p><ul><li>Produce incorrect information</li><li>Misunderstand context</li><li>Sound confident while being wrong</li><li>Struggle with unusual situations</li><li>Lack genuine human empathy</li><li>Require supervision</li><li>Make mistakes that businesses cannot afford</li></ul><p>One of the most interesting examples comes from <strong>Klarna</strong>.</p><p>The financial-technology company aggressively introduced AI into customer service.</p><p>Its chatbot was reported to perform work equivalent to around <strong>700 full-time customer-service workers</strong>, and the company significantly reduced staffing.</p><p>That sounds like the perfect example of AI replacing humans.</p><p>But the story did not end there.</p><p>By 2025, Klarna’s CEO acknowledged that the company had pushed cost-cutting through AI too aggressively and began changing its approach.</p><p>The company returned to hiring people and emphasized using AI alongside better products and customer service rather than treating AI purely as a way to eliminate labour.</p><p>Later reporting also showed that complicated customer problems were still frequently transferred to humans because customers wanted judgment, understanding and empathy that AI could not reliably provide.</p><p>That example teaches us something important:</p><p><strong>AI can replace a task successfully without replacing the human value surrounding that task.</strong></p><h3>Sometimes AI Makes Professionals More Powerful Instead</h3><p>Consider another industry: finance.</p><p>Morgan Stanley introduced AI tools for its financial advisors.</p><p>Its internal AI assistant helps advisors search large amounts of company research and find information much faster.</p><p>According to OpenAI, more than <strong>98% of Morgan Stanley advisor teams were using the system</strong>.</p><p>But Morgan Stanley did not remove its financial advisors.</p><p>Instead, AI became a tool that helped advisors access information faster while humans continued handling the client relationship, judgment and decision-making.</p><p>Morgan Stanley also introduced an AI tool that can summarize meetings, identify action items and draft follow-up emails for advisors.</p><p>So instead of:</p><p><strong>AI → Financial advisor disappears</strong></p><p>the model became:</p><p><strong>Financial advisor + AI → More productive financial advisor</strong></p><p>That pattern is likely to appear across many professions.</p><h3>The Biggest Change May Be Smaller Teams</h3><p>There is another effect that receives less attention.</p><p>Imagine a company previously needed:</p><p><strong>10 employees to complete 1,000 tasks.</strong></p><p>After introducing AI, those employees become twice as productive.</p><p>The company might now need:</p><p><strong>5 employees + AI</strong></p><p>to produce similar output.</p><p>The company has not automated the entire profession.</p><p>But it may still need fewer employees.</p><p>This means AI does not necessarily need to become capable of performing <strong>100% of your job</strong> before it affects employment.</p><p>Even automating <strong>30–50% of certain workflows</strong> can change hiring requirements.</p><p>That is why simply asking whether AI can completely replace a profession misses part of the problem.</p><h3>The Most Vulnerable Work Is Predictable Work</h3><p>AI is strongest when work is:</p><p><strong>Digital + repetitive + predictable + based on existing information.</strong></p><p>For example:</p><pre>Read this document<br>↓<br>Summarize it<br>↓<br>Extract information<br>↓<br>Put it into a template<br>↓<br>Write an email</pre><p>Modern AI systems can already perform workflows like this extremely quickly.</p><p>But work becomes harder to automate when it requires:</p><p><strong>Physical interaction + responsibility + human trust + unusual situations + deep judgment.</strong></p><p>A nurse comforting a patient.</p><p>A manager resolving conflict.</p><p>A salesperson understanding an unusual customer.</p><p>An engineer deciding whether a system is safe.</p><p>A leader deciding which business risk to take.</p><p>AI can assist these people.</p><p>But assistance and responsibility are different things.</p><h3>Human Skills May Become More Valuable, Not Less</h3><p>Interestingly, as AI becomes better at generating information, simply knowing information may become less valuable.</p><p>Human skills such as these become increasingly important:</p><p><strong>Communication</strong></p><p>Can you explain an idea clearly?</p><p><strong>Critical thinking</strong></p><p>Can you recognize when AI’s answer is wrong?</p><p><strong>Problem solving</strong></p><p>Can you determine which problem actually needs to be solved?</p><p><strong>Domain expertise</strong></p><p>Do you understand the business, industry or subject deeply?</p><p><strong>Decision making</strong></p><p>Can you take responsibility when several options exist?</p><p><strong>Creativity</strong></p><p>Can you develop something beyond the obvious patterns?</p><p><strong>Emotional intelligence</strong></p><p>Can you work effectively with actual humans?</p><p>A 2026 ILO report on skills in the AI era similarly found increasing importance for cognitive, socioemotional, digital and AI-related skills.</p><h3>Learning AI Alone Is Not Enough Either</h3><p>There is another misconception growing today:</p><blockquote><em>“Just learn AI and your career will be safe.”</em></blockquote><p>That is also too simple.</p><p>Knowing how to type prompts into ChatGPT is unlikely to remain a rare skill.</p><p>Millions of people can learn that.</p><p>The stronger combination is:</p><p><strong>Your main skill + AI</strong></p><p>For example:</p><pre>Doctor + AI<br>Lawyer + AI<br>Developer + AI<br>Marketer + AI<br>Designer + AI<br>Accountant + AI<br>Teacher + AI</pre><p>The AI knowledge makes you faster.</p><p>Your professional knowledge helps you determine whether the AI output is actually useful.</p><h3>What Should Students and Employees Do?</h3><p>I don’t think the right response to AI is panic.</p><p>But ignoring it is also risky.</p><p>We should concentrate on four things.</p><h3>1. Become good at something</h3><p>Do not depend entirely on AI.</p><p>Develop real knowledge in your profession.</p><h3>2. Learn to use AI</h3><p>Understand how AI can automate repetitive parts of your work.</p><h3>3. Learn to verify AI</h3><p>AI output is not automatically correct.</p><p>Knowing when <strong>not</strong> to trust AI may become as important as knowing how to use it.</p><h3>4. Improve your human skills</h3><p>Communication, leadership, creativity, negotiation and judgment become even more important when machines can generate routine information instantly.</p><h3>The Uncomfortable Reality</h3><ol><li>Some people will lose jobs because of AI.</li><li>Some companies will hire fewer employees.</li><li>Some entry-level positions may become harder to find.</li><li>Some existing professions will change dramatically.</li></ol><p>At the same time:</p><ol><li>New jobs will appear.</li><li>Existing workers will become more productive.</li><li>Small teams will be capable of building things that previously required much larger organizations.</li></ol><p>And people who learn to combine domain expertise with AI will gain capabilities that workers in previous generations never had.</p><p>Both realities can exist at the same time.</p><h3>So, Will AI Take Your Job?</h3><p>There is no universal answer.</p><p>AI probably will not affect a plumber, financial analyst, software developer, doctor, call-centre worker and teacher in exactly the same way.</p><p>The better question is:</p><blockquote><strong><em>Which parts of my work are becoming easier to automate, and what can I learn that remains valuable when those tasks are automated?</em></strong></blockquote><p>The future of work probably won’t be:</p><p><strong>Humans vs AI</strong></p><p>It will increasingly be:</p><p><strong>Humans working with AI, companies redesigning jobs around AI, and some tasks disappearing completely.</strong></p><p>AI is not coming someday.</p><p>It is already here.</p><p>The challenge now is not simply protecting the way we worked yesterday.</p><p>It is learning how to remain valuable in the way we will work tomorrow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f4df51fdec8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain for Beginners: From Prompts to Your First LLM Pipeline]]></title>
            <link>https://karanveersingh05.medium.com/langchain-for-beginners-from-prompts-to-your-first-llm-pipeline-24073fe99afc?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/24073fe99afc</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 11:30:39 GMT</pubDate>
            <atom:updated>2026-09-14T11:30:39.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*H6bOT7M7mFNy2Nw0ehJ17w.png" /></figure><p>Large Language Models such as <strong>Gemini, GPT, Claude, and Llama</strong> can generate impressive responses from a simple prompt.</p><p>But when we start building a real AI application, calling an LLM is only one part of the process.</p><p>An application may need to:</p><ol><li>Create dynamic prompts</li><li>Send those prompts to an LLM</li><li>Process the generated response</li><li>Handle multiple requests</li><li>Stream responses</li><li>Connect multiple processing steps</li><li>Run tasks sequentially or in parallel</li></ol><p>This is where <strong>LangChain</strong> becomes useful.</p><p>In this article, we will understand the fundamentals of LangChain and build our first LLM pipeline in Python.</p><h3>What is LangChain?</h3><p><strong>LangChain is a framework for building applications powered by Large Language Models.</strong></p><p>Instead of manually managing every step of an AI application, LangChain provides reusable components that can be connected together.</p><p>A simple LLM application might look like this:</p><pre>User Input<br>    ↓<br>Prompt<br>    ↓<br>LLM<br>    ↓<br>Response</pre><p>But a larger application may look like:</p><pre>User Input<br>    ↓<br>Prompt Template<br>    ↓<br>LLM<br>    ↓<br>Output Parser<br>    ↓<br>Additional Processing<br>    ↓<br>Final Output</pre><p>LangChain helps us organize these components into clear pipelines.</p><p>A simple way to remember it is:</p><blockquote><strong><em>The LLM is the brain, while LangChain helps connect that brain with the rest of the application.</em></strong></blockquote><h3>Why Use LangChain?</h3><p>We can absolutely call an LLM API directly.</p><p>For a small application, that may be enough.</p><p>But imagine building an application where we need to:</p><pre>Create Prompt<br>     ↓<br>Call Model<br>     ↓<br>Process Output<br>     ↓<br>Call Another Function<br>     ↓<br>Search Data<br>     ↓<br>Generate Final Response</pre><p>Writing and managing all of this manually can become complicated.</p><p>LangChain provides components for creating these workflows in a cleaner and more reusable way.</p><p>Some important LangChain concepts include:</p><pre>Models<br>Prompt Templates<br>Chains<br>Output Parsers<br>Runnables<br>Retrievers<br>Tools<br>Agents</pre><p>In this article, we will focus on the fundamental concepts needed before moving toward advanced topics such as RAG and agents.</p><h3>Setting Up LangChain</h3><p>For this example, we will use <strong>Google Gemini</strong> with LangChain.</p><p>Install the required packages:</p><pre>pip install langchain<br>pip install langchain-google-genai<br>pip install python-dotenv</pre><p>Create a .env file:</p><pre>GOOGLE_API_KEY=your_api_key_here</pre><p>Never publish your API key directly inside your Python code or upload your .env file to GitHub.</p><p>Now load the environment variables:</p><pre>from dotenv import load_dotenv<br>load_dotenv()</pre><h3>Connecting Gemini with LangChain</h3><p>Let’s start by calling the model directly.</p><pre>from dotenv import load_dotenv<br>from langchain_google_genai import ChatGoogleGenerativeAI<br><br>load_dotenv()<br><br>model = ChatGoogleGenerativeAI(<br>    model=&quot;gemini-2.5-flash&quot;<br>)<br>response = model.invoke(<br>    &quot;Explain machine learning in simple words.&quot;<br>)<br>print(response.text)<br><br>model.invoke(...)</pre><h3>What does invoke() mean?</h3><p>invoke() simply means:</p><blockquote><strong><em>Run this component once using the given input.</em></strong></blockquote><p>Think of it as:</p><pre>Input<br>  ↓<br>invoke()<br>  ↓<br>Model<br>  ↓<br>Output</pre><p>This becomes especially important because many LangChain components follow the same Runnable interface.</p><h3>What is a Prompt Template?</h3><p>Suppose we want to build an AI teacher.</p><p>Instead of manually writing:</p><pre>Explain Python loops to a beginner student.</pre><p>every time, we can create a reusable prompt.</p><pre>from langchain_core.prompts import ChatPromptTemplate<br><br>prompt = ChatPromptTemplate.from_messages([<br>    (<br>        &quot;system&quot;,<br>        &quot;You are an experienced {role}.&quot;<br>    ),<br>    (<br>        &quot;human&quot;,<br>        &quot;Explain {topic} to a {level} student.&quot;<br>    )<br>])</pre><p>Here:</p><pre>{role}<br>{topic}<br>{level}</pre><p>are variables.</p><p>We can provide different values whenever the prompt runs.</p><pre>result = prompt.invoke({<br>    &quot;role&quot;: &quot;Python trainer&quot;,<br>    &quot;topic&quot;: &quot;decorators&quot;,<br>    &quot;level&quot;: &quot;beginner&quot;<br>})<br><br>print(result)</pre><p>The final prompt will conceptually become:</p><pre>System:<br>You are an experienced Python trainer.<br><br>Human:<br>Explain decorators to a beginner student.</pre><p>This makes our prompts <strong>dynamic and reusable</strong>.</p><h3>Building Our First LangChain Chain</h3><p>Now comes one of the most useful concepts in LangChain.</p><p>Instead of separately doing:</p><pre>prompt_data = prompt.invoke(data)<br><br>response = model.invoke(prompt_data)</pre><p>we can connect the components:</p><pre>chain = prompt | model</pre><p>The | symbol is called the <strong>pipe operator</strong>.</p><p>Think of it like:</p><pre>Input<br>  ↓<br>Prompt<br>  ↓<br>Model<br>  ↓<br>Output</pre><p>Now we can directly run:</p><pre>response = chain.invoke({<br>    &quot;role&quot;: &quot;AI trainer&quot;,<br>    &quot;topic&quot;: &quot;Large Language Models&quot;,<br>    &quot;level&quot;: &quot;beginner&quot;<br>})<br><br>print(response.text)</pre><p>The output of one component automatically becomes the input of the next component.</p><p>That is the basic idea behind a <strong>chain</strong>.</p><h3>Understanding LCEL</h3><p>You may see the term <strong>LCEL</strong> while learning LangChain.</p><p>LCEL stands for:</p><p><strong>LangChain Expression Language</strong></p><p>It allows us to connect LangChain components using the pipe operator.</p><p>For example:</p><pre>chain = prompt | model</pre><p>Or:</p><pre>chain = prompt | model | parser</pre><p>Conceptually:</p><pre>Prompt<br>  |<br>  v<br>Model<br>  |<br>  v<br>Parser<br>  |<br>  v<br>Final Output</pre><p>This makes complex AI pipelines much easier to read.</p><h3>What is an Output Parser?</h3><p>Normally, a chat model returns a message object containing the model’s response and additional information.</p><p>Sometimes we simply want the final text.</p><p>For this, we can use:</p><pre>from langchain_core.output_parsers import StrOutputParser<br><br>parser = StrOutputParser()</pre><p>Now create the complete chain:</p><pre>chain = prompt | model | parser</pre><p>Run it:</p><pre>result = chain.invoke({<br>    &quot;role&quot;: &quot;Machine Learning trainer&quot;,<br>    &quot;topic&quot;: &quot;Logistic Regression&quot;,<br>    &quot;level&quot;: &quot;beginner&quot;<br>})<br><br>print(result)</pre><p>Because we added StrOutputParser(), the chain gives us a convenient string result.</p><p>Our pipeline is now:</p><pre>Input<br>  ↓<br>ChatPromptTemplate<br>  ↓<br>Gemini<br>  ↓<br>StrOutputParser<br>  ↓<br>String Output</pre><p>This is one of the most important patterns to understand when starting with LangChain.</p><h3>invoke(), batch() and stream()</h3><p>LangChain components can be executed in different ways.</p><h3>1. invoke()</h3><p>Use invoke() when you have <strong>one input</strong>.</p><pre>result = chain.invoke({<br>    &quot;role&quot;: &quot;Python trainer&quot;,<br>    &quot;topic&quot;: &quot;Functions&quot;,<br>    &quot;level&quot;: &quot;beginner&quot;<br>})</pre><pre>print(result)</pre><p>Think:</p><pre>One Input → One Output</pre><h3>2. batch()</h3><p>Suppose we want to process multiple inputs.</p><p>Instead of calling the chain manually again and again, we can use:</p><pre>results = chain.batch([<br>    {<br>        &quot;role&quot;: &quot;Python trainer&quot;,<br>        &quot;topic&quot;: &quot;Functions&quot;,<br>        &quot;level&quot;: &quot;beginner&quot;<br>    },<br>    {<br>        &quot;role&quot;: &quot;ML trainer&quot;,<br>        &quot;topic&quot;: &quot;Linear Regression&quot;,<br>        &quot;level&quot;: &quot;beginner&quot;<br>    }<br>])<br><br>for result in results:<br>    print(result)</pre><p>Think:</p><pre>Multiple Inputs<br>      ↓<br>    batch()<br>      ↓<br>Multiple Outputs</pre><h3>3. stream()</h3><p>Sometimes we don’t want to wait for the complete response.</p><p>We want the text to appear gradually, similar to how AI chat applications display responses.</p><pre>for chunk in chain.stream({<br>    &quot;role&quot;: &quot;AI trainer&quot;,<br>    &quot;topic&quot;: &quot;Generative AI&quot;,<br>    &quot;level&quot;: &quot;beginner&quot;<br>}):<br>    print(chunk, end=&quot;&quot;, flush=True)</pre><p>Think:</p><pre>Model<br> ↓<br>Part 1<br> ↓<br>Part 2<br> ↓<br>Part 3<br> ↓<br>Complete Response</pre><p>So remember:</p><pre>invoke() → One input<br>batch()  → Multiple inputs<br>stream() → Output gradually</pre><h3>What is a Runnable?</h3><p>Another important LangChain term is <strong>Runnable</strong>.</p><p>The name sounds complicated, but the idea is simple.</p><p>A Runnable is something that:</p><pre>Takes Input<br>    ↓<br>Does Something<br>    ↓<br>Returns Output</pre><p>Many LangChain components behave like Runnables.</p><p>For example:</p><pre>Prompt Template<br>Model<br>Output Parser<br>Chain</pre><p>This common interface is why we can easily connect different components.</p><h3>RunnableLambda</h3><p>What if we already have a normal Python function and want to use it inside a LangChain pipeline?</p><p>We can use RunnableLambda.</p><p>Example:</p><pre>from langchain_core.runnables import RunnableLambda<br><br>def make_uppercase(text):<br>    return text.upper()<br>upper = RunnableLambda(make_uppercase)<br>print(upper.invoke(&quot;hello langchain&quot;))</pre><p>Output:</p><pre>HELLO LANGCHAIN</pre><p>Now this Python function can also become part of a larger LangChain workflow.</p><h3>RunnablePassthrough</h3><p>Sometimes we simply want to pass the original input forward without changing it.</p><p>LangChain provides:</p><pre>from langchain_core.runnables import RunnablePassthrough</pre><p>Conceptually:</p><pre>Input<br>  ↓<br>RunnablePassthrough<br>  ↓<br>Same Input</pre><p>It becomes particularly useful when different branches of an application need the original input.</p><h3>Sequential vs Parallel Workflows</h3><p>LangChain workflows can also be understood in two common ways.</p><h3>Sequential Processing</h3><p>One task happens after another.</p><pre>Input<br>  ↓<br>Prompt<br>  ↓<br>Model<br>  ↓<br>Parser<br>  ↓<br>Output</pre><p>Our existing chain is already a sequential pipeline:</p><pre>chain = prompt | model | parser</pre><p>Each step depends on the previous step.</p><h3>Parallel Processing</h3><p>Sometimes multiple independent tasks can run from the same input.</p><p>Imagine analyzing an article and generating:</p><pre>┌→ Summary<br>Article → Input ─┼→ Keywords<br>                 └→ Sentiment</pre><p>These tasks do not necessarily need to wait for each other.</p><p>LangChain provides runnable components that make these parallel workflows possible.</p><p>This becomes valuable when building larger AI applications.</p><h3>Complete Beginner Example</h3><p>Let’s combine everything into a simple AI learning assistant.</p><pre>from dotenv import load_dotenv<br><br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>load_dotenv()<br>model = ChatGoogleGenerativeAI(<br>    model=&quot;gemini-2.5-flash&quot;<br>)<br>prompt = ChatPromptTemplate.from_messages([<br>    (<br>        &quot;system&quot;,<br>        &quot;You are an experienced teacher. &quot;<br>        &quot;Explain concepts clearly with simple examples.&quot;<br>    ),<br>    (<br>        &quot;human&quot;,<br>        &quot;Explain {topic} to a {level} student.&quot;<br>    )<br>])<br>parser = StrOutputParser()<br>chain = prompt | model | parser<br>result = chain.invoke({<br>    &quot;topic&quot;: &quot;Retrieval-Augmented Generation&quot;,<br>    &quot;level&quot;: &quot;beginner&quot;<br>})<br>print(result)</pre><p>Our complete application flow is:</p><pre>User Input<br>    ↓<br>ChatPromptTemplate<br>    ↓<br>Gemini Model<br>    ↓<br>StrOutputParser<br>    ↓<br>Final Answer</pre><p>With only a few lines of code, we have created a reusable LLM pipeline.</p><h3>Where Does LangChain Go From Here?</h3><p>What we learned today is only the foundation.</p><p>Once these fundamentals are clear, we can move toward:</p><pre>LangChain Fundamentals<br>        ↓<br>Prompt Templates<br>        ↓<br>Chains &amp; LCEL<br>        ↓<br>Runnables<br>        ↓<br>Conversation History<br>        ↓<br>Document Loaders<br>        ↓<br>Embeddings<br>        ↓<br>Vector Databases<br>        ↓<br>RAG<br>        ↓<br>Tools<br>        ↓<br>AI Agents</pre><p>Understanding prompts, chains, parsers, and Runnables first makes these advanced topics much easier.</p><h3>Final Thoughts</h3><p>LangChain is not an LLM itself.</p><p>Gemini, GPT, Claude, and Llama are models.</p><p><strong>LangChain provides the framework for connecting models with prompts, processing logic, data sources, tools, and larger application workflows.</strong></p><p>The most important workflow to remember from this article is:</p><pre>INPUT<br>  ↓<br>PROMPT<br>  ↓<br>MODEL<br>  ↓<br>PARSER<br>  ↓<br>OUTPUT</pre><p>And in Python:</p><pre>chain = prompt | model | parser</pre><p>Once this simple pattern makes sense, LangChain starts feeling much less complicated.</p><p>The goal is not to memorize every LangChain class.</p><p>The goal is to understand how different AI components can be connected to build a complete application.</p><p>And that is exactly where the real power of LangChain begins.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24073fe99afc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Unlimited Tokens”: Scam or Reality?]]></title>
            <link>https://karanveersingh05.medium.com/fake-api-keys-and-unlimited-tokens-scam-or-reality-9cee3e2e4964?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cee3e2e4964</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[unlimited-tokens]]></category>
            <category><![CDATA[myths]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 10:28:55 GMT</pubDate>
            <atom:updated>2026-08-30T12:45:13.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*CPKZXj1FfYGsmLreXLfdpQ.png" /></figure><p>If you are learning <strong>Generative AI, LLMs, or APIs</strong>, you may have seen videos or posts claiming:</p><ol><li>“Free ChatGPT API key”</li><li>“Unlimited API tokens”</li><li>“GPT API key generator”</li><li>“Get paid AI APIs for free”</li></ol><p>For beginners, these claims can be confusing.</p><p>Can someone really create an unlimited API key? Can a fake API key work? And is there any legitimate way to use AI APIs for free?</p><p>Let’s understand it step by step.</p><h3>1. What Is an API Key?</h3><p>An <strong>API key</strong> is a secret credential that allows your application to communicate with an online service.</p><p>For example, if your Python program wants to use an AI model:</p><pre>Python Application<br>        ↓<br>     API Key<br>        ↓<br>   AI Provider<br>        ↓<br>      Model<br>        ↓<br>     Response</pre><p>You can think of an API key like a <strong>digital access card</strong>.</p><p>It tells the provider:</p><blockquote><em>“This request is coming from this account or project.”</em></blockquote><p>A key may look something like:</p><pre>API_KEY = &quot;your-secret-api-key&quot;</pre><p>You should never publicly share your real API key.</p><h3>2. Does an API Key Contain Tokens?</h3><p>No.</p><p>This is one of the biggest misunderstandings beginners have.</p><p>An API key does <strong>not store tokens, credits, or money inside it</strong>.</p><p>The API provider keeps that information on its own servers.</p><p>When you send a request, the provider checks:</p><pre>API Request<br>     ↓<br>Is the API key valid?<br>     ↓<br>Which account owns it?<br>     ↓<br>Does the account have credits?<br>     ↓<br>Are rate limits available?<br>     ↓<br>Run the model</pre><p>So an API key is mainly used for <strong>authentication and authorization</strong>.</p><h3>3. What Are API Tokens?</h3><p>Tokens are small pieces of text processed by an AI model.</p><p>For example:</p><pre>Artificial intelligence is powerful.</pre><p>is divided into smaller pieces called <strong>tokens</strong> before the model processes it.</p><p>Generally, API usage includes:</p><pre>Input Tokens + Output Tokens = Total Token Usage</pre><p>Depending on the provider and model, these tokens may affect the cost of your request.</p><p>So remember:</p><pre>API Key → Access<br>Tokens → Model Usage</pre><p>They are not the same thing.</p><h3>4. What Is an “Unlimited API Key”?</h3><p>You may see someone sharing something like:</p><pre>sk-free-unlimited-ai-123456789</pre><p>and claiming:</p><blockquote><em>“This key gives unlimited AI tokens.”</em></blockquote><p>A string can look like an API key, but that does not mean it is valid.</p><p>The real API provider checks the key on its server.</p><p>If the key does not exist, the request will normally be rejected.</p><p>Therefore:</p><pre>API key - looking text ≠ Real API access</pre><p>And:</p><pre>Real API key ≠ Unlimited tokens</pre><p>Usage limits are normally controlled by the provider’s servers, not by the text written inside the key.</p><h3>5. Safe Fake API Key Experiment</h3><p>We can understand this using a deliberately fake API key.</p><p>First install:</p><pre>pip install requests</pre><p>Then try:</p><pre>import requests<br><br>fake_api_key = &quot;sk-this-is-a-fake-demo-key&quot;<br>headers = {<br>    &quot;Authorization&quot;: f&quot;Bearer {fake_api_key}&quot;<br>}<br><br>response = requests.get(<br>    &quot;https://api.openai.com/v1/models&quot;,<br>    headers=headers<br>)<br><br>print(response.status_code)<br>print(response.text)</pre><p>This key is intentionally fake.</p><p>The request may reach the API server, but authentication should fail because the key is not connected to a valid authorized project.</p><p>You may receive an error such as:</p><pre>401 Unauthorized</pre><p>This experiment teaches an important concept:</p><pre>Creating random API keys<br>        ↓<br>Does NOT create<br>        ↓<br>Real API access</pre><h3>6. What About API Keys Found on the Internet?</h3><p>Sometimes you may find API keys on:</p><ol><li>GitHub</li><li>Telegram</li><li>Discord</li><li>YouTube comments</li><li>Random websites</li><li>Forums</li></ol><p>Some of these keys may even work temporarily.</p><p>But this does not mean they are <strong>free API keys</strong>.</p><p>They may belong to another developer whose key was accidentally leaked.</p><p>Using someone else’s exposed API key can consume their quota or create charges on their account.</p><p>So:</p><pre>Leaked API Key ≠ Free API Key</pre><p>A leaked key is actually a <strong>security problem</strong>.</p><h3>7. Common API Key Scams</h3><p>One dangerous scam looks like this:</p><pre>Enter your OpenAI API key<br>to unlock unlimited tokens.</pre><p>You enter your real API key, and the website secretly saves it.</p><p>The attacker could then use your API account.</p><p>Another common scam is:</p><pre>Download this API Key Generator.exe</pre><p>Unknown programs like this may contain malware or steal information from your computer.</p><p>Be suspicious of services claiming:</p><pre>Unlimited GPT API<br>Free premium API forever<br>API key generator<br>Cracked AI API<br>10,000 working API keys</pre><p>If something normally costs money but someone promises unlimited access for free, verify it carefully.</p><h3>8. Can We Get Free API Tokens Legally?</h3><p>Yes.</p><p>There are legitimate ways to experiment with AI APIs without immediately paying large amounts.</p><p>Some providers offer:</p><ol><li>Free API tiers</li><li>Trial credits</li><li>Developer credits</li><li>Student programs</li><li>Limited free models</li></ol><p>A free tier may work like:</p><pre>Create Account<br>      ↓<br>Generate Real API Key<br>      ↓<br>Receive Limited Free Usage<br>      ↓<br>Use API<br>      ↓<br>Rate Limits Apply</pre><p>The important word is <strong>limited</strong>.</p><p>Free API access can exist.</p><p>Unlimited free access to expensive cloud AI models is much less realistic.</p><p>Always check the provider’s <strong>official pricing page</strong> to see its current free-tier rules.</p><h3>9. Free Tier vs Unlimited API</h3><p>These are very different.</p><h4>a. Legitimate Free Tier</h4><pre>Free usage<br>Limited requests<br>Limited tokens<br>Rate limits<br>Selected models</pre><h4>b. “Unlimited Free API” Claim</h4><pre>Unlimited requests<br>Unlimited tokens<br>Premium models<br>No billing<br>No restrictions</pre><p>The second claim should immediately make you cautious.</p><p>AI models require expensive GPUs, electricity, servers, storage, networking, and infrastructure.</p><p>That is why providers normally place limits on their services.</p><h3>10. Another Option: Run AI Models Locally</h3><p>If you are learning AI and don’t want to spend money on APIs, you can also experiment with <strong>open-source models</strong>.</p><p>Examples include models from families such as:</p><pre>Qwen<br>Gemma<br>Llama<br>Mistral<br>DeepSeek</pre><p>You can run supported models locally using tools such as Hugging Face Transformers or local LLM applications.</p><p>The workflow becomes:</p><pre>Your Computer<br>      ↓<br>Local Model<br>      ↓<br>Your Prompt<br>      ↓<br>Response</pre><p>There is no cloud API token charge because the model is running on your computer.</p><p>However, you are still using your own:</p><pre>CPU / GPU<br>RAM<br>Storage<br>Electricity</pre><h3>11. How to Protect Your Real API Key</h3><p>Never write your real API key directly in code that you plan to upload publicly.</p><p>Avoid:</p><pre>api_key = &quot;my-real-secret-key&quot;</pre><p>Instead, store it inside a .env file:</p><pre>OPENAI_API_KEY=your-secret-key</pre><p>Then access it using Python:</p><pre>from dotenv import load_dotenv<br>import os<br><br>load_dotenv()<br>api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)</pre><p>Also add:</p><pre>.env</pre><p>to your:</p><pre>.gitignore</pre><p>This helps prevent your API key from accidentally being uploaded to GitHub.</p><h3>12. What If Your API Key Gets Leaked?</h3><p>If you accidentally expose your API key, don’t just delete it from your Python file.</p><p>A safer process is:</p><pre>API Key Leaked<br>      ↓<br>Revoke Old Key<br>      ↓<br>Generate New Key<br>      ↓<br>Update Your Application<br>      ↓<br>Check API Usage<br>      ↓<br>Check Unexpected Charges</pre><p>Once a secret has been publicly exposed, you should assume someone may have copied it.</p><h3>Final Thoughts</h3><p>API keys are an important part of modern AI development, but beginners should understand what they actually do.</p><p>An API key is mainly a <strong>credential that gives your application access to a service</strong>.</p><p>It does not contain unlimited tokens.</p><p>Random API key generators cannot magically create authorized access to paid AI services.</p><p>Free API usage can definitely exist through official free tiers, trial credits, student programs, or free models.</p><p>So instead of searching for:</p><pre>Unlimited free API key</pre><p>search for:</p><pre>Official API free tier<br>AI developer credits<br>Student AI credits<br>Free LLM API<br>Open-source LLM<br>Local LLM</pre><p>The safest rule is simple:</p><blockquote><strong><em>Create API keys only from the official provider, keep them private, and never trust “unlimited API key” claims without verifying them from official documentation.</em></strong></blockquote><p>Understanding this early will save you from scams, unexpected charges, and serious security problems while learning AI development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cee3e2e4964" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LLM APIs: From API Keys to Your First LLM Request]]></title>
            <link>https://karanveersingh05.medium.com/understanding-llm-apis-from-api-keys-to-your-first-llm-request-87cd2cb52bcb?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/87cd2cb52bcb</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 07:48:04 GMT</pubDate>
            <atom:updated>2026-08-26T10:14:00.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZsfzufqTDGI31Ikx-BGSQ.png" /></figure><p>Large Language Models are becoming a major part of modern applications.</p><p>From <strong>ChatGPT-style assistants</strong> to <strong>customer-support systems, summarization tools, code generators, and document analyzers</strong>, many applications use LLMs behind the scenes.</p><p>But an important question is :</p><p><strong>How does our Python application actually communicate with an LLM?</strong></p><p>The answer is usually through an <strong>API</strong>.</p><p>In this blog , we’ll understand the basic flow of an LLM application, API keys, requests and responses, system instructions, conversation context, and how to make our first Gemini API request using Python.</p><h3>1. What Is an LLM?</h3><p><strong>LLM stands for Large Language Model.</strong></p><p>An LLM is a machine-learning model trained on large amounts of text and other data so that it can learn patterns in language and generate responses based on the input and context it receives.</p><p>Some common applications of LLMs include:</p><ol><li>Question Answering</li><li>Text Summarization</li><li>Translation</li><li>Code Generation</li><li>Text Classification</li><li>Information Extraction</li><li>Content Generation</li><li>Reasoning</li><li>Conversational Applications</li></ol><p>For example, we could give an LLM this input:</p><pre>Explain machine learning in simple words.</pre><p>The model processes the input and generates an appropriate response.</p><p>One important concept to understand is:</p><blockquote><strong><em>An LLM is the model, while an API is the interface through which our application communicates with that model.</em></strong></blockquote><h3>2. Why Use an LLM API Instead of a Local Hugging Face Model?</h3><p>We often use an <strong>LLM API</strong> because it is easier and faster than running a large Hugging Face model locally.</p><p><strong>Main Reasons :</strong></p><ol><li><strong>No powerful GPU required</strong> — the model runs on the provider’s server.</li><li><strong>Easy setup</strong> — connect using an API key and SDK.</li><li><strong>Faster development</strong> — no need to download and configure large models.</li><li><strong>Easy deployment</strong> — the application only sends requests to the API.</li><li><strong>Access to powerful models</strong> — we can use large models that may not run on a normal laptop.</li><li><strong>Less maintenance</strong> — the provider manages model infrastructure and scaling.</li></ol><pre>Application → API → LLM → Response</pre><h4>When Hugging Face Is Better</h4><p>Use Hugging Face models when you need <strong>fine-tuning, offline use, more control, or custom model development</strong>.</p><p>So:</p><pre>Quick and easy application → LLM API<br>More control and customization → Hugging Face Model</pre><h3>3. How Does a Python Application Communicate With an LLM?</h3><p>The basic flow looks like this:</p><pre>Python Application<br>        ↓<br>       API<br>        ↓<br>       LLM<br>        ↓<br>    Response<br>        ↓<br>Python Application</pre><p>Our Python program usually does not directly interact with the internal architecture of the model.</p><p>Instead, our application sends a <strong>request</strong> through an API.</p><p>The API passes the request to the selected model.</p><p>The model processes the request and generates a response.</p><p>The API then returns that response to our application.</p><p>So we can think of the API as a <strong>communication bridge</strong> between our software and the LLM.</p><h3>4. What Is an API Key?</h3><p>When our application sends a request to an API, the API needs to know which application or account is making the request.</p><p>This is where the <strong>API key</strong> comes in.</p><p>An API key is a credential used to authenticate an application with an API.</p><p>Conceptually:</p><pre>Python Application<br>        ↓<br>    API Key<br>        ↓<br>       API<br>        ↓<br>       LLM</pre><p>An API key should be treated like a password.</p><p>We should <strong>not write the API key directly inside our Python code</strong>, especially if the project will be uploaded to GitHub.</p><p>Avoid doing this:</p><pre>api_key = &quot;my-secret-api-key&quot;</pre><p>Instead, we can store the API key in an environment file.</p><h3>5. Why Do We Need an API?</h3><p>An <strong>API — Application Programming Interface — </strong>allows different software systems to communicate with each other.</p><p>In an LLM application:</p><pre>Our Application → API → LLM</pre><p>The API gives our application access to the model.</p><p>For example, instead of downloading and running a very large model on our own computer, our Python application can send a request to a hosted model using an API.</p><p>This makes it easier to integrate LLM capabilities into applications such as:</p><pre>Chatbots<br>Customer Support Systems<br>AI Assistants<br>Document Summarizers<br>Content Generators<br>Code Assistants<br>Recommendation Systems</pre><h3>6. Setting Up the Gemini API in Python</h3><p>Before sending requests to Gemini, we need to <strong>store our API key securely, install the required SDK, and connect our Python application to the API</strong>.</p><h4>Step 1: Store the API Key</h4><p>Create a .env file:</p><pre>GEMINI_API_KEY=your_api_key_here</pre><p>The .env file keeps the API key separate from our Python code.</p><h4>Step 2: Protect the API Key</h4><p>Create a .gitignore file and add:</p><pre>.env</pre><p>This prevents the API key from being uploaded to GitHub.</p><h4>Step 3: Install Required Libraries</h4><pre>pip install google-genai python-dotenv</pre><ol><li>google-genai → connects our application with the Gemini API.</li><li>python-dotenv → loads the API key from the .env file.</li></ol><h4>Step 4: Connect the Python Application</h4><pre>import os<br>from dotenv import load_dotenv<br>from google import genai<br>load_dotenv()<br>api_key = os.getenv(&quot;GEMINI_API_KEY&quot;)<br>client = genai.Client(api_key=api_key)</pre><p>Here:</p><ol><li>load_dotenv() loads the .env file.</li><li>os.getenv() gets the API key.</li><li>genai.Client() creates the connection between our Python application and the Gemini API.</li></ol><p>The complete flow is:</p><pre>.env<br>  ↓<br>API Key<br>  ↓<br>Python Application<br>  ↓<br>Gemini Client<br>  ↓<br>Gemini API<br>  ↓<br>LLM</pre><p>Now our application is ready to send its first request to the model.</p><h3>7 . Making Our First LLM Request</h3><p>Now let’s send our first request to the model.</p><pre>import os<br>from dotenv import load_dotenv<br>from google import genai<br>load_dotenv()<br><br>api_key = os.getenv(&quot;GEMINI_API_KEY&quot;)<br>client = genai.Client(api_key=api_key)<br>response = client.models.generate_content(<br>    model=&quot;gemini-2.5-flash&quot;,<br>    contents=&quot;Explain machine learning in simple words.&quot;<br>)<br><br>print(response.text)</pre><p>Our application is now communicating with an LLM through an API.</p><p>The flow is:</p><pre>Python Program<br>      ↓<br>Gemini API<br>      ↓<br>Gemini Model<br>      ↓<br>Generated Response<br>      ↓<br>response.text<br>      ↓<br>Python Program (Output)</pre><h3>8. Understanding the Gemini API Code</h3><p>Now let’s understand the main parts used when sending a request to an LLM.</p><pre>from google.genai import types<br>response = client.models.generate_content(<br>    model=&quot;gemini-2.5-flash&quot;,<br>    contents=&quot;Explain machine learning in simple words.&quot;,<br>    config=types.GenerateContentConfig(<br>        system_instruction=&quot;You are a Python tutor. Explain concepts in simple words.&quot;,<br>        temperature=0.5,<br>        max_output_tokens=200<br>    )<br>)<br>print(response.text)</pre><h4>1. client</h4><pre>client.models.generate_content()</pre><p>client is used by our Python application to communicate with the Gemini API.</p><pre>Python Application → Client → Gemini API → Model</pre><h4>2. model</h4><pre>model=&quot;gemini-2.5-flash&quot;</pre><p>model specifies <strong>which LLM will process our request</strong>.</p><h4>3. contents</h4><pre>contents=&quot;Explain machine learning in simple words.&quot;</pre><p>contents represents the <strong>actual user input or question</strong> sent to the model.</p><h4>4. system_instruction</h4><pre>system_instruction=&quot;You are a Python tutor. Explain concepts in simple words.&quot;</pre><p>A system instruction defines <strong>how the model should behave</strong>.</p><p>For example:</p><pre>System Instruction → You are a professional customer service assistant.</pre><pre>User Input → The product I received is damaged.</pre><p>The system instruction gives the model its <strong>role and behavior</strong>, while contents gives it the <strong>actual task</strong>. Google provides system_instruction through GenerateContentConfig.</p><h4>5. temperature</h4><pre>temperature=0.5</pre><p>temperature controls how varied or creative the response can be.</p><pre>Lower Temperature → More focused and predictable<br>Higher Temperature → More varied and creative</pre><p>For factual or technical responses, a lower temperature is often useful.</p><h4>6. max_output_tokens</h4><pre>max_output_tokens=200</pre><p>It controls the <strong>maximum amount of output the model can generate</strong>. A larger value allows a longer response.</p><h4>7. Other Optional Settings</h4><p>Gemini also provides other configuration options when needed, such as:</p><ol><li>top_p / top_k → control token selection and response variation.</li><li>stop_sequences → tells the model where to stop generating.</li><li>tools → allows the model to work with supported tools/functions.</li><li>response_schema → can control the structure of the generated output.</li></ol><p>These are optional and can be added depending on the application.</p><h4>8. response.text</h4><pre>print(response.text)</pre><p>The generated result is stored in response, and response.text gives us the final text generated by the model.</p><h4>Complete Flow</h4><pre>System Instruction<br>        +<br>User Input (contents)<br>        +<br>Model Configuration<br>        ↓<br>Python Application<br>        ↓<br>Gemini Client<br>        ↓<br>Gemini API<br>        ↓<br>LLM<br>        ↓<br>Generated Response<br>        ↓<br>response.text</pre><p>In simple terms:</p><pre>client             → Communicates with the API<br>model              → Selects the LLM<br>contents           → User&#39;s actual input<br>system_instruction → Defines model behavior<br>temperature        → Controls response variation<br>max_output_tokens  → Controls maximum response length<br>response.text      → Gets the generated answer</pre><p>These are the basic components we use to <strong>control what we send to an LLM and how we want it to respond</strong>.</p><h3>9. LLM vs API vs Application</h3><p>These three concepts are easy to confuse, so let’s separate them.</p><h4>LLM</h4><p>The model that understands and generates language.</p><pre>Gemini<br>GPT<br>Claude<br>Llama</pre><h4>API</h4><p>The communication interface used by our application to access a hosted model.</p><pre>Application → API → Model</pre><h4>Application</h4><p>The actual software the user interacts with.</p><p>For example:</p><pre>Chatbot<br>Website<br>Python Program<br>Customer Support Tool<br>AI Assistant</pre><p>The complete architecture can therefore look like:</p><pre>             USER<br>               ↓<br>        Python Application<br>               ↓<br>       Prepare the Request<br>               ↓<br>       Add Instructions<br>               ↓<br>       Add Conversation Context<br>               ↓<br>              API<br>               ↓<br>              LLM<br>               ↓<br>        Generated Response<br>               ↓<br>              API<br>               ↓<br>        Python Application<br>               ↓<br>             USER</pre><h3>Conclusion</h3><p>LLM APIs make it easier to bring powerful language models into real applications without downloading or managing large models locally. By understanding the role of the <strong>LLM, API, API key, client, system instructions, user input, and model parameters</strong>, we can clearly understand how a Python application sends a request and receives a response. This basic flow is the foundation for building more advanced applications such as <strong>chatbots, AI assistants, customer-support systems, RAG applications, and AI agents</strong>.</p><h3>Stay Connected</h3><p>If you found this blog helpful and want to learn more about <strong>Python, Machine Learning, NLP, Generative AI, LLMs, and practical AI projects</strong>, feel free to connect with me on <strong>LinkedIn</strong> and follow me on <strong>Medium</strong>.</p><p>I’ll continue sharing simple explanations, practical examples, and what I learn while exploring AI and LLM development.</p><p><strong>Medium : </strong><a href="https://medium.com/@karanveernetsquaresoftwares"><strong><em>Click Here</em></strong></a><br><strong>LinkedIn : </strong><a href="http://www.linkedin.com/in/karanveer-singh-926a0b287"><strong><em>Click Here</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87cd2cb52bcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hugging Face Pipelines : A Simple Way to Use Pretrained AI Models]]></title>
            <link>https://karanveersingh05.medium.com/hugging-face-pipelines-a-simple-way-to-use-pretrained-ai-models-87e9c039876f?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/87e9c039876f</guid>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 08:46:22 GMT</pubDate>
            <atom:updated>2026-08-21T09:35:01.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6U6HFC8wnTtqHHNR42ZRVA.png" /></figure><p>Artificial Intelligence can look difficult when we hear terms like <strong>Transformers, tokenizers, pretrained models, and inference</strong>.</p><p>But Hugging Face makes it much easier to start using AI models in Python.</p><p>One of the easiest ways to use a pretrained model is with the <strong>pipeline()</strong> function.</p><p>In this blog, we will understand what a pipeline is, how it works, and how we can use it for tasks like <strong>sentiment analysis and text generation</strong>.</p><h3>1. What Is Hugging Face?</h3><p><strong>Hugging Face</strong> is a popular AI platform and open-source community that provides many pretrained machine learning and deep learning models.</p><p>A pretrained model is a model that has already learned from a large amount of data.</p><p>For example, suppose we want to create a system that tells us whether a customer review is positive or negative.</p><p>Without using a pretrained model, we may have to:</p><ol><li>Collect a dataset.</li><li>Clean the data.</li><li>Tokenize the text.</li><li>Load a model.</li><li>Train or fine-tune it.</li><li>Evaluate the model.</li><li>Write prediction code.</li></ol><p>This is useful when we want to understand the complete process, but it requires more code and time.</p><p>I have explained this manual approach in my previous Medium article using <strong>Hugging Face and DistilBERT</strong>, where the complete process includes dataset loading, tokenization, training, evaluation, and prediction.</p><p><strong>Previous article:</strong> [Add your DistilBERT Medium article link here]</p><p>Once we understand the manual process, we can see why Hugging Face pipelines are so useful.</p><h3>2. What Is a Pipeline?</h3><p>A <strong>pipeline</strong> is a simple way to use a pretrained model without manually handling every step.</p><p>For example:</p><pre>from transformers import pipeline<br>classifier = pipeline(&quot;sentiment-analysis&quot;)</pre><p>With only this code, Hugging Face prepares a model that can perform sentiment analysis.</p><p>The basic flow is:</p><pre>Text Input<br>    ↓<br>Tokenizer<br>    ↓<br>Pretrained Model<br>    ↓<br>Prediction</pre><p>The pipeline handles most of these steps automatically.</p><h3>3. Pipeline vs Manual Approach</h3><p>The manual approach may look like:</p><pre>Dataset<br>   ↓<br>Tokenizer<br>   ↓<br>Model<br>   ↓<br>Training / Fine-Tuning<br>   ↓<br>Evaluation<br>   ↓<br>Prediction</pre><p>Using a pipeline for inference can look much simpler:</p><pre>Input<br>   ↓<br>pipeline()<br>   ↓<br>Output</pre><p>Both approaches are useful.</p><p>This approach helps us understand what is happening behind the model instead of only using a ready-made solution.</p><p>If you want to understand this process with a practical Machine Learning example, you can refer to my previous Medium article:</p><p><strong>Read my previous Machine Learning article here: </strong><a href="https://medium.com/@karanveernetsquaresoftwares/sentiment-analysis-with-distilbert-a-complete-fine-tuning-guide-14161fcd677a?sharedUserId=karanveernetsquaresoftwares"><strong><em>[Click Here]</em></strong></a></p><p>Once we understand the manual approach, it becomes easier to understand why Hugging Face pipeline() is so useful. It handles many steps for us and allows us to use pretrained models with much less code.</p><h3>4. Why Use Pipelines?</h3><p>Hugging Face pipelines are useful because they:</p><ol><li>Require less code.</li><li>Make pretrained models easy to use.</li><li>Help beginners experiment with AI.</li><li>Support many different tasks.</li><li>Are useful for prototypes and small projects.</li><li>Allow us to test models quickly.</li></ol><p>Some common pipeline tasks include:</p><pre>pipeline(&quot;sentiment-analysis&quot;)<br>pipeline(&quot;text-generation&quot;)<br>pipeline(&quot;summarization&quot;)<br>pipeline(&quot;question-answering&quot;)<br>pipeline(&quot;translation&quot;)<br>pipeline(&quot;ner&quot;)</pre><h3>5. Sentiment Analysis Using Pipeline</h3><p>Sentiment analysis is used to understand whether a piece of text expresses a positive or negative feeling.</p><p>A simple example is:</p><pre>from transformers import pipeline<br>classifier = pipeline(&quot;sentiment-analysis&quot;)<br>text = input(&quot;Enter text : &quot;)<br>result = classifier(text)<br>print(f&quot;Sentiment : {result[0][&#39;label&#39;]}&quot;)<br>print(f&quot;Confidence : {result[0][&#39;score&#39;]}&quot;)</pre><p>Suppose the user enters:</p><pre>I really love this product.</pre><p>The output may look like:</p><pre>Sentiment : POSITIVE<br>Confidence : 0.999</pre><p>The label tells us the predicted sentiment, while the score tells us how confident the model is about its prediction.</p><h3>Real-Life Example</h3><p>Imagine an online shopping company receives hundreds of customer reviews every day.</p><p>Instead of reading every review manually, sentiment analysis can help separate them into:</p><pre>Customer Reviews<br>      ↓<br>Sentiment Model<br>      ↓<br>Positive / Negative</pre><p>The company can then quickly find unhappy customers and respond to them.</p><h3>6. Analyzing Multiple Reviews</h3><p>A pipeline can also process multiple inputs together.</p><pre>from transformers import pipeline<br>classifier = pipeline(&quot;sentiment-analysis&quot;)<br>texts = [<br>    &quot;I love this product.&quot;,<br>    &quot;This product is terrible.&quot;,<br>    &quot;The delivery was very fast.&quot;<br>]<br>results = classifier(texts)<br>for i, result in enumerate(results, start=1):<br>    print(f&quot;Review {i} : {result[&#39;label&#39;]} | {result[&#39;score&#39;]}&quot;)</pre><p>This is useful when we have many customer reviews.</p><p>We can also calculate:</p><pre>Total Reviews<br>Positive Reviews<br>Negative Reviews<br>Average Confidence</pre><p>This turns a small sentiment program into a simple review-analysis system.</p><h3>7. Text Generation Using Pipeline</h3><p>Pipelines are not only used for classification.</p><p>We can also generate text.</p><p>For example:</p><pre>from transformers import pipeline<br>Generator = pipeline(<br>    &quot;text-generation&quot;,<br>    model=&quot;Qwen/Qwen2.5-0.5B-Instruct&quot;<br>)<br>topic = input(&quot;Enter the topic : &quot;)<br>prompt = (<br>    &quot;Write a short paragraph about &quot;<br>    + topic<br>)<br>Result = Generator(<br>    prompt,<br>    max_new_tokens=60,<br>    return_full_text=False<br>)<br>print(Result[0][&quot;generated_text&quot;])</pre><p>If we enter:</p><pre>Artificial Intelligence</pre><p>the model will generate a short paragraph about AI.</p><p>The flow becomes:</p><pre>User Prompt<br>    ↓<br>Text Generation Model<br>    ↓<br>Generated Content</pre><h3>8. Why Is the Prompt Important?</h3><p>The model needs a clear instruction.</p><p>For example, this prompt is not very clear:</p><pre>Python</pre><p>The model does not know exactly what we want.</p><p>A better prompt would be:</p><pre>Write a short beginner-friendly paragraph about Python.</pre><p>We can make it even clearer:</p><pre>Write a short beginner-friendly paragraph about Python.<br>Use simple language.<br>Start directly with the content.</pre><p>Clear instructions usually make it easier for the model to understand the required task.</p><h3>9. One Model Can Perform Different Writing Tasks</h3><p>The same text-generation model can be used for different tasks by changing the prompt.</p><p>For example:</p><pre>Write a blog introduction about Machine Learning.</pre><p>or:</p><pre>Write a product description about a smartwatch.</pre><p>or:</p><pre>Write a social media post about Artificial Intelligence.</pre><p>The model remains the same.</p><p>Only the instruction changes.</p><pre>Same Model<br>    ↓<br>Different Prompt<br>    ↓<br>Different Output</pre><p>This makes text-generation models very flexible.</p><h3>10. Combining Sentiment Analysis and Text Generation</h3><p>We can combine two pipelines in one program. First, the <strong>sentiment-analysis pipeline</strong> understands the customer’s review. Then, the <strong>text-generation pipeline</strong> creates a suitable customer-service response.</p><p>For example:</p><pre>from transformers import pipeline<br><br>classifier = pipeline(&quot;sentiment-analysis&quot;)<br>Generator = pipeline(<br>    &quot;text-generation&quot;,<br>    model=&quot;Qwen/Qwen2.5-0.5B-Instruct&quot;<br>)<br><br>user_text = input(&quot;Enter customer review : &quot;)<br>result = classifier(user_text)<br>print(f&quot;Sentiment : {result[0][&#39;label&#39;]}&quot;)<br><br>prompt = f&quot;&quot;&quot;<br>You are a professional customer service representative.<br>Customer sentiment: {result[0][&#39;label&#39;]}<br>Customer review:<br>{user_text}<br>Write a short and polite response to the customer.<br>If the review is negative, apologize and offer help.<br>If the review is positive, thank the customer.<br>Do not repeat the review.<br>Start directly with the response.<br>&quot;&quot;&quot;<br><br>response = Generator(<br>    prompt,<br>    max_new_tokens=60,<br>    num_return_sequences=1,<br>    return_full_text=False<br>)<br><br>print(f&quot;AI Response : {response[0][&#39;generated_text&#39;]}&quot;)</pre><p>Suppose the customer enters:</p><pre>The product arrived damaged and the delivery was very late.</pre><p>The program may produce:</p><pre>Sentiment : NEGATIVE<br>AI Response :<br>We apologize for the inconvenience caused by the damaged product and<br>delayed delivery. Please contact our support team so we can help<br>resolve the issue as quickly as possible.</pre><p>The complete process is:</p><pre>Customer Review<br>      ↓<br>Sentiment Analysis Pipeline<br>      ↓<br>POSITIVE / NEGATIVE<br>      ↓<br>Sentiment + Review added to Prompt<br>      ↓<br>Text Generation Pipeline<br>      ↓<br>Customer Service Response</pre><p>This is a simple real-life example of how <strong>two different AI pipelines can work together in one application</strong>.</p><h3>Conclusion</h3><p>Hugging Face pipelines are a simple way to start working with pretrained AI models.</p><p>With only a few lines of Python, we can build programs for <strong>sentiment analysis, text generation, customer-review analysis, and many other AI tasks</strong>.</p><p>We started with:</p><pre>pipeline(&quot;sentiment-analysis&quot;)</pre><p>and saw how the same idea can grow into a small AI application.</p><p>The important thing is to understand the flow:</p><pre>Real-Life Problem<br>      ↓<br>Choose the Task<br>      ↓<br>Choose the Pipeline<br>      ↓<br>Give Input<br>      ↓<br>Get Model Output<br>      ↓<br>Use It in an Application</pre><p>Pipelines are a great starting point for beginners because they allow us to experiment with real AI models without making the first step unnecessarily complicated.</p><h3>Stay Connected</h3><p>If you found this blog helpful and want to explore more content on <strong>Python, Machine Learning, NLP, Generative AI, and LLMs</strong>, feel free to follow me on:</p><p>🔗 <a href="http://www.linkedin.com/in/karanveer-singh-926a0b287"><strong>LinkedIn</strong></a><br>✍️ <a href="https://medium.com/@karanveernetsquaresoftwares"><strong>Medium</strong></a></p><p>I’ll keep sharing what I learn through simple explanations, practical examples, and hands-on projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87e9c039876f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis with DistilBERT: A Complete Fine-Tuning Guide]]></title>
            <link>https://karanveersingh05.medium.com/sentiment-analysis-with-distilbert-a-complete-fine-tuning-guide-14161fcd677a?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/14161fcd677a</guid>
            <category><![CDATA[distilbert]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 17:44:53 GMT</pubDate>
            <atom:updated>2026-08-14T05:18:59.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4_LbL0WyD5sa_ndqnkOgSQ.png" /></figure><p>In this beginner-friendly guide, we will explore how to <strong>fine-tune DistilBERT using Hugging Face</strong> for sentiment analysis.</p><p>We will understand the complete workflow step by step, including preparing the data, tokenization, loading a pre-trained Transformer model, setting training parameters, fine-tuning the model, evaluating its performance, and making predictions on new text.</p><h3>💡 Before You Start</h3><p>For a better understanding of the concepts covered in this article, I recommend going through my previous articles first. These will help you build a strong foundation in <strong>Python and Machine Learning</strong> before moving toward Transformer-based NLP models.</p><p><em>📘 </em><strong><em>1. </em></strong><a href="https://medium.com/@karanveernetsquaresoftwares/introduction-to-python-35c60be8f972"><strong><em>Introduction to Python</em></strong></a></p><p><em>📘 </em><strong><em>2. </em></strong><a href="https://medium.com/@karanveernetsquaresoftwares/python-functions-a-beginner-friendly-guide-f6918533940d"><strong><em>Python Functions: A Beginner-Friendly Guide</em></strong></a></p><p><em>📘 </em><strong><em>3. </em></strong><a href="https://medium.com/@karanveernetsquaresoftwares/linear-regression-and-logistic-regression-in-machine-learning-6ab64d35e489"><strong><em>Linear Regression and Logistic Regression in Machine Learning</em></strong></a></p><p>Going through these articles will make it easier to understand the transition from <strong><em>Python fundamentals → Machine Learning → NLP → Transformers → DistilBERT Fine-Tuning</em></strong><em>.</em></p><p>This article is designed for beginners who want to understand how <strong>Hugging Face, Transformers, DistilBERT, tokenization, and fine-tuning</strong> work together in a practical NLP project using Python.</p><h3>1. Introduction</h3><p>Natural Language Processing (<strong>NLP</strong>) is a branch of Artificial Intelligence that helps computers understand and work with human language.</p><p>In this article, we will learn how to <strong>fine-tune DistilBERT using Hugging Face</strong> for sentiment analysis. The explanation is kept simple so that even a beginner can follow the complete process.</p><p><strong>Real-Life Example :</strong></p><p>Suppose an online store receives customer reviews</p><h4>a. First review :</h4><pre>&quot;The product is amazing and works perfectly.&quot;</pre><p>The model should predict : <strong>Positive</strong></p><h4>b. Second review :</h4><pre>&quot;The product quality is very poor.&quot;</pre><p>The model should predict : <strong>Negative</strong></p><p>We do not need to create a language model from the beginning. We can use an already trained model called <strong>DistilBERT</strong> and teach it to do our specific task. This extra training is called <strong>fine-tuning</strong>.</p><pre>Pre-trained DistilBERT<br>(already trained to understand language)<br>        ↓<br>Text Dataset<br>(examples of text with correct labels)<br>        ↓<br>Fine-Tuning<br>(train DistilBERT on our specific task)<br>        ↓<br>Sentiment Prediction<br>(predict whether the text is Positive or Negative)</pre><p>By the end of this article, you will understand how <strong>Hugging Face, DistilBERT, tokenization, training, evaluation, and prediction</strong> work together in a complete NLP project.</p><h3>2. What is Hugging Face?</h3><p><strong>Hugging Face</strong> is a platform and Python library that provides many ready-to-use AI and NLP models.</p><p>Instead of creating a large language model from the beginning, we can use models that are already trained and available on Hugging Face.</p><p>For example:</p><pre>Hugging Face<br>   ↓<br>Choose a pre-trained model<br>(DistilBERT, BERT, etc.)<br>   ↓<br>Use it in Python<br>   ↓<br>Train it for our own task</pre><p>Simple Real-Life Example :</p><p>Think of Hugging Face like an <strong>app store for AI models</strong>.</p><p>When you need an app, you usually do not create it from scratch. You download an existing app and use it.</p><p>Similarly, with Hugging Face:</p><pre>Need an NLP model<br>        ↓<br>Find a ready-made model<br>        ↓<br>Download it<br>        ↓<br>Customize it for your task</pre><p>In our project, we use Hugging Face to load :</p><pre>model = AutoModelForSequenceClassification.from_pretrained(<br>    model_name,<br>    num_labels=2<br>)</pre><p><strong>AutoModelForSequenceClassification</strong> : loads a model for text classification</p><h3>3. What is DistilBERT?</h3><p><strong>DistilBERT</strong> is a smaller and faster version of <strong>BERT</strong>, which is a popular language model used in NLP.</p><p>You can think of DistilBERT as a model that already has a basic understanding of English.</p><p>For example, it can understand that these sentences are different:</p><pre>&quot;I love this movie.&quot;<br>&quot;I hate this movie.&quot;</pre><p>It understands the meaning of words based on the sentence around them.</p><h4>Simple way to understand</h4><p>Think of DistilBERT like a <strong>student who already knows English</strong>.So we are not teaching it English from the beginning.</p><pre>DistilBERT<br>(already knows general English)<br>        ↓<br>We give it our examples<br>        ↓<br>We train it for our task<br>        ↓<br>It learns sentiment analysis</pre><h4>Why use DistilBERT?</h4><ol><li>Smaller than BERT</li><li>Faster to train</li><li>Faster to make predictions</li><li>Good for beginners and practical NLP projects</li></ol><p>In your project, you select DistilBERT like this:</p><pre>model_name = &quot;distilbert-base-uncased&quot;</pre><h3>4. What is Fine-Tuning?</h3><p><strong>Fine-tuning</strong> means taking a model that is already trained and training it a little more for our own specific task.</p><p>Think of it like a student who already knows English, but now we teach the student how to identify whether a review is <strong>Positive or Negative</strong>.</p><pre>Pre-trained DistilBERT (already understands language)<br>                 ↓<br>Give it our labeled data (Positive and Negative examples)<br>                 ↓ <br>Fine-Tuning (train it for our specific task)<br>                 ↓<br>Sentiment Model (predicts Positive or Negative)</pre><p>In our project, Hugging Face performs fine-tuning when we run:</p><pre>trainer.train()</pre><h3>5. How the Complete Workflow Works</h3><p>Before writing the complete code, it is useful to understand the full process in a simple way.</p><p>Our sentiment analysis project follows these steps:</p><pre>Text Dataset (reviews with Positive/Negative labels)<br>                   ↓ <br>Tokenizer (converts text into numbers)<br>                   ↓ <br>Tokenized Data (data that DistilBERT can understand)<br>                   ↓ <br>Pre-trained DistilBERT (already understands language)<br>                   ↓ <br>Fine-Tuning (train the model for our task)<br>                   ↓ <br>Evaluation (check how well the model performs)<br>                   ↓ <br>Prediction (Predict Positive or Negative)</pre><h3>6. Installing the Required Libraries</h3><p>Before we start coding, we need to install the Python libraries required for this project.</p><p>Use this command in your terminal or command prompt:</p><pre>pip install transformers datasets evaluate torch</pre><p>These libraries have different roles:</p><ol><li><strong>transformers</strong>→ provides DistilBERT, tokenizer, Trainer, and other Hugging Face tools.</li><li><strong>datasets</strong> → helps us load and work with datasets.</li><li><strong>evaluate</strong> → helps us calculate model performance such as accuracy.</li><li><strong>torch </strong>→ PyTorch library used to run and train the model.</li></ol><h3>7. Importing the Required Libraries</h3><p>Now that the libraries are installed, we need to import the tools that we will use in our project</p><pre>from datasets import load_dataset <br>from transformers import ( <br>               AutoTokenizer,<br>               AutoModelForSequenceClassification,<br>               TrainingArguments,<br>               Trainer<br>                         )<br>import numpy as np <br>import evaluate <br>import torch</pre><p>What does each import do?</p><ol><li><strong>load_dataset</strong> → loads the dataset.</li><li><strong>AutoTokenizer </strong>→ converts text into numbers that DistilBERT can understand.</li><li><strong>AutoModelForSequenceClassification</strong> → loads DistilBERT for a classification task.</li><li><strong>TrainingArguments</strong> → stores the settings used during training.</li><li>Trainer → handles model training and evaluation.</li><li><strong>numpy</strong> → helps with numerical operations.</li><li><strong>evaluate</strong> → helps us calculate metrics such as accuracy.</li><li><strong>torch</strong> → runs the model and is also used during prediction.</li></ol><h3>8. Loading the Dataset</h3><p>Now we need some text data to train our model.</p><p>Hugging Face provides many ready-to-use datasets. We can load a dataset using the load_dataset() function.</p><pre>dataset = load_dataset(&quot;stanfordnlp/imdb&quot;)</pre><p>Here:</p><ol><li><strong>load_dataset() </strong>→ downloads and loads the dataset.</li><li><strong>“stanfordnlp/imdb” </strong>→ tells Hugging Face which dataset we want to use.</li></ol><h3>9. Preparing a Smaller Dataset for Practice</h3><p>The original dataset contains a large number of reviews. For learning and practice, we can use a smaller part of it so that training is faster.</p><pre>train_dataset = (<br>    dataset[&quot;train&quot;]<br>    .shuffle(seed=42)<br>    .select(range(2000))<br>)<br><br>test_dataset = (<br>    dataset[&quot;test&quot;]<br>    .shuffle(seed=42)<br>    .select(range(500))<br>)</pre><p>Here:</p><ol><li><strong>dataset[“train”] </strong>→ selects the training data.</li><li><strong>dataset[“test”]</strong> → selects the testing data.</li><li><strong>shuffle(seed=42)</strong> → randomly mixes the data.</li><li><strong>select(range(2000)) </strong>→ selects 2000 reviews for training.</li><li><strong>select(range(500)) </strong>→ selects 500 reviews for testing.</li></ol><h3>10. Understanding the Dataset</h3><p>Before training the model, it is useful to look at one sample from the dataset.</p><pre>print(train_dataset[0])</pre><p>This may give output like:</p><pre>{<br>    &quot;text&quot;: &quot;This movie was really enjoyable...&quot;,<br>    &quot;label&quot;: 1<br>}</pre><p>Each sample mainly contains two things:</p><ol><li><strong>text </strong>→ the review or sentence given to the model.</li><li><strong>label</strong> → the correct answer for that text.</li></ol><p>Simple Example :</p><pre>Text:<br>&quot;I really loved this movie.&quot;<br>Label: 1</pre><p>This means the review is <strong>Positive</strong>.</p><h3>11. Selecting a Pre-Trained Model</h3><p>Now we select the pre-trained DistilBERT model:</p><pre>model_name = &quot;distilbert-base-uncased&quot;</pre><p>Here:</p><ol><li><strong>distilbert-base-uncased</strong> → the DistilBERT model we want to use.</li><li><strong>uncased</strong> → uppercase and lowercase words are treated similarly.</li></ol><p>Example:</p><pre>&quot;Movie&quot; ≈ &quot;movie&quot;</pre><p>In simple words, this line tells Hugging Face which pre-trained model we want to use.</p><h3>12. Loading the Tokenizer</h3><p>Now we load the tokenizer for DistilBERT.</p><pre>tokenizer = AutoTokenizer.from_pretrained(model_name)</pre><p>The tokenizer converts normal text into numbers that DistilBERT can understand.</p><p>Example:</p><pre>&quot;I love this movie&quot;<br>        ↓<br>Tokenizer<br>        ↓<br>Token IDs<br>        ↓<br>Numbers for DistilBERT</pre><p>In simple words:</p><p><strong>Tokenizer = Text → Numbers</strong></p><h3>13. Understanding Tokenization</h3><p>Tokenization means breaking text into smaller parts and converting them into numbers.</p><p>Example:</p><pre>text = &quot;I really enjoyed this movie.&quot;<br><br>print(tokenizer.tokenize(text))<br>print(tokenizer(text)[&quot;input_ids&quot;])</pre><p>Flow:</p><pre>&quot;I really enjoyed this movie.&quot;<br>        ↓<br>Tokens<br>        ↓<br>Token IDs<br>        ↓<br>Numbers that DistilBERT can understand</pre><p>In simple words:</p><p><strong>Tokenization = Text → Tokens → Numbers</strong></p><h3>14. Tokenizing the Complete Dataset</h3><p>Now we tokenize all training and testing text.</p><pre>def tokenize_function(examples):<br>    return tokenizer(<br>        examples[&quot;text&quot;],<br>        truncation=True,<br>        padding=&quot;max_length&quot;,<br>        max_length=128<br>    )<br><br>tokenized_train = train_dataset.map(<br>    tokenize_function,<br>    batched=True<br>)<br>tokenized_test = test_dataset.map(<br>    tokenize_function,<br>    batched=True<br>)</pre><p>Here:</p><ol><li><strong>truncation=True</strong> → cuts text if it is too long.</li><li><strong>padding=”max_length”</strong> → makes all inputs the same length.</li><li><strong>max_length=128</strong> → keeps a maximum of 128 tokens.</li><li><strong>batched=True </strong>→ processes multiple reviews together.</li></ol><h3>15. Loading the Pre-Trained DistilBERT Model</h3><p>Now we load DistilBERT for our classification task.</p><pre>model = AutoModelForSequenceClassification.from_pretrained(<br>    model_name,<br>    num_labels=2<br>)</pre><p>Here:</p><ol><li><strong>model_name</strong> → loads the DistilBERT model.</li><li><strong>num_labels</strong>=2 → we have two classes:</li><li>0 = Negative ,1 = Positive</li></ol><h3>16. Setting Up the Evaluation Metric</h3><p>Now we use <strong>accuracy</strong> to check how well our model performs.</p><pre>accuracy = evaluate.load(&quot;accuracy&quot;)</pre><p>Then we create a function:</p><pre>def compute_metrics(eval_pred):<br>    predictions, labels = eval_pred<br>    predictions = np.argmax(predictions, axis=1)<br>    return accuracy.compute(<br>        predictions=predictions,<br>        references=labels<br>    )</pre><p>Here:</p><ol><li><strong>predictions </strong>→ model outputs</li><li><strong>labels </strong>→ correct answers</li><li><strong>np.argmax()</strong> → selects the class with the highest score</li><li><strong>accuracy.compute() </strong>→ calculates accuracy</li></ol><h3>17. Setting the Training Arguments</h3><p>Now we define the settings used to train the model.</p><pre>training_args = TrainingArguments(<br>    output_dir=&quot;./sentiment_model&quot;,<br>    eval_strategy=&quot;epoch&quot;,<br>    learning_rate=2e-5,<br>    per_device_train_batch_size=16,<br>    per_device_eval_batch_size=16,<br>    num_train_epochs=2,<br>    weight_decay=0.01,<br>    report_to=&quot;none&quot;<br>)</pre><p>Here:</p><ol><li><strong>output_dir</strong> → where training results are saved.</li><li><strong>eval_strategy=”epoch”</strong> → evaluates after each epoch.</li><li><strong>learning_rate=2e-5 </strong>→ controls how fast the model learns.</li><li><strong>batch_size=16 </strong>→ processes 16 examples at a time.</li><li><strong>num_train_epochs=2</strong> → trains on the dataset 2 times.</li><li><strong>weight_decay=0.01 </strong>→ helps reduce overfitting.</li><li><strong>report_to=”none”</strong> → disables external logging.</li></ol><h3>19. Creating the Hugging Face Trainer</h3><p>Now we create the Trainer, which manages the training and evaluation process.</p><pre>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_train,<br>    eval_dataset=tokenized_test,<br>    compute_metrics=compute_metrics<br>)</pre><p>Here:</p><ol><li><strong>model </strong>→ DistilBERT model</li><li><strong>args </strong>→ training settings</li><li><strong>train_dataset</strong> → data used for training</li><li><strong>eval_dataset</strong> → data used for evaluation</li><li><strong>compute_metrics</strong> → calculates accuracy</li></ol><h3>20. Fine-Tuning DistilBERT</h3><p>Now we start training the model on our dataset.</p><pre>trainer.train()</pre><h3>21. Evaluating the Fine-Tuned Model</h3><p>After training, we check how well the model performs on the testing data.</p><pre>results = trainer.evaluate()<br>print(results)</pre><p>Here:</p><ol><li><strong>trainer.evaluate() </strong>→ tests the model.</li><li><strong>results </strong>→ stores values like accuracy and loss.</li></ol><h3>22. Saving the Fine-Tuned Model</h3><p>After training, we save the model so we can use it later without training again.</p><pre>save_path = &quot;./fine_tuned_sentiment_model&quot;<br>trainer.save_model(save_path)<br>tokenizer.save_pretrained(save_path)</pre><p>Here:</p><ol><li><strong>save_model()</strong> → saves the trained DistilBERT model.</li><li><strong>save_pretrained()</strong> → saves the tokenizer.</li><li><strong>save_path</strong> → folder where the files are stored</li></ol><h3>23. Making Predictions on New Text</h3><p>After training, we can use the model to predict the sentiment of new text.</p><pre>def predict_sentiment(text):<br>    inputs = tokenizer(<br>        text,<br>        return_tensors=&quot;pt&quot;,<br>        truncation=True,<br>        padding=True<br>    )<br>    inputs = {<br>        key: value.to(model.device)<br>        for key, value in inputs.items()<br>    }<br>    with torch.no_grad():<br>        outputs = model(**inputs)<br>    prediction = torch.argmax(<br>        outputs.logits,<br>        dim=1<br>    ).item()<br>    if prediction == 1:<br>        return &quot;Positive&quot;<br>    else:<br>        return &quot;Negative&quot;</pre><p>Here:</p><ol><li><strong>tokenizer()</strong> → converts the new text into model-readable numbers.</li><li><strong>model(**inputs) </strong>→ sends the text to DistilBERT.</li><li><strong>torch.argmax() </strong>→ selects the class with the highest score.</li><li>1 → Positive , 0 → Negative</li></ol><h3>24. Complete Code</h3><p>Here is the complete code for fine-tuning DistilBERT for sentiment analysis:</p><pre>from datasets import load_dataset<br>from transformers import (<br>    AutoTokenizer,<br>    AutoModelForSequenceClassification,<br>    TrainingArguments,<br>    Trainer<br>)<br>import numpy as np<br>import evaluate<br>import torch<br><br># Load dataset<br>dataset = load_dataset(&quot;stanfordnlp/imdb&quot;)<br><br># Create smaller datasets<br>train_dataset = (<br>    dataset[&quot;train&quot;]<br>    .shuffle(seed=42)<br>    .select(range(2000))<br>)<br>test_dataset = (<br>    dataset[&quot;test&quot;]<br>    .shuffle(seed=42)<br>    .select(range(500))<br>)<br><br># Select model<br>model_name = &quot;distilbert-base-uncased&quot;<br><br># Load tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br><br># Tokenize dataset<br>def tokenize_function(examples):<br>    return tokenizer(<br>        examples[&quot;text&quot;],<br>        truncation=True,<br>        padding=&quot;max_length&quot;,<br>        max_length=128<br>    )<br><br>tokenized_train = train_dataset.map(<br>    tokenize_function,<br>    batched=True<br>)<br>tokenized_test = test_dataset.map(<br>    tokenize_function,<br>    batched=True<br>)<br><br># Load DistilBERT<br>model = AutoModelForSequenceClassification.from_pretrained(<br>    model_name,<br>    num_labels=2<br>)<br><br># Accuracy metric<br>accuracy = evaluate.load(&quot;accuracy&quot;)<br><br>def compute_metrics(eval_pred):<br>    predictions, labels = eval_pred<br>    predictions = np.argmax(predictions, axis=1)<br>    return accuracy.compute(<br>        predictions=predictions,<br>        references=labels<br>    )<br><br># Training settings<br>training_args = TrainingArguments(<br>    output_dir=&quot;./sentiment_model&quot;,<br>    eval_strategy=&quot;epoch&quot;,<br>    learning_rate=2e-5,<br>    per_device_train_batch_size=16,<br>    per_device_eval_batch_size=16,<br>    num_train_epochs=2,<br>    weight_decay=0.01,<br>    report_to=&quot;none&quot;<br>)<br><br># Create Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_train,<br>    eval_dataset=tokenized_test,<br>    compute_metrics=compute_metrics<br>)<br><br># Fine-tune model<br>trainer.train()<br><br># Evaluate model<br>results = trainer.evaluate()<br>print(results)<br><br># Save model<br>save_path = &quot;./fine_tuned_sentiment_model&quot;<br>trainer.save_model(save_path)<br>tokenizer.save_pretrained(save_path)<br><br># Prediction function<br>def predict_sentiment(text):<br>    inputs = tokenizer(<br>        text,<br>        return_tensors=&quot;pt&quot;,<br>        truncation=True,<br>        padding=True<br>    )<br>    inputs = {<br>        key: value.to(model.device)<br>        for key, value in inputs.items()<br>    }<br>    with torch.no_grad():<br>        outputs = model(**inputs)<br>    prediction = torch.argmax(<br>        outputs.logits,<br>        dim=1<br>    ).item()<br>    if prediction == 1:<br>        return &quot;Positive&quot;<br>    else:<br>        return &quot;Negative&quot;<br><br># Test prediction<br>print(<br>    predict_sentiment(<br>        &quot;I really enjoyed this movie!&quot;<br>    )<br>)</pre><h3>25. Understanding the Complete Workflow</h3><p>Now let’s quickly revise the complete process:</p><pre>Load Dataset<br>        ↓<br>Select Training and Testing Data<br>        ↓<br>Load Tokenizer<br>        ↓<br>Convert Text into Tokens/Numbers<br>        ↓<br>Load Pre-trained DistilBERT<br>        ↓<br>Set Training Arguments<br>        ↓<br>Create Trainer<br>        ↓<br>Fine-Tune the Model<br>        ↓<br>Evaluate Accuracy<br>        ↓<br>Save the Model<br>        ↓<br>Predict New Text</pre><h3>26. Conclusion</h3><p>In this article, we learned how to fine-tune <strong>DistilBERT using Hugging Face</strong> for a sentiment analysis task. We covered the complete process, including <strong>loading the dataset, tokenization, model training, evaluation, saving the model, and making predictions</strong>.</p><p>The main idea is simple:</p><p><strong>Use a pre-trained model → train it for your task → evaluate it → use it for predictions.</strong></p><p>With this foundation, you can move on to more advanced NLP tasks and other Transformer models.</p><h3>🚀 Stay Connected &amp; Keep Learning</h3><p>If you enjoyed this article and want to explore more beginner-friendly content on <strong>Python, Machine Learning, NLP, Generative AI, and LLMs</strong>, follow me on Medium:</p><p>👉 <strong>Medium : </strong><a href="https://medium.com/@karanveernetsquaresoftwares"><strong><em>Click Here</em></strong></a></p><p>You can also connect with me on LinkedIn for more <strong>projects, learning updates, practical insights, and upcoming articles</strong>:</p><p>👉 <strong>LinkedIn : </strong><a href="http://www.linkedin.com/in/karanveer-singh-926a0b287"><strong><em>Click Here</em></strong></a></p><p>Let’s keep <strong>learning, building, and growing together. 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14161fcd677a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is NLP and Why is it So Hard? An Introduction for Python Developers]]></title>
            <link>https://karanveersingh05.medium.com/what-is-nlp-and-why-is-it-so-hard-an-introduction-for-python-developers-5dcdd3a66485?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dcdd3a66485</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp-language]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 11:16:23 GMT</pubDate>
            <atom:updated>2026-08-04T11:16:23.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-QJdxKO6Of-nEvyLZgT5A.png" /></figure><p><strong>Natural Language Processing (NLP)</strong> is a multidisciplinary field of Artificial Intelligence (AI) that focuses on the interaction between computers and human language. Its primary goal is to enable machines to read, decipher, understand, and make sense of human languages in a way that is valuable. NLP combines computational linguistics rule-based modeling of human language with statistical, machine learning, and deep learning models.</p><p>Regular search looks for <strong>Keywords</strong>. NLP search (Semantic Search) looks for <strong>Meaning</strong>. Searching for “how to fix a flat” will find results for “tire repair” even if the words don’t match exactly</p><h3>Core Goals of NLP</h3><ol><li><strong>Human-Computer Interaction:</strong> Allowing people to talk or type to devices in everyday language instead of using complex code.</li><li><strong>Data Processing:</strong> Turning large amounts of unstructured text and speech into useful data that computers can analyze.</li><li><strong>Global Communication:</strong> Breaking down language barriers through automated translation and smart assistants</li></ol><h3>Key Areas Where NLP is Used</h3><ul><li><strong>Virtual Assistants</strong>: Siri, Alexa, and Google Assistant process spoken voice commands to perform tasks.</li><li><strong>Search Engines</strong>: Google and Bing analyze user intent to deliver accurate webpage results.</li><li><strong>Translation Tools</strong>: Google Translate and DeepL instantly convert text between different languages.</li><li><strong>AI Chatbots</strong>: Customer service bots answer questions and resolve support tickets automatically.</li><li><strong>Sentiment Analysis</strong>: Brands scan social media reviews to track positive or negative opinions.</li></ul><h3>Challenges in NLP</h3><ol><li><strong>Ambiguity</strong>: Explain how words change meaning based on context.</li><li><strong>Sarcasm</strong>: Detail how tone changes the literal meaning of text.</li><li><strong>Slang &amp; Idioms</strong>: Mention how cultural phrasing complicates literal translation.</li></ol><h3>Key Technical Tasks</h3><p>To process language, NLP systems perform a series of foundational “micro-tasks”:</p><ol><li><strong>Tokenization:</strong> Breaking sentences into smaller units (tokens) like words or sub-words.</li><li><strong>Sentiment Analysis:</strong> Determining the emotional tone (e.g., Is the customer angry or happy?).</li><li><strong>Named Entity Recognition (NER):</strong> Identifying specific people, places, or organizations in a text.</li><li><strong>[Part-of-Speech Tagging]:</strong> Identifying nouns, verbs, and adjectives to understand grammatical structure.</li><li><strong>Speech-to-Text (STT):</strong> Converting spoken audio into digital text for processing.</li></ol><h3>How It Works (The Processing Pipeline)</h3><p>Modern NLP transforms “messy” human speech into “clean” machine data through a structured pipeline:</p><ol><li><strong>Preprocessing :</strong> Cleaning the text (removing “stop words” like <em>the</em> or <em>a</em>) and reducing words to their roots (e.g., “running” becomes “run”).</li><li><strong>Vectorization :</strong> Converting words into numbers (vectors) so the computer can perform math on their meanings.</li><li><strong>Contextual Pass :</strong> The <strong>Attention Mechanism</strong> looks at the entire sentence to decide which words are most important to the meaning.</li><li><strong>Inference :</strong> The model predicts the intent or generates the next part of the conversation.</li></ol><h4>1. Preprocessing</h4><p><strong>a. Lowercasing</strong>:</p><p>Standardizes all characters to avoid duplicate entries for the same word</p><p>Example :</p><pre>import html<br><br>raw_text = &quot;The 2 active Data Scientists couldn&#39;t open emails from hr@company.com! &amp;amp; check details.&quot;<br><br># Convert characters to lowercase and decode HTML text artifacts<br>step1_text = html.unescape(raw_text.lower())<br><br>print(&quot;Step 1 Output:\n&quot;, step1_text)<br># Output: the 2 active data scientists couldn&#39;t open emails from hr@company.com! &amp; check details.</pre><p><strong>b. Noise Removal</strong>:</p><p>Eliminates HTML tags, URLs, punctuation, digits, and special characters.</p><p>Example:</p><pre>import re<br><br># Remove email addresses<br>clean_step = re.sub(r&quot;\S+@\S+&quot;, &quot;&quot;, step1_text)<br><br># Remove numbers<br>clean_step = re.sub(r&quot;\d+&quot;, &quot;&quot;, clean_step)<br><br># Remove special characters, symbols, and punctuation marks<br>clean_step = re.sub(r&quot;[^a-z\s]&quot;, &quot;&quot;, clean_step)<br><br># Standardize messy spacing arrays down to a single clean whitespace block<br>step2_text = re.sub(r&quot;\s+&quot;, &quot; &quot;, clean_step).strip()<br><br>print(&quot;Step 2 Output:\n&quot;, step2_text)<br># Output: the active data scientists couldnt open emails from check details</pre><p><strong>c. Tokenization</strong>:</p><p>Segments continuous strings of text into distinct units (tokens).</p><p>Example :</p><pre># Split the cleaned string into an array of independent word tokens<br>step3_tokens = step2_text.split()<br><br>print(&quot;Step 3 Output:\n&quot;, step3_tokens)<br># Output: [&#39;the&#39;, &#39;active&#39;, &#39;data&#39;, &#39;scientists&#39;, &#39;couldnt&#39;, &#39;open&#39;, &#39;emails&#39;, &#39;</pre><p><strong>d. Stop Word Removal</strong>:</p><p>Filters out frequent, low-information articles and prepositions.</p><p>Example :</p><pre>import nltk<br>from nltk.corpus import stopwords<br><br># Download and fetch the English stopwords resource array<br>nltk.download(&#39;stopwords&#39;, quiet=True)<br>stop_words = set(stopwords.words(&quot;english&quot;))<br><br># Filter tokens, keeping only those not present in the stop words list<br>step4_tokens = [word for word in step3_tokens if word not in stop_words]<br><br>print(&quot;Step 4 Output:\n&quot;, step4_tokens)<br># Output: [&#39;active&#39;, &#39;data&#39;, &#39;scientists&#39;, &#39;couldnt&#39;, &#39;open&#39;, &#39;emails&#39;, &#39;check&#39;,</pre><p><strong>e. Lemmatization</strong>:</p><p>Maps inflected words back to their structurally correct dictionary base form.</p><p>Example :</p><pre>import nltk<br>from nltk.stem import WordNetLemmatizer<br><br># Download and initialize the WordNet database dictionary mapping tool<br>nltk.download(&#39;wordnet&#39;, quiet=True)<br>lemmatizer = WordNetLemmatizer()<br><br># Reconstruct each token into its dictionary base root form<br>step5_tokens = [lemmatizer.lemmatize(word) for word in step4_tokens]<br><br># Join tokens back together into a finalized sentence string<br>final_preprocessed_text = &quot; &quot;.join(step5_tokens)<br><br>print(&quot;Step 5 Output (Final Tokens):\n&quot;, step5_tokens)<br># Output: [&#39;active&#39;, &#39;data&#39;, &#39;scientist&#39;, &#39;couldnt&#39;, &#39;open&#39;, &#39;email&#39;, &#39;check&#39;, &#39;detail&#39;]</pre><h4><strong>2. Vectorization</strong></h4><p><strong>a. Bag of Words :</strong></p><p>The <strong>Bag of Words</strong> model converts unstructured text into a matrix of word counts. It compiles every unique word across all documents to establish a master vocabulary list, then counts how many times each vocabulary word appears in a given document.</p><p>Example :</p><pre>import pandas as pd<br>from sklearn.feature_extraction.text import CountVectorizer<br><br># 1. Define sample text database (Corpus)<br>corpus = [<br>    &quot;I love NLP and Machine Learning.&quot;,<br>    &quot;Machine Learning is amazing&quot;,<br>    &quot;I love learning new things.&quot;<br>]<br><br># 2. Initialize CountVectorizer (The Bag of Words object)<br>vectorizer = CountVectorizer()<br><br># 3. Fit (Creates vocabulary) and Transform (Counts word occurrences)<br>bow_matrix = vectorizer.fit_transform(corpus)<br>vocabulary = vectorizer.get_feature_names_out()<br><br># 4. Display as a readable table (DataFrame)<br>df_bow = pd.DataFrame(<br>    bow_matrix.toarray(), <br>    columns=vocabulary, <br>    index=[&quot;Doc 1&quot;, &quot;Doc 2&quot;, &quot;Doc 3&quot;]<br>)<br><br>print(&quot;Master Vocabulary List:\n&quot;, list(vocabulary))<br>print(&quot;\nBag of Words Vector Matrix:&quot;)<br>print(df_bow)</pre><p><strong>b. TF-IDF (Term Frequency-Inverse Document Frequency):</strong></p><p>It builds directly on top of the Bag of Words architecture, but resolves its primary flaw. It mathematically penalizes words that appear frequently across an entire database while scaling up the weight of rare, highly specific terms.</p><pre>import pandas as pd<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br># 1. Define sample text database (Corpus)<br>corpus = [<br>    &quot;I love NLP and Machine Learning.&quot;,<br>    &quot;Machine Learning is amazing&quot;,<br>    &quot;I love learning new things.&quot;<br>]<br><br># 2. Initialize TfidfVectorizer<br>tfidf_vectorizer = TfidfVectorizer()<br><br># 3. Fit (Calculates TF and IDF weights) and Transform (Generates matrix)<br>tfidf_matrix = tfidf_vectorizer.fit_transform(corpus)<br>vocabulary = tfidf_vectorizer.get_feature_names_out()<br><br># 4. Display as a readable table (DataFrame)<br>df_tfidf = pd.DataFrame(<br>    tfidf_matrix.toarray(), <br>    columns=vocabulary, <br>    index=[&quot;Doc 1&quot;, &quot;Doc 2&quot;, &quot;Doc 3&quot;]<br>)<br><br>print(&quot;TF-IDF Vocabulary List:\n&quot;, list(vocabulary))<br>print(&quot;\nTF-IDF Weighted Matrix (Notice how rare words get higher values):&quot;)<br>print(df_tfidf.round(4))</pre><h3>Conclusion</h3><p>Natural Language Processing has evolved from basic word counting to deeply understanding human context. By cleaning raw text, converting it to numbers, and measuring mathematical similarity, we allow computers to interact with the world just like humans do.</p><h3><strong>Key Takeaways for Your Project</strong></h3><ol><li><strong>Clean Data First</strong>: Pre processing steps like lemmatization and noise removal make or break your model’s accuracy.</li><li><strong>Choose the Right Vectorizer</strong>: Use <strong>Bag of Words</strong> for simple counting tasks, but choose <strong>TF-IDF</strong> when word rarity and importance matter.</li><li><strong>Trust Cosine Similarity</strong>: When comparing text files or search queries, always use cosine similarity to prevent document length from messing up your results.</li></ol><h3>Connect &amp; Support! 🚀</h3><p>If you found this guide helpful, don’t forget to <strong>clap 👏</strong> for this article and <strong>follow</strong> me here on<a href="https://medium.com/@karanveernetsquaresoftwares"> <strong><em>Medium</em></strong> </a>for more weekly Python and AI tutorials.</p><p>Let’s connect, network, and talk data science! You can find me on <strong>LinkedIn</strong> here:<br>🔗 <a href="http://www.linkedin.com/in/karanveer-singh-926a0b287"><strong><em>Connect with me on LinkedIn</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dcdd3a66485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression and Logistic Regression in Machine Learning]]></title>
            <link>https://karanveersingh05.medium.com/linear-regression-and-logistic-regression-in-machine-learning-6ab64d35e489?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ab64d35e489</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 07:00:11 GMT</pubDate>
            <atom:updated>2026-07-31T07:00:11.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*ftuwulZtWc72JEc3vDbZYQ.png" /></figure><p>Regression searches for relationships among <strong>variables</strong>. For example, you can observe several employees of some company and try to understand how their salaries depend on their <strong>features</strong>, such as experience, education level, role, city of employment, and so on.</p><p>This is a regression problem where data related to each employee represents one <strong>observation</strong>. The presumption is that the experience, education, role, and city are the independent features, while the salary depends on them.</p><p>Similarly, you can try to establish the mathematical dependence of housing prices on area, number of bedrooms, distance to the city center, and so on.</p><p>Generally, in regression analysis, you consider some phenomenon of interest and have a number of observations. Each observation has two or more features. Following the assumption that at least one of the features depends on the others, you try to establish a relation among them.</p><p>In other words, you need to find a <strong>function that maps some features or variables to others</strong> sufficiently well.</p><h3><strong>Linear Regression</strong></h3><p>Linear Regression is a statistical approach that assumes a linear relationship between the input variables (independent variables) and the output variable (dependent variable). It predicts the value of the dependent variable based on the given set of independent variables. The goal is to find the best-fit line that minimizes the sum of squared errors between the predicted and actual values.</p><p>The equation of a simple linear regression model can be represented as:<strong> y = mx + c</strong></p><p>Where:</p><ul><li><strong>y</strong> — dependent variable (target variable)</li><li><strong>x — </strong>independent variable (input variable)</li><li><strong>m</strong> — slope of the line (coefficient)</li><li><strong>c</strong> — y-intercept (constant term)</li></ul><p><em>A regression line can be a Positive Linear Relationship or a Negative Linear Relationship.</em></p><h4><strong>Implementation of Linear Regression :</strong></h4><p>Step 1: Import the required libraries</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error, r2_score</pre><p>Step 2: Load and explore the dataset</p><pre># Load the dataset<br>data = pd.read_csv(&#39;dataset.csv&#39;) <br># Explore the dataset<br>print(data.head())</pre><pre># Explore the dataset<br>print(data.head())</pre><p>Step 3: Split the dataset into training and testing sets</p><pre># Split the dataset into features (X) and target variable (y)<br>X = data[[&#39;independent_variable&#39;]]<br>y = data[&#39;dependent_variable&#39;]</pre><pre># Split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>Step 4: Create and train the Linear Regression model</p><pre># Create a Linear Regression model<br>model = LinearRegression()</pre><pre># Train the model using the training sets<br>model.fit(X_train, y_train)</pre><p>Step 5: Make predictions and evaluate the model</p><pre># Make predictions on the testing set<br>y_pred = model.predict(X_test)<br># Evaluate the model<br>mse = mean_squared_error(y_test, y_pred)<br>r2 = r2_score(y_test, y_pred)<br>print(&#39;Mean Squared Error:&#39;, mse)<br>print(&#39;R-squared:&#39;, r2)</pre><h3>Logistic Regression</h3><p>It is a supervised machine learning algorithm used for classification problems. Unlike linear regression, which predicts continuous values , it predicts the probability that an input belongs to a specific class.It is used for binary classification where the output can be one of two possible categories such as Yes/No, True/False or 0/1. It uses sigmoid function to convert inputs into a probability value between 0 and 1.</p><p>Instead of fitting a straight line like linear regression, logistic regression uses the <strong>sigmoid (logistic) function</strong>, which converts any real-valued number into a value between 0 and 1.</p><p><strong>Linear Regression:</strong> Output = z</p><p><strong>Logistic Regression:</strong> Output = Sigmoid(z) = probability between 0 and 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*wLLfWAm_1rcEuOVOEg3ukg.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*UmNpZIOMuCEM7C_sQ1mbrw.png" /></figure><ul><li><strong><em>β0​ — </em></strong>the starting value when all input features are 0.</li><li><strong><em>β1,β2,…,βn</em>​ — </strong>Weights (coefficients) learned by the model during training.</li><li><strong><em>x1,x2,…,xn </em>—</strong> Input features<strong> </strong>(the values describing each data point).</li></ul><h4>Implementation of Linear Regression :</h4><p>Step 1: Import the required libraries</p><pre>import numpy as np<br>import pandas as pd<br><br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score classification_report</pre><p>Step 2 : <strong>No Change</strong> Same as that of Linear Regression</p><p>Step 3 : <strong>No Change</strong> Same as that of Linear Regression</p><p>Step 4 : Create and train the Logistic Regression model</p><pre># Create Logistic Regression model<br>model = LogisticRegression()</pre><pre># Train model<br>model.fit(X_train, y_train)</pre><p>Step 5 : Make predictions and evaluate the model</p><pre># Make predictions on the testing set<br>y_pred = model.predict(X_test) <br><br>accuracy = accuracy_score(y_test, y_pred)<br>print(&quot;Accuracy:&quot;, accuracy)<br><br>print(&quot;Classification Report:&quot;)<br>print(classification_report(y_test, y_pred))</pre><h3>Linear Regression vs Logistic Regression</h3><ol><li>Linear Regression is used for predicting<strong> continuous</strong> numerical values and uses a <strong>straight-line</strong> relationship between input and output</li><li>Logistic Regression is used for predicting <strong>categorical</strong> outputs, mostly binary classification and forms a <strong>S-shaped</strong> curve graph</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N8sbbSwund-No9KIW8Js2A.png" /></figure><h3>Confusion Matrix</h3><p>The confusion matrix is a tabular representation that summarises the performance of a classification model. It provides a detailed breakdown of the predicted and actual class labels. The confusion matrix for a binary classification problem consists of four cells:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*RoyIumMGmdHWs3Wj.png" /></figure><ul><li><strong>True Positive (TP)</strong>: The model correctly predicted the positive class.</li><li><strong>True Negative (TN)</strong>: The model correctly predicted the negative class.</li><li><strong>False Positive (FP)</strong>: The model incorrectly predicted the positive class when the actual class was negative (Type I error).</li><li><strong>False Negative (FN)</strong>: The model incorrectly predicted the negative class when the actual class was positive (Type II error).</li></ul><p>The confusion matrix helps evaluate the model’s performance by calculating various metrics:</p><ol><li><strong>Accuracy:</strong> The overall proportion of correct predictions, calculated as (TP + TN) / (TP + TN + FP + FN).</li><li><strong>Precision:</strong> The proportion of true positive predictions among all positive predictions, calculated as TP / (TP + FP).</li><li><strong>Recall</strong> (Sensitivity or True Positive Rate): The proportion of true positive predictions among all actual positive instances, calculated as TP / (TP + FN).</li><li><strong>Specificity</strong> (True Negative Rate): The proportion of true negative predictions among all actual negative instances, calculated as TN / (TN + FP).</li><li><strong>F1 Score</strong>: The harmonic mean of precision and recall, providing a balanced measure of model performance, calculated as 2 * (precision * recall) / (precision + recall).</li></ol><h3>Conclusion</h3><p>I hope this article helped you understand the Algorithm and Most of the concepts related to it.<br>Coming up next ,We will Understand the Another Concept of Python Programming.</p><p>Follow me on <a href="https://medium.com/@karanveernetsquaresoftwares"><strong><em>Medium</em></strong></a> So You can Explore more about Today’s World Evolving Technology. For future updates Follow me on <a href="http://www.linkedin.com/in/karanveer-singh-926a0b287"><strong><em>Linkedln</em></strong></a></p><p><strong>HAPPY LEARNING!!!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ab64d35e489" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supervised Machine Learning]]></title>
            <link>https://karanveersingh05.medium.com/supervised-machine-learning-92581e60c31b?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/92581e60c31b</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 06:01:04 GMT</pubDate>
            <atom:updated>2026-07-30T06:01:04.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7BmBlrgIrD13DGPFhS6GlA.png" /></figure><p>Supervised learning as its name suggests is like training with your teacher(supervisor) who provides answers while you are learning.</p><p>In supervised machine learning, the machine uses labeled data to find relationships and patterns between input and target variables. The machine uses its learning from given labeled data to make predictions about new unseen data.</p><p><strong>Note</strong>: input variables are also called independent variables or features and target variables are also called dependent variables.</p><h3>What is labeled data?</h3><p>Dataset with input-output pairs where each input is mapped with its correct output value. For example, in a classification task to classify pictures into cat or dog, labeled data would consist of example pictures with their correct label as a cat or a dog.</p><h3>Working of Supervised Machine Learning</h3><p>The working of supervised machine learning follows these key steps:</p><h4>1. Collect Labeled Data</h4><p>Gather a dataset where each input has a known correct output (label).</p><p><strong>Example</strong>: Images of handwritten digits with their actual numbers as labels.</p><h4>2. Split the Dataset</h4><p>Divide the data into training data (about 80%) and testing data (about 20%).</p><p>The model will learn from the training data and be evaluated on the testing data.</p><h4>3. Train the Model</h4><p>Feed the training data (inputs and their labels) to a suitable supervised learning algorithm (like Decision Trees, SVM or Linear Regression).</p><p>The model tries to find patterns that map inputs to correct outputs.</p><h4>4. Validate and Test the Model</h4><p>Evaluate the model using testing data it has never seen before.</p><p>The model predicts outputs and these predictions are compared with the actual labels to calculate accuracy or error.</p><h4>5. Deploy and Predict on New Data</h4><p>Once the model performs well, it can be used to predict outputs for completely new, unseen data.</p><h3>Terms needs to know To continue Further</h3><ol><li><strong>Features (Independent Variables / X)</strong>: The columns the model looks at to learn and make decisions. If you are predicting house prices, the features are columns like number_of_bedrooms, square_footage, and zip_code.</li><li><strong>Target (Dependent Variable / Label / y)</strong>: The specific column you want the model to predict. This is the “answer key” during training (e.g., price for a house, or is_spam for an email).</li><li><strong>Numerical Data (Continuous / Discrete):</strong> Columns containing numbers that you can do math with (e.g., Salary, Temperature, Item_Count). Machine learning models love numerical data.</li><li><strong>Categorical Data (Text / Groups):</strong> Columns containing text labels, categories, or distinct groups (e.g., Color, Gender, Country). Models cannot understand text directly, so these must be turned into numbers before training.</li></ol><h3>Types of Supervised Learning Algorithms</h3><p>Based on target variables type algorithms are divided into two types:</p><h4>1. Regression Problems</h4><p><strong>Objective:</strong> Predict continuous numerical values from input data</p><p><strong>Characteristics:</strong></p><ol><li>Output is numerical (infinite possible values within a range)</li><li>Answers questions like “How much?” or “What quantity?”</li><li>Results are continuous measurements</li></ol><p>Examples :</p><pre>House price prediction ($250,000, $180,500, etc.)<br>Stock price forecasting<br>Temperature prediction (23.5°C, 31.2°C, etc.)<br>Sales revenue estimation</pre><p>Syntax of Python code :</p><pre># 1. Import modules<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression  # Swap algorithm here<br>from sklearn.metrics import mean_squared_error, r2_score<br><br># 2. Prepare data<br>X = df[[&#39;feature1&#39;, &#39;feature2&#39;]]  # Independent variables (Matrix)<br>y = df[&#39;target_column&#39;]           # Dependent variable (Vector)<br><br># 3. Split data<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)<br><br># 4. Initialize model<br>model = LinearRegression()<br><br># 5. Train model<br>model.fit(X_train, y_train)<br><br># 6. Predict<br>predictions = model.predict(X_test)<br><br># 7. Evaluate<br>mse = mean_squared_error(y_test, predictions)<br>r2 = r2_score(y_test, predictions)<br><br># Print final mathematical scores<br>print(&quot;Average Error:&quot;, mse)<br>print(&quot;Accuracy Score:&quot;, r2)</pre><ol><li><strong>X</strong> : The independent input columns used to make predictions.</li><li><strong>y</strong> : The single dependent target column you want to predict.</li><li><strong>train_test_split</strong> : Breaks data into pieces.</li><li><strong>X_train/y_train</strong> (80%): Features and matching answers for the model to study.</li><li><strong>X_test/y_test (20%)</strong>: Hidden features and answers used later to grade the model.</li><li><strong>test_size=0.2</strong> : Explicitly allocates 20% of the data rows for the test phase.</li><li><strong>random_state=42</strong> : A seed value ensuring the data splits identically every run.</li><li><strong>fit() </strong>: The “training” phase. The model maps mathematical relationships between inputs and outputs.</li><li><strong>predict() </strong>: The “testing” phase. Model looks at unseen test features and outputs its guesses.</li><li><strong>r2_score </strong>: Goodness-of-fit metric. <strong>1.0</strong> is perfect accuracy</li></ol><h4>2. Classification</h4><p><strong>Objective:</strong> Predict discrete categories or classes from input data</p><p><strong>Characteristics:</strong></p><ol><li>Output is categorical (finite set of labels)</li><li>Answers questions like “Which category does this belong to?”</li><li>Results are mutually exclusive classes</li></ol><p>Examples:</p><pre>Email spam detection (Spam vs. Not Spam)<br>Medical diagnosis (Disease A, B, or C)<br>Image recognition (Cat, Dog, Bird)<br>Customer segmentation (High, Medium, Low value)</pre><p>Syntax of Python Code :</p><pre># 1. Import tools (The building blocks)<br>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier  # Classification algorithm<br>from sklearn.metrics import accuracy_score          # Evaluation tool<br><br># 2. Load the data<br>df = pd.read_csv(&#39;your_data.csv&#39;)<br><br># 3. Separate Features (X) and the Category Target (y)<br># Replace &#39;category_column&#39; with the name of the column you want to predict<br>X = df.drop(columns=[&#39;category_column&#39;]) <br>y = df[&#39;category_column&#39;]<br><br># 4. Split data into Training (80%) and Testing (20%)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># 5. Initialize the Classifier model<br>model = RandomForestClassifier()<br><br># 6. Train the model (Let it learn the categories)<br>model.fit(X_train, y_train)<br><br># 7. Predict categories for the unseen test data<br>predictions = model.predict(X_test)<br><br># 8. Print out the performance in simple terms<br>print(&quot;Correct Guesses Percentage:&quot;, accuracy_score(y_test, predictions))</pre><p>To switch your code from Regression to Classification, you only need to change these 2 precise parts else terms remain same :</p><ol><li><strong>The Model Type</strong>: Change Regressor to Classifier when you import and initialize the model (e.g., change <strong>RandomForestRegressor</strong> to <strong>RandomForestClassifier</strong>).</li><li>The Score Metric: Change your final evaluation function from checking number errors (like <strong>r2_score or mean_squared_error</strong>) to checking a category percentage (like <strong>accuracy_score</strong>)</li></ol><h3>Conclusion</h3><p>Supervised machine learning in Python relies on a consistent four-step workflow — import, instantiate, fit, and predict — using Scikit-Learn to streamline both regression and classification tasks.</p><p>To receive further tutorials ,knowledge form basic to advance please follow on<strong> </strong><a href="https://medium.com/@karanveernetsquaresoftwares"><strong><em>Medium</em></strong></a><strong> </strong>and for latest news stay connected on<em> </em><a href="http://www.linkedin.com/in/karanveer-singh-926a0b287"><strong><em>Linkedln</em></strong></a></p><blockquote><strong>Happy Coding</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92581e60c31b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to Machine Learning]]></title>
            <link>https://karanveersingh05.medium.com/beginners-guide-to-machine-learning-7139ad9ade37?source=rss-6c36802ab9b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7139ad9ade37</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Karanveer Singh]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 06:52:38 GMT</pubDate>
            <atom:updated>2026-07-29T06:52:38.433Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*ei-OvV1R2BuQLBX2PTz1Sg.png" /></figure><p>Machine learning is the subset of artificial intelligence (AI) focused on algorithms that can “learn” the patterns of training data and make accurate <em>inferences</em> about new data. This pattern recognition ability enables machine learning models to make decisions or predictions without explicit, hard-coded instructions.</p><h3>Why Machine Learning ?</h3><ol><li><strong>Handling Complexity:</strong> Traditional computer programs need rigid rules written by humans, which fail for tasks like recognizing a face or translating speech. Machine learning figures out these rules by learning from examples.</li><li><strong>Automation at Scale:</strong> It takes over repetitive, time-consuming work, reducing human error and boosting speed in daily operations.</li><li><strong>Smart Personalization:</strong> Systems look at individual habits to customize choices, such as media streaming services suggesting movies or shops recommending products.</li><li><strong>Accurate Predictions:</strong> By studying past trends, models forecast future outcomes like customer demand, financial fraud, or equipment failures.</li></ol><h3>Types of Machine Learning</h3><ol><li>Supervised Machine Learning</li><li>Unsupervised Machine Learning</li><li>Reinforcement Learning</li><li>Semi-Supervised Learning</li></ol><h4>1. Supervised Machine Learning</h4><p>Supervised learning is defined as when a model gets trained on a “Labeled Dataset”. Labelled datasets have both input and output parameters. In Supervised Learning algorithms learn to map points between inputs and correct outputs. It has both training and validation datasets labelled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*amJX-w5DBSz8QJV0RwP0nw.png" /></figure><h4>2. Unsupervised Machine Learning</h4><p>Unsupervised Learning works with “Unlabeled data”, meaning there are no predefined outputs. The algorithm finds hidden patterns, groups or relationships within the data on its own. It’s mainly used for clustering, dimensionality reduction and data visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*61KKewVKZaAWLIj82pPMfA.png" /></figure><h4>3. Reinforcement Learning</h4><p>Reinforcement learning trains an agent to make a sequence of decisions through trial and error. The agent interacts with the environment, receives feedback in the form of rewards or penalties and learns optimal actions over time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*2dFNl_IHuuj-QJLQpQVutg.png" /></figure><h4>4. Semi-Supervised Learning</h4><p>Semi-Supervised learning Semi-Supervised Learning combines both Supervised and Unsupervised approaches. It uses a small set of “labeled data” and a large set of “Unlabeled data” for training useful when labeling is costly or time-consuming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*SIh5UqRuuwboYESRH4hP8g.png" /></figure><h3>Comparison of Machine Learning Types</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*0PPtRXVESomVFioTTNiDSw.png" /></figure><h3>Applications of Machine Learning</h3><ol><li>Recommendation engines</li><li>Malware threat detection</li><li>Predictive maintenance</li><li>Virtual personal assistant</li><li>Medical diagnosis</li><li>Stock market trading</li><li>Speech and image recognition</li><li>Self-driving cars</li></ol><h3>Conclusion</h3><p>The ultimate goal of Machine Learning is not just to create a model also to solve real-world problems intelligently, efficiently, and at scale. This article will keep getting updates for you to learn.</p><p>Thanks for reading.</p><p>Let’s connect through <a href="http://www.linkedin.com/in/karanveer-singh-926a0b287"><strong><em>LinkedIn</em></strong></a> for further updates follow me on <a href="https://medium.com/@karanveernetsquaresoftwares"><strong><em>Medium</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7139ad9ade37" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>