<?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 Sandeep Singh Shekhawat on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Singh Shekhawat on Medium]]></description>
        <link>https://medium.com/@sandeep.shekhawat?source=rss-28219f1dabc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wv_at2Gqmh2Ky9HcSPB07w@2x.jpeg</url>
            <title>Stories by Sandeep Singh Shekhawat on Medium</title>
            <link>https://medium.com/@sandeep.shekhawat?source=rss-28219f1dabc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 21:32:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandeep.shekhawat/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[Linear Regression Algorithm in Machine Learning with Python]]></title>
            <link>https://medium.com/@sandeep.shekhawat/linear-regression-algorithm-in-machine-learning-with-python-21b5b0e130dc?source=rss-28219f1dabc------2</link>
            <guid isPermaLink="false">https://medium.com/p/21b5b0e130dc</guid>
            <category><![CDATA[linear-regression-python]]></category>
            <category><![CDATA[linear-regression-example]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sandeep Singh Shekhawat]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 13:10:24 GMT</pubDate>
            <atom:updated>2023-10-16T13:10:24.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l1GbI-HFhjXGiWV7" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Linear regression is a supervised machine learning algorithm. It tries to find a linear relationship between two variables, where one is dependent and the other is independent. The dependent variable value is calculated based on a linear equation that uses a coefficient, an independent variable, and an intercept. The two variables may or may not have a relationship. The linear regression algorithm predicts an outcome based on the values of the independent variable.</p><h3>Linear Regression</h3><p>Linear regression is a statistical method that uses a linear equation to show the relationship between two variables. One variable is dependent, meaning that its value is determined by the other variable, which is independent. For example, the weight of a person is linearly related to their height. This means that there is a direct relationship between the two variables, such that as one variable increases, the other variable also increases.</p><p>Sometimes, one variable does not depend on another variable, but they can still have a critical relationship. In these cases, we can use a scatter plot to visualize the relationship between the variables. If the scatter plot does not show any increasing or decreasing pattern, then linear regression is not the right option.</p><h3>Linear Regression Equation</h3><p>The formula for the linear regression equation is as follows:</p><pre> <br>y = a + bx</pre><p>where:</p><ul><li>y is the predicted or dependent variable, plotted on the y-axis.</li><li>x is the explanatory or independent variable, plotted on the x-axis.</li><li>b is the slope of the regression line or regression coefficient, with a value between -1 and 1.</li><li>a is the constant, equal to y when x = 0. It is also known as the intercept.</li></ul><p>The regression line is drawn on a scatter plot based on the Mean of the x and y variable values. Linear regression determines a straight line.</p><h3>Linear Regression Algorithm with Python code</h3><p>Python has a variety of modules and libraries that already have built-in functions for machine learning. In this Python code program, the goal is to predict a person’s weight based on their height. This is done by multiplying the height by the regression coefficient and adding the intercept. The height is the input feature, which means it is the independent variable. The weight is the explanatory variable.</p><h4>Import required Python Libraries:</h4><p>To perform calculations, predict, and draw scatter plots, we need to import some Python libraries. The following code snippet shows how to import these libraries:</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plot<br>from sklearn import linear_model<br>from sklearn.metrics import r2_score</pre><p>These libraries can be installed using the following shell commands. We ran these commands one by one.</p><pre>pip install scikit-learn<br>pip install matplotlib</pre><p>The following is a brief explanation of the libraries used in this program.</p><ul><li><strong>NumPy:</strong> A library for numerical calculation and statistical operations. It is used for computation and processing of n-dimensional arrays and metrics.</li><li><strong>Matplotlib:</strong> Matplotlib is a Python library used for data visualization. It provides scatter plotting, which is a type of graph that can be used to show trends in data.</li><li><strong>Scikit-learn:</strong> Scikit-learn is a machine learning library that provides regression, classification, and clustering algorithms. It is built on top of NumPy and SciPy.</li></ul><h4>Read Data from Source:</h4><p>First and foremost, we need data to train and test a model. Therefore, we need to read the data from a source. The Pandas library can be used to load data from different file sources. In the following code snippet, we are loading data from a CSV file that contains data for height and weight. The CSV file has two columns.</p><pre>dataset = pd.read_csv(&quot;heighWight.csv&quot;)<br>dataset.head()</pre><p>The following is data format in data source (CSV) file. The CSV file has two columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*1TUDiRNOrLnvMi0dMZ2vQw.png" /><figcaption>Figure 1: Data format in CSV file</figcaption></figure><h4>Selecting Features to Predict a Value:</h4><p>The algorithm predicts an outcome based on input features. In this case, we are selecting “Height” as an input feature and “Weight” as the outcome. Since this is a simple linear regression, the input feature has only one column.</p><pre>dataset = dataset[[&quot;Height&quot;,&quot;Weight&quot;]]</pre><h4>Visualizing Data:</h4><p>The linear regression algorithm uses a scatter plot to show the relationship between two variables. The input features should be plotted on the x-axis, while the predicted values should be plotted on the y-axis. The matplotlib.pyplot library can be used to plot the data. The following code snippet shows how to draw a scatter plot:</p><pre>plot.scatter(dataset[&quot;Height&quot;],dataset[&quot;Weight&quot;], color = &quot;orange&quot;)<br>plot.xlabel(&quot;Height&quot;)<br>plot.ylabel(&quot;Weight&quot;)<br>plot.show()</pre><p>Run the application. It will show the following scatter plot for the data in the CSV file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*djTLo08YVTCoRAz0IFUWlg.png" /><figcaption>Figure 2: Scatter plot for Height vs Weight CSV data</figcaption></figure><h4>Dividing Data for Training and Testing:</h4><p>In order to train a machine learning model to predict an outcome, we need training data. Once the model is trained, we need to test its accuracy, so we need some testing data. As we have a large dataset, we divide it into two datasets: a training dataset and a testing dataset.</p><p>We use ~80% of the data for training the model and the remaining ~20% for testing the trained model. This is because we need a lot of data for training the model to be accurate.</p><pre>trainData = dataset[:(int((len(dataset)*0.8)))]<br>testData = dataset[(int((len(dataset)*0.8))):]</pre><h4>Training of Model:</h4><p>We train our model using a training dataset and a linear regression algorithm. We use the scikit-learn library, which has an inbuilt method for training models. We also calculate the coefficient and intercept, which will be used to determine the best-fitting regression line.</p><pre>regr = linear_model.LinearRegression()<br>trainIndepdentData = np.array(trainData[[&quot;Height&quot;]])<br>trainDepedentData = np.array(trainData[[&quot;Weight&quot;]])<br>regr.fit(trainIndepdentData,trainDepedentData)<br> <br>print(&quot;regression coefficients: &quot;, regr.coef_)<br>print(&quot;intercepts of y: &quot;, regr.intercept_)</pre><p>Run the application. It will show the following output for coefficient and intercept.</p><blockquote>regression coefficients: [[0.94473105]]<br>intercepts of y: [-93.41215107]</blockquote><h4>Plot the least-squares regression line (LSRL):</h4><p>Linear regression determines a straight line called the least-squares regression line (LSRL). We can draw the best-fitting regression line using the following code snippet, as we have the coefficients and intercepts. The LSRL passes through the mean value of the explanatory (Y) and independent (X) variables.</p><pre>plot.scatter(trainData[&quot;Height&quot;],trainData[&quot;Weight&quot;], color=&quot;orange&quot;)<br>plot.plot(trainIndepdentData,regr.coef_*trainIndepdentData+regr.intercept_,&#39;-r&#39;)<br>plot.xlabel(&quot;Height&quot;)<br>plot.ylabel(&quot;Weight&quot;)<br>plot.show()</pre><p>This code snippet creates a scatter plot of the data and then fits a regression line to the data. The regression line is then plotted on top of the scatter plot. The code also labels the axes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*lIIwDC372PesNPSjGMEv4A.png" /><figcaption>Figure 3: Regression Line on Plotting data based on coefficient.</figcaption></figure><h3>Predication Function:</h3><p>We wrote a predication function based on a linear equation. The function returns a predicate value based on the input feature value, coefficient, and intercept. The following code snippet shows the function:</p><pre>def get_regression_predictions(input_features, intercept, coefficient):<br>    predicated_values = intercept + coefficient*input_features<br>    # Maths form is y = a + bx; <br>    return predicated_values</pre><p>This function can be used to predict the value of a target variable based on the values of one or more input variables. For example, we could use this function to predict the price of a house based on the square footage of the house, the number of bedrooms, and the number of bathrooms.</p><h3>Predicating Weight Value:</h3><p>We can predict the value of “Weight” for an input value of “Height” based on a regression line. The following code snippet demonstrates this.</p><pre>input_feature_height = 210<br>estimated_weight = get_regression_predictions(input_feature_height,regr.intercept_[0],regr.coef_[0][0])<br>print(&quot;Estimated weight &quot;, estimated_weight)</pre><p>Run the application. It will show the following output for predicated weight.</p><blockquote>Estimated weight 104.98136870822182</blockquote><h3>Accuracy of Model using Testing data:</h3><p>We have trained a machine learning model, so now we can verify its accuracy using testing data. We have actual values in our test data, and the machine learning model will give us predicted values based on a regression line. We will compare the actual and predicted values to determine the model’s accuracy. The following code snippet shows how to do this.</p><pre>test_x = np.array(testData[[&#39;Height&#39;]])<br>test_y = np.array(testData[[&#39;Weight&#39;]])<br>test_y_ = regr.predict(test_x)<br> <br>print(&quot;Mean absolute error: %.2f&quot; % np.mean(np.absolute(test_y_ - test_y)))<br>print(&quot;Mean sum of squares (MSE): %.2f&quot; % np.mean((test_y_ - test_y) ** 2))<br>print(&quot;R2-score: %.2f&quot; % r2_score(test_y_, test_y))</pre><p>Run the application. It will show the following output</p><blockquote>Mean absolute error: 1.37<br>Mean sum of squares (MSE): 2.06<br>R2-score: 0.90</blockquote><p>In machine learning, R-squared is often used to evaluate the performance of regression models. A higher R-squared value indicates that the model is better able to predict the values of the dependent variable. However, it is important to note that R-squared is not a perfect measure of model performance. It can be inflated by the presence of irrelevant features or by overfitting the data. The value of R-squared lies between 0 and 1.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21b5b0e130dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Machine Learning (ML)]]></title>
            <link>https://medium.com/@sandeep.shekhawat/an-introduction-to-machine-learning-ml-199ec3577f8e?source=rss-28219f1dabc------2</link>
            <guid isPermaLink="false">https://medium.com/p/199ec3577f8e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sandeep Singh Shekhawat]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 13:04:56 GMT</pubDate>
            <atom:updated>2023-10-16T13:04:56.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SoqdTCFHFLR0D5tr" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Machine Learning (ML) enables a machine to learn self from trained data without being explicit programmed. It improves over the time when trained data (labelled data) increases. A traditional program is set of instruction in which explicitly defined that what action needs to be taken based on input while machine learning algorithm detects pattern in data and learn from data using that pattern. Hence, it learns from experience. Once pattern identifies in data then it creates a set of rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*fxccjHd8VT7hM8S5DA5RRw.png" /><figcaption>Figure 1: Introduction to Machine Learning</figcaption></figure><h3>Types of Machine Learning</h3><p>There are 4 types of machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*0jDL9Jy_67tF_q7Uyy5yQw.png" /><figcaption>Figure 2: Types of Machine Learning</figcaption></figure><p><strong>Supervised Learning:</strong> It is provided input data with label or tag with expected output. It also defines rules to categories input data.</p><p><strong>How it works:</strong></p><p><strong>Step 1- Train the model:</strong> We pass labeled data with desired output. We pass some apples images as an input along with desired output which is “These are green apples”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*D78yyzdrbod8maVNVjhmag.png" /><figcaption>Figure 3: Train Supervise Learning Model</figcaption></figure><p><strong>Step 2- Test the model:</strong> We pass an image to model again without desired output. The output of model is “These are green apples”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*pFJ4fFJKj6jjXGnbek2ZjA.png" /><figcaption>Figure 4: Test of Supervise Learning Model</figcaption></figure><p><strong>Unsupervised Learning:</strong> It learns from unlabeled data. It uses unlabeled data as input and train the model. It detects a pattern based on input data. It uses only input data.</p><p><strong>How it works:</strong></p><p><strong>Step 1- Input Unlabeled Data:</strong> We provide different kinds of fruits images without label or tag. Also, we don’t provide desired output along with input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*iQEd8WEpx74yHoEv1FZBTA.png" /><figcaption>Figure 5: Input unlabeled data</figcaption></figure><p><strong>Step 2- Test Model:</strong> As we have input unlabeled data so learning model detects a pattern based on color, size , quantity etc. Once the pattern identifies it groups fruits based on features and properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*Ub_kHRMyklwzjlX3qGuIaA.png" /><figcaption>Figure 6: Unsupervised Learning model testing</figcaption></figure><p><strong>Semi-supervised Learning:</strong> It used both labelled and unlabeled data, so it lies between the supervised learning and unsupervised learning. It doesn’t have restrictions about data, so it has large numbers of data. Hence, its main purpose is to effectively use all available data.</p><p><strong>Reinforcement Learning: </strong>It’s based on taking appropriate action and maximize reward. Once it takes any action or decision in particular situation then it receives feedback on that decision. It helps to determine whether the decision it made was right, wrong, or neutral. It’s self-learning system which initially learn by trials and errors. Basically, it has an agent that learns to behave in environment by performing action and seeing feedback on that action and a reward system. When agent gets positive feedback on each good action while gets negative feedback on each bad action. Hence, it’s a feedback-based learning system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199ec3577f8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Artificial Intelligence (AI)]]></title>
            <link>https://medium.com/@sandeep.shekhawat/introduction-to-artificial-intelligence-ai-785597a20623?source=rss-28219f1dabc------2</link>
            <guid isPermaLink="false">https://medium.com/p/785597a20623</guid>
            <category><![CDATA[artificalintelligence]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sandeep Singh Shekhawat]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 12:59:03 GMT</pubDate>
            <atom:updated>2023-10-16T12:59:03.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZF8S6WwnztZrg1Mh" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p><strong>Artificial Intelligence (AI):</strong>Artificial Intelligence is a set of technologies that enable a machine to perform tasks like an intelligent being. It refers to the capability of any machine to simulate human intelligence. AI includes Machine Learning and Deep Learning technologies.</p><p><strong>Machine Learning (ML):</strong> Machine Learning focuses on the development of algorithms and statistical models. These models enable machines to learn from data and make decisions or predictions without explicit rules by human. These data could be labeled data.</p><p><strong>Deep Learning (DL):</strong> Deep Learning uses complex structure of algorithms. It is inspired by the structure and function of the human brain. It enables the processing of unstructured data such as images and text.</p><h3>Types of Artificial Intelligence (AI)</h3><p>Artificial Intelligence has 7 types. All types are under two categories which are based on capabilities and based on functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*uYAt1u42dkPvaHdAxHXDWw.png" /><figcaption>Figure 1: Types of Artificial Intelligence</figcaption></figure><h4>AI BASED ON CAPABILITIES</h4><p><strong>Weak AI:</strong> It’s also called Narrow AI. It can perform narrow tasks with intelligence. It targets a single subset of cognitive abilities. Hence, it has been trained for a specific task only. Apple Siri is an example of Weak AI.</p><p><strong>Strong AI:</strong> It’s also called General AI. It could perform intellectual tasks like a human. It allows the system to think like humans and apply knowledge in different contexts. It’s under research so far.</p><p><strong>Super AI:</strong> It surpasses human intelligence. It can perform any tasks better than human. It evolves similar human sentiments and experience. Its existence is hypothetical.</p><p><strong>AI BASED ON FUNCTIONALITIES</strong></p><p><strong>Reactive Machine:</strong> It works with specific tasks only and doesn’t have capabilities beyond the task. It works with present data. It doesn’t store in memories and experience to utilize in future.</p><p><strong>Limited Memory:</strong> It trains with past data. It stores data for a short time duration in memory. It uses past data to make decisions. Self-driving cars are an example of it.</p><p><strong>Theory of Mind:</strong> It should understand human behaviors, belief , emotions and thoughts. It is just a concept.</p><p><strong>Self-Awareness:</strong> It has its own emotions and sentiments. It is smarter than the human brain. It is a hypothetical concept.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785597a20623" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate ChatGPT API in Python]]></title>
            <link>https://medium.com/@sandeep.shekhawat/integrate-chatgpt-api-in-python-348037adcadc?source=rss-28219f1dabc------2</link>
            <guid isPermaLink="false">https://medium.com/p/348037adcadc</guid>
            <category><![CDATA[artificalintelligence]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sandeep Singh Shekhawat]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 12:55:57 GMT</pubDate>
            <atom:updated>2023-10-16T12:55:57.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qYjQ48-CW4Dr9dX9" /><figcaption>Photo by <a href="https://unsplash.com/@jupp?utm_source=medium&amp;utm_medium=referral">Jonathan Kemper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>ChatGPT is a generative artificial intelligence (AI) tool. ChatGPT stands for Chat Generative Pre-trained Transformer. It was developed by OpenAI. It is based on a reinforcement machine learning algorithm. It uses natural language processing to create human-like conversations.</p><h3>Steps to Integrate ChatGPT in Python Code</h3><p>These are the following steps to integrate the ChatGPT or OpenAI api in Python application.</p><h4>Create a ChatGPT Account</h4><p>If you do not have a ChatGPT account, you must create a ChatGPT or OpenAI account on the OpenAI platform. You can do this by following the link https://platform.openai.com/ . After entering a valid email address and password, you may receive an error message that says “Signup is currently unavailable, please try again later.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*dwOKtv88cjJps78A6wfX8A.png" /><figcaption>Figure 1: Create Open AI Account</figcaption></figure><p>ChatGPT is currently not accepting new signups. What should you do next? Don’t worry! There are other options that you can try. Just choose any of the three options shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*eBGZ9CxJoa5XxLlLTKpS-g.png" /><figcaption>Figure 2: Sign up for Open AI via Google Account</figcaption></figure><p>We will use the Google option for sign-up, so please use a valid Gmail account. Sometimes, the OTP (One-Time Password) does not come on your mobile number, so It will send you an OTP on WhatsApp. Please keep WhatsApp installed on your device. This is a prerequisite for integrating Open AI.</p><p>Now, you can access chat GPT as shown below image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*k3gMbkjf87qDOtClQHhNSg.jpeg" /><figcaption>Figure 3: ChatGPT prompt in iOS App</figcaption></figure><h3>Generate Secret API Key</h3><p>After successfully logging in, click on the <strong><em>Personal</em></strong> tab in the top right corner of the page. Then, click on <strong><em>View API Keys</em></strong>. Next, click on <strong><em>Create new secret key</em></strong>. This will open a pop-up window where you can enter a key name. See the following image for an example. The secret key that is generated will be used to connect with OpenAI from code. You should copy this key because you will not be able to view it again. If you lose the secret key, you will need to regenerate it using the same steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnsBsSY3p0pmdq5X3LmnaA.png" /><figcaption>Figure 4: Generate Open AI Secret key</figcaption></figure><h3>Set up Open AI</h3><p>To install the <strong>OpenAI</strong> library for Python, open the terminal in the VS Code editor and run the following command.</p><pre> <br>pip install openai</pre><p>In this program, we will integrate the chat completion API.</p><h3>Import Open AI</h3><p>Now, we import the OpenAI library in the Python code file and configure it. The following code snippet shows how to import the OpenAI library. Then, the OpenAI secret key is assigned to a variable.</p><pre>import openai<br>openai.api_key = &#39;sk-xxxxx&#39;</pre><p>We now define a context for the API in advance so that the model can adapt to requests accordingly. The following JSON code has an array variable named messages. It is an array of message objects so that we can send a set of messages instead of a single message string as a prompt. Each message object has two properties: role and content.</p><h3>Set the context for ChatGPT API</h3><p>We now define a context for the API in advance so that the model can adapt to requests accordingly. The following JSON code has an array variable named <strong><em>messages</em></strong>. It is an array of <strong><em>message</em></strong> objects so that we can send a set of messages instead of a single message string as a prompt. Each <strong><em>message</em></strong> object has two properties: <strong><em>role</em></strong> and <strong><em>content</em></strong>.</p><pre>messages = [<br>                {<br>                    &quot;role&quot;:&quot;system&quot;,<br>                    &quot;content&quot; : &quot;It&#39;s ChatGPT assistant&quot;<br>                }<br>            ]</pre><p>The message object can accept three types of role values:</p><ul><li><strong>System:</strong> This is also known as a system message. It is included at the beginning of the array. Its main objective is to provide initial instructions to the model, thereby setting up the context and behavior of the assistant.</li><li><strong>User: </strong>This is used to accept the instructions of the end user for the ChatGPT API.</li><li><strong>Assistant: </strong>This is used to store the response from the model and keep the conversation going.</li></ul><h3>Accept User Instruction</h3><p>We write code to accept user input as an instruction. This code works as a chat prompt and is defined under a while loop block so that the chat can continue indefinitely. The message variable stores user input.</p><p>Next, we check if the <strong><em>message</em></strong> variable contains input. If it does contain an instruction, we append it to the <strong><em>messages</em></strong> array. Since this is user input, the <strong><em>message</em></strong> object’s role value will be “user”.</p><pre>while True:<br>    message = input(&quot;User: &quot;)<br>    if message:<br>        messages.append(<br>            {<br>            &quot;role&quot;:&quot;user&quot;,<br>            &quot;content&quot;: message<br>            }<br>        )</pre><h3>Generate Chat</h3><p>The code is calling the <strong><em>openai.ChatCompletion.create()</em></strong> function. This function is used to generate a completion for a chat conversation. The function takes two arguments:</p><ul><li><strong>model:</strong> The name of the model to use. In this case, the model is gpt-3.5-turbo.</li><li><strong>messages:</strong> An array of messages that represent the conversation so far. In this case, the messages variable has user and system instructions.</li></ul><p>The <strong><em>openai.ChatCompletion.create()</em></strong> function returns a <strong><em>ChatCompletion</em></strong> object.</p><pre>chat = openai.ChatCompletion.create(<br>            model = &quot;gpt-3.5-turbo&quot;,<br>            messages = messages<br>        )</pre><h3>Show Conversation</h3><p>We store the response content from the <strong><em>ChatCompletion</em></strong> object to the <strong><em>reply</em></strong> variable. We then show the reply on the console. Finally, we append the reply to the <strong><em>messages</em></strong> array so that it can be shown in indefinite conversations.</p><pre>reply = chat.choices[0].message.content<br>        print(f&quot;ChatGPT : {reply}&quot;)<br>        messages.append({&quot;role&quot;:&quot;assistant&quot;,<br>        &quot;conent&quot;:reply})</pre><h3>Run the Application</h3><p>We run the application and it asks for user input. We ask the question,<strong><em> “What is the difference between ChatGPT and Bard AI in tabular form?” </em></strong>.The application shows the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*OmSFdJ4AB20EqW-tP31vjg.png" /><figcaption>Figure 5: Response from ChatGPT API</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=348037adcadc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[var and let in ECMAScript 6]]></title>
            <link>https://medium.com/@sandeep.shekhawat/var-and-let-in-ecmascript-6-936ca11ad78?source=rss-28219f1dabc------2</link>
            <guid isPermaLink="false">https://medium.com/p/936ca11ad78</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ecmascript]]></category>
            <category><![CDATA[ecmascript-6]]></category>
            <dc:creator><![CDATA[Sandeep Singh Shekhawat]]></dc:creator>
            <pubDate>Sat, 12 Oct 2019 07:02:06 GMT</pubDate>
            <atom:updated>2019-10-12T07:02:06.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYhu77NcI-0LtdJaKk2o4Q.jpeg" /><figcaption>Photo by Christopher Robin Ebbinghaus on Unsplash</figcaption></figure><p>The var and let have a main difference in scope. The var variable has scope at function level while let variable has scope at block level.</p><h4>Access before declaration</h4><p>The var variable adds to window object so it can be accessed everywhere in function/program while let variable has scope as block level. A code snippet which accesses var and let variables before their declaration such as following snippet.</p><pre>console.log(x);<br>var x=&#39;JavaScript&#39;;</pre><pre>console.log(y);<br>let y=&#39;ECMA6&#39;;</pre><p>Here, it prints ‘undefined’ for x variable which declared with var keyword in first line. While in third line y variable which declared with let keyword, throws an error ‘ReferenceError: y is not defined’. When a variable declares with var keyword then it adds in window object and has scope globally.</p><h4>Redeclaration of variable</h4><p>The var variable can be redeclared in the same code block and can be reassigned in entire code snippet.</p><pre>var x=&#39;JavaScript&#39;;<br>var x=&#39;ECMA6&#39;;<br>console.log(x);</pre><p>It prints ECMA6 as output for x variable. It has been redeclared and reassigns in same code block. While let variable can’t be redeclared in same code block. However, let variable can be reassigned in same block or child block.</p><pre>let y=&#39;Angular&#39;;<br>let y=&#39;React&#39;;<br>console.log(y);</pre><p>It throws an error ‘SyntaxError: Identifier ‘y’ has already been declared’.</p><pre>let country =&quot;USA&quot;;</pre><pre>function getCountryName()<br>{<br>  let country=&quot;India&quot;;<br>  return country;<br>}</pre><pre>console.log(getCountryName());<br>console.log(country);</pre><p>It prints India and USA respectively. If variable country doesn’t redeclare in function code block and assign only then both print India. It has similar behavior for both var and let.</p><h4>Scope of variable</h4><p>The var variable has scope at function level while let variable has scope at block level. The below code snippet has a var variable named name inside function and called outside.</p><pre>function getName()<br>{<br>   var name=&quot;john&quot;;<br>}</pre><pre>getName();<br>console.log(name);</pre><p>It throws an error ‘ReferenceError: name is not defined’ because variable which declared with var has scope at function level. Let’s see another example for the block level.</p><pre>for(var x=1;x&lt;=10;x++)<br>{<br>  //do something<br>}<br>console.log(x);</pre><p>It prints 11 for variable x value. It has scope outside the block but inside function. Let’s see an example for the let.</p><pre>for(let y=1;y&lt;=10;y++)<br>{<br>   //do something<br>}<br>console.log(y);</pre><p>It throws an error ‘ReferenceError: y is not defined’ because variable declared with let keyword has scope at block level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=936ca11ad78" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>