<?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 Abbas Mohammed on Medium]]></title>
        <description><![CDATA[Stories by Abbas Mohammed on Medium]]></description>
        <link>https://medium.com/@abbas7mohammed?source=rss-4c1bfa196a5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5Zw1OqwqWgyN1W251cmgoQ.jpeg</url>
            <title>Stories by Abbas Mohammed on Medium</title>
            <link>https://medium.com/@abbas7mohammed?source=rss-4c1bfa196a5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:00:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abbas7mohammed/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[Setting up a MicroPython environment with the ESP8266 and flash the first script]]></title>
            <link>https://medium.com/@abbas7mohammed/setting-up-a-micropython-environment-with-the-esp8266-and-executing-the-first-script-264594aacc11?source=rss-4c1bfa196a5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/264594aacc11</guid>
            <category><![CDATA[micropython]]></category>
            <category><![CDATA[esp9266]]></category>
            <category><![CDATA[esptool]]></category>
            <category><![CDATA[esp]]></category>
            <category><![CDATA[arduino-lab-micropython]]></category>
            <dc:creator><![CDATA[Abbas Mohammed]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 21:05:19 GMT</pubDate>
            <atom:updated>2026-08-08T18:21:00.431Z</atom:updated>
            <content:encoded><![CDATA[<p>Before developing applications with MicroPython, it is necessary to prepare the programming environment by installing the required software and configuring the target microcontroller. A properly configured environment allows developers to write, upload, execute, and debug MicroPython programs efficiently. Once the setup is complete, the first script serves as a simple verification that the ESP8266, firmware, and development tools are functioning correctly, providing a solid foundation for more advanced projects.</p><h4>Hardware requirements</h4><ul><li>Laptop</li><li>NodeMCU ESP8266</li><li>USB cable</li></ul><h4>Software requirements</h4><ul><li>Python</li><li>esptool.py</li><li>Firmware</li><li>Arduino Lab for MicroPython</li></ul><h3>1- Install Python</h3><p>From the official Python website <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>, download the Python executable file and install it on your computer. Don’t forget to add it to the path in the environment variables.</p><h3>2- Install esptool</h3><ul><li>Open CMD or any terminal you use and type the following:</li></ul><pre>python -m pip install esptool</pre><p>Wait until it’s finished. You should end up seeing something similar to:</p><p><em>Successfully installed esptool …</em></p><ul><li>Then make sure it worked:</li></ul><pre>python -m esptool version</pre><p>If the esptool version number appears, it’s OK.</p><p>You can get a port number of connection by using:</p><pre>python -m serial.tools.list_ports</pre><p>The next step will be to erase the flash file before installing MicroPython. Close IDEs and any serial monitor, then execute:</p><pre>python -m esptool --port COM6 erase-flash</pre><p><em>Note: change COM6 to your port number.</em></p><p>You should see something similar to:</p><p><em>Connecting…</em></p><p><em>Chip is ESP8266…</em></p><p><em>Erasing flash…</em></p><p><em>Chip erase completed successfully</em></p><p>If Connecting appears … and it keeps waiting, press the FLASH button on the ESP while connecting, and if you have an RST button, press it quickly while pressing FLASH.</p><p>You should look at something similar to:</p><p><em>Flash memory erased successfully in 7.4 seconds.</em></p><h3>3- Download and install Firmware</h3><p>The firmware is a special version of the MicroPython operating system that is installed within the development board’s memory. It is responsible for running the Python interpreter and managing the microcontroller’s resources.</p><p>Go to the official website <a href="https://micropython.org/download/ESP8266_GENERIC/">https://labs.arduino.cc/en/labs/micropython</a>, download the latest version of firmware (you can download any version depending on the type of microcontroller you have).</p><p>After it’s downloaded, save it in an easily accessible location such as Downloads, then open CMD in the same path and type the following:</p><pre>python -m esptool --port COM6 --baud 460800 write-flash --flash-size=detect 0 ESP8266_GENERIC-20260406-v1.28.0.bin</pre><p><em>Note: change this ESP8266_GENERIC-20260406-v1.28.0.bin to the name of the version that you downloaded.</em></p><p>If you get like this:</p><p><em>Hash of data verified.</em></p><p><em>Hard resetting via RTS pin…</em></p><p>which means MicroPython installed successfully. Now, you go to Arduino Lab for MicroPython and run the first Python code on the ESP8266.</p><h3>4- Install Arduino Lab for MicroPython</h3><p>From the official website <a href="https://labs.arduino.cc/en/labs/micropython">https://labs.arduino.cc/en/labs/micropython</a> , download the software and install it on your computer.</p><p>Run the software and connect the board to the computer via a USB cable. The software will automatically detect the port, like com4, com5, etc.; select the port.</p><h3>5- Write the first script.</h3><p>If everything is ok, now you can test your first script. You can test the following simple LED on and off code:</p><pre>from machine import Pin<br>from time import sleep<br><br>led = Pin(2, Pin.OUT)<br><br>while True:<br>    led.value(0)<br>    sleep(5)<br>    led.value(1)<br>    sleep(5)</pre><p>Run the code and enjoy the result 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=264594aacc11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Colab with Firebase: practical application]]></title>
            <link>https://medium.com/@abbas7mohammed/colab-with-firebase-practical-application-75613e8f76ad?source=rss-4c1bfa196a5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/75613e8f76ad</guid>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[colab]]></category>
            <dc:creator><![CDATA[Abbas Mohammed]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 18:30:37 GMT</pubDate>
            <atom:updated>2025-08-07T18:30:37.129Z</atom:updated>
            <content:encoded><![CDATA[<p>We write code every day and build applications every time. There are different features in our apps. Today one of the special features of any application is that it contains artificial intelligence (AI) regardless of the type of application.</p><p>This article describes how to use AI by using the Colab framework with a Firebase database, which is used as a backend in the application and exchanges data between them.</p><p>This lesson introduces a prototype for an example. This prototype is a mini project in IoT system to cover what we need in this description. The following diagram illustrates our work, in which we will use sensors to import data from outside and store it in a database (Firebase database) by using a microcontroller (nodeMCU) and transfer this data to the Colab framework to act on some process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*pI14p1x6bpbej0VGx5BS0g.jpeg" /></figure><p>This mini project is irrigation system, in which sensors collect data from outside and store it in a database, and then data move to colab to execute some process and apply AI model to it.</p><p><strong><em>Section One:</em></strong></p><p>This section explains hardware side, where it collect data from any field in outside, our example represented by nodeMCU esp8266 with some sensors like temperature, humidity, etc., since this lesson focus on Firebase and Colab connection, I will settle for some points for Hardware section.</p><ul><li>Prepare all sensors and set them in their proper position.</li><li>Connect these sensors with nodeMCU using jumper wires.</li><li>Open the Arduino IDE and write a code for each sensor (<em>for more, see the Arduino website</em>).</li><li>Go to the Firebase website and create a new project (<em>for more, see the Arduino website</em>).</li><li>Store each sensor values in the Firebase Realtime Database (<em>for more, see the firebase documentation</em>).</li></ul><p>Finally, the structure of the Firebase database is illustrated in the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*5Cv7mHhvpwBJojUDA78OLg.png" /></figure><p>The field off irrigation receives data from colab in case of we want to run any part in the system.</p><p><strong><em>Section Two:</em></strong></p><p>This section is the key focus of the article. It demonstrates how to connect Firebase with Colab to exchange data. I will explain this part step by step and write code for each step.</p><p>1) For the Firebase project, we need the following:</p><ul><li>Database URL</li><li>API Key</li><li>Or <strong><em>serviceAccountKey.json</em></strong> file</li></ul><p><strong>Do the following: </strong>From the Firebase Console:</p><ul><li>Go to Project Settings &gt; Service Accounts &gt; “Generate new private key”</li><li>Download the <strong><em>serviceAccountKey.json</em></strong> file</li></ul><p>2) In Colab:</p><ul><li>Create a new project</li><li>Upload <strong><em>serviceAccountKey.json</em></strong> file</li><li>Install the Firebase library as:</li></ul><pre>!pip install firebase-admin</pre><ul><li>Then type the following code:</li></ul><pre>from google.colab import files<br>uploaded = files.upload()</pre><p>Now we try to connect to the Firebase:</p><pre>import firebase_admin<br>from firebase_admin import credentials, db<br><br># Upload credentials to cred variable <br><br>cred = credentials.Certificate(&quot;serviceAccountKey.json&quot;)<br><br># Change following link with your firebase database link<br># you can get it in project setting in firebase project<br><br>firebase_admin.initialize_app(cred, {<br>    &#39;databaseURL&#39;: &#39;https://&lt;YOUR-PROJECT-ID&gt;.firebaseio.com/&#39;  # ← change this<br>})</pre><p>Once we&#39;ve successfully established the connection, it&#39;s time to import data from Firebase. Notice the following code:</p><pre>ref = db.reference(&#39;/sensor_data&#39;)<br>data = ref.get()</pre><p>Note: <strong><em>/sensor_data</em></strong> is the data path in Firebase.</p><p>We are now bringing the data to our project in Colab for further processing.</p><ul><li>Convert the data into a Dataframe using Pandas.</li></ul><pre>import pandas as pd<br>df = pd.DataFrame(data.values())</pre><p>It&#39;s time to build a model. Import some libraries, such as</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import accuracy_score, classification_report</pre><p>Determine the features and targets, then split the data into training and testing sets:</p><pre>X = df[[&#39;humidity&#39;, &#39;temperature&#39;, &#39;rainfall&#39;]] # inputs <br>y = df[&#39;irrigate&#39;]   # output<br><br># Split data into train and test<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>Now fit a model into data using <strong><em>RandomForestClassifier()</em></strong> method, which combines the predictions of multiple decision trees to produce a more accurate and stable result.</p><pre>model = RandomForestClassifier()<br>model.fit(X_train, y_train)</pre><p>Finally, predict and evaluate the model and then print the report.</p><pre>predict_data = model.predict(X_test)<br>acc_data = accuracy_score(y_test, preds)<br><br>print(f&quot;\n accuracy: {acc:.2f}&quot;)<br>print(&quot;\n classification report:&quot;)<br>print(classification_report(y_test, preds))</pre><p>Until now you have learned how to receive data from Firebase and initialize it in Colab.</p><p>Now we’ll see how to send back data from Colab to Firebase. After running the model and predicting the results, we can send some commands to Firebase. I won’t go into the details of reading the latest data from the sensors, cleaning it, and making a decision based on the latest results, as this process depends on how you read and the required data. However, I will explain how data can be returned to the database based on the decisions made, depending on the results of the process.</p><p>Create a variable to store the last value of the sensors and predict the result.</p><pre>ref = db.reference(&#39;/sensor_data&#39;)<br>data = ref.get()<br><br>latestValue = sorted(data.keys())[-1]<br>latestValue = data[latestValue]<br>latestDf = pd.DataFrame([latestValue]) # convert it to Dataframe<br><br>inputData = latestDf[[&#39;humidity&#39;, &#39;temperature&#39;, &#39;rainfall&#39;]]<br># predic model <br>decision = model.predict(inputData)[0]</pre><p>Now we’ll create a path in the Firebase db like <strong><em>/control/pump_status </em></strong>to store our decision value.</p><pre>controlIrr = db.reference(&#39;/control/status&#39;)<br>status = &quot;ON&quot; if decision == 1 else &quot;OFF&quot;<br>controlIrr.set(status)</pre><p>As noticed in the above code, if decision from prediction is 1 status will be ON; otherwise, it will be OFF and you will see like this in firebase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*JKmn7FT40BPMowouUvOtSA.png" /></figure><p>In this article, you learned how to connect Colab and Firebase and exchange data between these two environments. You can now apply this mechanism to your projects, especially if they are in the field of the Internet of Things, and leverage artificial intelligence to analyze data and make classifications or predictions based on artificial intelligence algorithms.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75613e8f76ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensemble in machine learning]]></title>
            <link>https://medium.com/@abbas7mohammed/ensemble-in-machine-learning-73e737d6de37?source=rss-4c1bfa196a5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/73e737d6de37</guid>
            <category><![CDATA[ensemble]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abbas Mohammed]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 20:59:07 GMT</pubDate>
            <atom:updated>2025-07-27T20:59:07.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y6m66LVnv7YKk61z" /></figure><p>Ensemble learning in machine learning means merging two or more different models or the same model (with a few differences) to improve it and increase accuracy and generalization.</p><p>This technique is used to achieve better accuracy in predictions than any individual learning method could provide on its own. <br>It is based on the idea that some models are good at modeling one part of the data, and others are good at modeling another. The plan is to take advantage of what each model does well while minimizing what each one does poorly.</p><p><strong>Types of Ensemble</strong></p><p>Various ensemble learning methods exist, each with its unique strategy for merging models. In terms of frequency, bagging, boosting, and stacking are at the top. Bagging is a method for reducing variation in predictions by averaging the results of several models trained on separate subsets of the training data. Reducing bias is the main goal of boosting, which trains models progressively on misclassified examples. By feeding their predictions into a meta-model, stacking allows several models to work together. The meta-model figures out how to take the best parts of each model and use them to make a forecast. In subsequent slides, we will go into depth on Bagging and Boosting.</p><p><strong>1- Bagging Method</strong></p><p>Bagging stands for Bootstrap Aggregating, which is a technique used in ensemble learning to reduce the variance of machine learning models. The idea behind bagging is to train multiple models on different subsets of the training data and then combine their predictions to make the final prediction.</p><p>The most famous example is <strong>RandomForest</strong>. The idea is multiple models (often Decision Trees) are trained on different random samples of data (with repetition). The results of these models are then averaged or voted on. The aim of Bagging is to reduce variance and improve stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*-peEUPvp7oyQZGnU39ny-Q.png" /></figure><p>following example in Python using BaggingClassifier from <strong>scikit-learn</strong>, applied to the Iris dataset:</p><pre>from sklearn.datasets import load_iris<br>from sklearn.ensemble import BaggingClassifier<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br># Load dataset<br>X, y = load_iris(return_X_y=True)<br>X_train, X_test, y_test = train_test_split(X, y, random_state=42)<br><br># Create base model<br>base_model = DecisionTreeClassifier()<br><br># Create Bagging ensemble<br>bagging_model = BaggingClassifier(base_estimator=base_model, n_estimators=10, random_state=42)<br>bagging_model.fit(X_train, y_train)<br><br># Predict and evaluate<br>y_pred = bagging_model.predict(X_test)<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))</pre><p>In this example we use 10 decision trees as base estimators (n_estimators=10) and train on the Iris dataset and finally print test accuracy.</p><p><strong>2- Boosting Method</strong></p><p>In order to reduce training mistakes, boosting merges several weak learners into a single strong one. To use boosting, one selects data at random, applies a model to it, and then trains it successively. To rephrase, the goal of each successive model is to address the drawbacks of its predecessor. Rather than one exceptional learner, it seems like we have many mediocre ones. By merging these weak learners, we can create a powerful one with less bias. Popular examples in Boosting method are AdaBoost, Gradient Boosting, XGBoost, and LightGBM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsgqKV9U-2m97AxX5EjmkQ.png" /></figure><p>The idea is that models are trained sequentially, with each subsequent model attempting to correct the errors of the previous model. Higher weight is given to samples that were previously misclassified to reduce bias and increase accuracy.</p><p>following example in Python using <strong>AdaBoost </strong>with a decision tree applied to the Iris dataset:</p><pre>from sklearn.datasets import load_iris<br>from sklearn.ensemble import AdaBoostClassifier<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br># Load dataset<br>X, y = load_iris(return_X_y=True)<br>X_train, X_test, y_test = train_test_split(X, y, random_state=42)<br><br># Create base model<br>base_model = DecisionTreeClassifier(max_depth=1)<br><br># Create Boosting ensemble<br>boosting_model = AdaBoostClassifier(base_estimator=base_model, n_estimators=50, random_state=42)<br>boosting_model.fit(X_train, y_train)<br><br># Predict and evaluate<br>y_pred = boosting_model.predict(X_test)<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))</pre><p>In this example we use AdaBoost (a classic boosting algorithm) which base model is shallow decision trees (max_depth=1) and Ensemble of 50 trees.</p><p><strong>3- Stacking Method</strong></p><p>As an ensemble machine learning technique, stacking (also known as stacked generalization) learns how to optimally aggregate the predictions from many basic machine learning algorithms through the use of a meta-learning algorithm. The main objective is to improve prediction performance beyond what a single model might offer by combining the capabilities of many models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/0*XexNFHluC7TKIGVT.png" /></figure><p>By merging predictions from many models, stacking improves performance, which in turn leads to improved accuracy. This makes the final product more dependable and reduces the Stacking, when combined with appropriate cross-validation, can reduce the likelihood of overfitting by compensating for the shortcomings of individual models.</p><p>following example in Python using⁣ StackingClassifier from scikit-learn:</p><pre>from sklearn.datasets import load_iris<br>from sklearn.ensemble import StackingClassifier<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.svm import SVC<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score<br><br># Load dataset<br>X, y = load_iris(return_X_y=True)<br>X_train, X_test, y_test = train_test_split(X, y, random_state=42)<br><br># Define base learners<br>base_learners = [<br>    (&#39;dt&#39;, DecisionTreeClassifier()),<br>    (&#39;svc&#39;, SVC(probability=True))<br>]<br><br># Define meta learner<br>meta_learner = LogisticRegression()<br><br># Create Stacking ensemble<br>stack_model = StackingClassifier(estimators=base_learners, final_estimator=meta_learner)<br>stack_model.fit(X_train, y_train)<br><br># Predict and evaluate<br>y_pred = stack_model.predict(X_test)<br>print(&quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))</pre><p>In this example we used base learners: Decision Tree + SVC in which their results are then used as input for another model, called a meta-model, to determine the final outcome. here a meta-learner was Logistic Regression applied on the Iris dataset.</p><p>Finally, the ensemble addresses weaknesses in individual models and reduces the possibility of overfitting or underfitting as well as gives higher performance on different datasets.</p><p>Ensemble learning has been successfully applied in various real-world scenarios, one such example is the Netflix Prize Challenge, You can check it on Google.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73e737d6de37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regularization: Ridge and Lasso Regression concepts in machine learning]]></title>
            <link>https://medium.com/@abbas7mohammed/regularization-and-ridge-and-lasso-regression-concepts-in-machine-learning-aba601d69d92?source=rss-4c1bfa196a5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/aba601d69d92</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[ridge]]></category>
            <category><![CDATA[lasso]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Abbas Mohammed]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 12:04:18 GMT</pubDate>
            <atom:updated>2025-04-05T12:12:20.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vPyWQlLMiFeV4Nm2cbydA.png" /></figure><p>There are many challenges in machine learning work, especially when trying to build a model and training a huge amount of data. Overfitting and underfitting are more important challenges, Which must be controlled and prevented from happening.</p><p><strong>What are Overfitting and underfitting</strong></p><blockquote>Overfitting happens when a model learns too much from the training data, including details that don’t matter (like noise or outliers). For example, imagine fitting a very complicated curve to a set of points. The curve will go through every point, but it won’t represent the actual pattern. As a result, the model works great on training data but fails when tested on new data. Overfitting models are like students who memorize answers instead of understanding the topic. They do well in practice tests (training) but struggle in real exams (testing).</blockquote><blockquote>Underfitting is the opposite of overfitting. It happens when a model is too simple to capture what’s going on in the data. For example, imagine drawing a straight line to fit points that actually follow a curve. The line misses most of the pattern. In this case, the model doesn’t work well on either the training or testing data. Underfitting models are like students who don’t study enough. They don’t do well in practice tests or real exams.</blockquote><p><strong>What is regularization?</strong></p><p>Regularization is a technique used to prevent overfitting by adding a penalty term to the model’s loss function. It helps the model generalize better to unseen data by discouraging it from learning noise or overly complex patterns.</p><p><strong>Types of Regularization:</strong></p><ul><li><strong>L1 Regularization (Lasso):</strong> This adds a penalty equal to the absolute value of the magnitude of coefficients. This can lead to some coefficients being zero, which means the model ignores the corresponding features. It is useful for feature selection. The equation of lasso is the following:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*grH2911XwAGzb3Ca5fB-xA.png" /></figure><p>lambda (λ) is the penalty term that denotes the amount of shrinkage (or constraint) that will be implemented in the equation.</p><p>The following image describes two types clearly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*7BiPZpdMLBT8hu-aHGU-Vw.jpeg" /></figure><ul><li><strong>L2 Regularization (Ridge): </strong>Adds a penalty equal to the square of the magnitude of coefficients. All coefficients are shrunk by the same factor, and none are eliminated, as in L1. The equation of lasso is the following:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*5eevc3X1zBZrpa49u67kxw.png" /></figure><p>Here, while lasso regression takes the magnitude of the coefficients, ridge regression takes the square.</p><p><strong>Python implementation</strong></p><p>For this implementation, we will generate a random dataset with using polynomial regression and perform ridge and lasso regression in <a href="https://www.datacamp.com/learn/python"><strong>Python</strong></a></p><p><strong>Steps:</strong></p><p>1- Import important libraries</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.linear_model import LinearRegression<br>from sklearn.preprocessing import PolynomialFeatures<br>from sklearn.metrics import mean_squared_error<br>from sklearn.linear_model import Ridge, Lasso<br>from sklearn.model_selection import train_test_split</pre><p>2- Generate random dataset</p><pre>np.random.seed(42)<br>X = np.random.rand(100,1) * 10<br>y = 3 * X**2 + 2 * X * np.random.rand(100,1) * 5</pre><p>3- Transform features to polynomial</p><pre>poly_feature = PolynomialFeatures(degree=2, include_bias=False)<br>X_poly = poly_feature.fit_transform(X)</pre><p>4- Fit model for polynomial regression values</p><pre>model = LinearRegression()<br>model.fit(X_poly, y)<br>y_predict = model.predict(X_poly)</pre><p>5- Split data to train with 80% and test with 20%</p><pre>X_train, X_test, y_train, y_test = train_test_split(X_poly,y, test_size=0.2, random_state=42)</pre><p>6- Perform Ridge regression using alpha = 1</p><pre>ridge_model = Ridge(alpha=1.0)<br>ridge_model.fit(X_train, y_train)<br>ridge_predict = ridge_model.predict(X_test)</pre><p>7- Perform Lasso regression using alpha = 1</p><pre>lasso_model = Lasso(alpha=1.0)<br>lasso_model.fit(X_train, y_train)<br>lasso_predict = lasso_model.predict(X_test)</pre><p>8- Evaluate Ridge and Lasso regression using mean square error</p><pre># Evaluation Ridge<br>ridge_mse = mean_squared_error(y_test, ridge_predict)<br>print(&quot;Ridge Regression MSE: &quot;, ridge_mse)<br><br># Evaluation Ridge<br>lasso_mse = mean_squared_error(y_test, lasso_predict)<br>print(&quot;Lasso Regression MSE: &quot;, lasso_mse)</pre><p>Full code:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.linear_model import LinearRegression<br>from sklearn.preprocessing import PolynomialFeatures<br>from sklearn.metrics import mean_squared_error<br>from sklearn.linear_model import Ridge, Lasso<br>from sklearn.model_selection import train_test_split<br><br><br># get some data<br>np.random.seed(42)<br>X = np.random.rand(100,1) * 10<br>y = 3 * X**2 + 2 * X * np.random.rand(100,1) * 5<br><br># Transform feature to polynomial<br>poly_feature = PolynomialFeatures(degree=2, include_bias=False)<br>X_poly = poly_feature.fit_transform(X)<br><br><br># Fit polynomial regression<br>model = LinearRegression()<br>model.fit(X_poly, y)<br>y_predict = model.predict(X_poly)<br><br>X_train, X_test, y_train, y_test = train_test_split(X_poly,y, test_size=0.2, random_state=42)<br><br># Ridge Regression<br>ridge_model = Ridge(alpha=1.0)<br>ridge_model.fit(X_train, y_train)<br>ridge_predict = ridge_model.predict(X_test)<br><br># Lasso Regression <br>lasso_model = Lasso(alpha=1.0)<br>lasso_model.fit(X_train, y_train)<br>lasso_predict = lasso_model.predict(X_test)<br><br># Evaluation Ridge<br>ridge_mse = mean_squared_error(y_test, ridge_predict)<br>print(&quot;Ridge Regression MSE: &quot;, ridge_mse)<br><br># Evaluation Ridge<br>lasso_mse = mean_squared_error(y_test, lasso_predict)<br>print(&quot;Lasso Regression MSE: &quot;, lasso_mse)</pre><p>Now run the code and see the result.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aba601d69d92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Python libraries: Numpy , Pandas, Matplotlib In data representation and processing]]></title>
            <link>https://medium.com/@abbas7mohammed/using-python-libraries-numpy-pandas-matplotlib-in-data-representation-and-processing-2859e3e3b4b9?source=rss-4c1bfa196a5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2859e3e3b4b9</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-representation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abbas Mohammed]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 13:01:56 GMT</pubDate>
            <atom:updated>2025-02-07T16:31:10.065Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How to use </strong>python <strong>libraries: Numpy, Pandas, </strong>Matplotlib <strong>In data representation and processing</strong></h3><p><strong>Getting to know libraries like Numpy , Pandas, Matplot and how to use it through a practical application . </strong><br> <strong><br> Note: The famous editor will be used. jupyter In the examples provided in the explanation, you can use any editor you prefer . </strong><br> <strong><br> <br> Getting started …</strong></p><p>First I will explain some parts of the system. jupyter Where it is considered jupyter An integrated system and one of the huge open source projects through which many programming languages are coded such as Python, Java, Matlab, Ruby, and others (popular among Python developers). The image below shows the environment. jupyter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FkJ5CAM5ErxhcF1Z2U9yAA.png" /><figcaption>jupyter note book</figcaption></figure><p>He provides jupyter Workspace Suitable for programmers through many features that help the programmer in writing the code, implementing it and seeing the results. You can go to the site through the following link :</p><p><a href="https://www.blogger.com/blog/post/edit/5197302306873432651/1965397186082633978">https://jupyter.org/index.html</a></p><ul><li><strong>Installation jupyter // </strong><br> <strong><br> I</strong>nstall Jupyter Using the pip package , preferably the latest version, so it will update pip <br> <br> — open the command window through the run window as shown in the picture</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*NNsEtcdLPkqDHrnyBK6HEA.png" /></figure><p>After opening the window cmd Type the following command :</p><p><strong><em>pip3 install — upgrade pip</em></strong></p><p>It will update the pip package. <br> <br> — Now install jupyter Through the following command :</p><p><strong><em>pip3 install jupyter</em></strong></p><p>* After finishing, type the following command and press enter to open the system jupyter :</p><p><strong><em>jupyter notebook</em></strong></p><p><strong>Environment will be opened Jupyter.</strong></p><p><strong>Note: It is possible to run the system Jupyter Through your browser via the link : </strong><a href="https://www.blogger.com/blog/post/edit/5197302306873432651/1965397186082633978">https://nbviewer.jupyter.org/ </a><br> <strong><br> <br> * To create a new project, click on the New icon and then choose python3. The image below shows some of the features within the system .</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*unp6yVqb-fXznHMK.JPG" /></figure><p><strong>&gt;&gt; Here are some shortcuts to control the cell, such as deleting, inserting, and changing. You can also modify the shortcuts through the Edit icon.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*y3oDgDtX9_o_ZLZ2.JPG" /></figure><p><strong>Type the following code inside the cell and press Run or ( ctrl+Enter ) from the keyboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uxRLzlDBWTe8JCy7.JPG" /></figure><p>You will notice the code inside the cell stores the number [1] as a cell pointer and next to it In to indicate the input or Out to indicate the output.</p><p><strong>To learn more about the features of Jupyter You can refer to the site’s documentation through the link</strong></p><p><a href="https://www.blogger.com/blog/post/edit/5197302306873432651/1965397186082633978">https://jupyter.readthedocs.io/en/latest/</a></p><p><strong>Moving on to the main topic …</strong></p><p>Now move on to explaining libraries and start with <br> <br> <br> <strong>first // the library Numpy</strong></p><p>It is considered a library. Numpy One of the important libraries in Python that is used in mathematical operations, processing multi-directional arrays, and complex mathematical functions. It is an abbreviation for (numerical Python), as it includes many functions to perform operations on data, process it, and output it in the required form .</p><p>- Install a library Numpy Through the pip package, write the following command in cmd</p><p><strong><em>pip install numpy</em></strong></p><p>Wait until the installation is complete .</p><p>Go to jupyter and open a new project</p><p>- First, Call the library through the import command as follows :</p><p><strong><em>import numpy as nm</em></strong></p><p>Then write the code</p><p>Let’s take an example by creating a one-dimensional array as in the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eQEM2rnajEUkL-gH.JPG" /></figure><p>Note: The code will be in the form of an image throughout the explanation so that the reader can apply the code with his own hands and avoid copying and pasting .</p><p>Here is another two-dimensional matrix as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CmsapwBGiEJDbnMi.JPG" /></figure><p>Here is a unitary matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FK2w2Me6H92qL-n4.JPG" /></figure><p>This is how to make a matrix with equal elements = 5</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KvFCSj0KkLFGhiLF.JPG" /></figure><p>Here it declare a new array called c and change the element with position (2,2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5OVBGvTtsS9V5dm0.JPG" /></figure><p>example , use the sum function to extract the sum of the elements as shown in the result :=</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BEpmm5vxBctpHncR.JPG" /></figure><p>There are many special functions for this library that can be referred to through the site .</p><p>********************************</p><p><strong>Second // Pandas Library</strong></p><p>Pandas library provides speed and flexibility in dealing with data and creating a structure for data using frameworks that support data scheduling and relationships between them, which facilitates the process of analyzing and counting data in a wonderful way.</p><p><strong>Pandas library using pip package</strong></p><p>- Go to cmd and type the following command:</p><p><strong><em>pip install pandas</em></strong></p><p>- Go to Jupyter Open a new project and import the library.</p><p><strong><em>Import pandas as pd</em></strong></p><p>&gt;&gt; Pandas library uses several methods to tabulate data, including :</p><p><strong>1- Series:</strong> Used to represent one-dimensional matrices.</p><p>Where the Series uses the index instruction to address each value inside the array .</p><p>Let’s take the example and apply the series to see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WEv8AomDR5b2necH.JPG" /></figure><p>here :</p><p>* declared a data variable and assigned it an array value using the library Numpy As we have already taken</p><p>* declared another variable a and assigned it the index value to address the elements of the array, and we will see that in the result.</p><p>* Using Series assign index to array elements .</p><p>Now execute the code to see the result as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S6-t0vsiEOpmymjA.jpg" /></figure><p><strong>2- DataFrame :</strong> Used to represent two-dimensional matrices.</p><ul><li>take the example and apply the DataFrame</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-_377jYkh9EP0jyi.JPG" /></figure><p>here :</p><p>* used the variable data1 which is a Dictionary that contains the element and its value .</p><p>* created an object from DataFrame And its assignment to the variable c, which includes the index and column headings .</p><p>execute the code and notice the result as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*SM-KVJYIwBQQJ-TY.JPG" /></figure><p>amazing !</p><p>We can also extract part of the matrix as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a0Hm9X8Zx1OFf4JC.JPG" /></figure><p>You can also extract only one column as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d1a8d_YTcrmme6VO.JPG" /></figure><p>********************************</p><p><strong>Secondly // Library Matplot</strong></p><p>It is considered a library. Matplot It is one of the huge and very famous libraries in the world of Python, as it is widely used in modeling and representing data and provides interactive environments and charts that make data easy to count, analyze, or represent .</p><p><strong>Matplot library using pip package</strong></p><p>- Go to cmd and type the following command:</p><p><strong><em>pip install matplot</em></strong></p><p>- Go to Jupyter Open a new project and import the library.</p><p><strong><em>import matplotlib.pyplot as plt</em></strong></p><p><strong>Library contains Matplot There are many functions for drawing. I will try to touch on a group of them .</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AG12zTfazgotytEy.JPG" /></figure><p>- In this example called a library Matplot On Object plt also declared the variable x as an array using the library. numpy</p><p>- Then use a function plot to plot the function .</p><p>show function is used to display the shape .</p><p>How easy ^__^ .</p><p>* it will add addresses to the x and y coordinates using xlable and label And also a title for the form using title as in the image below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bn0l5hxDcHLD7gH-.JPG" /></figure><p>Another example where used color and shape :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rpLrw92clXup1CmJ.JPG" /></figure><ul><li>Here we have drawn curve number 2.</li></ul><p>- The first curve z^ 2: Takes the blue color and square shape using ‘bs’.</p><p>- The first curve z^ 3: Takes the green color and the ^ shape using ‘^g’.</p><p>can be divided into several plots using figure and subplot. As follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GA1ODDJlq9CrEZbs.JPG" /></figure><p>Here it used plt.grid (True) to display a grid behind the curve .</p><p>Also another type of pie chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/0*gnyoVbBYXH-Rb67O.JPG" /></figure><p>There are many diagrams and functions that cannot all be listed in this article .</p><p>But you can refer to it through the library’s website at the following link:</p><p><a href="https://www.blogger.com/blog/post/edit/5197302306873432651/1965397186082633978">https://matplotlib.org/</a></p><p>I hope you have benefited from this lesson. You still have to practice and apply for more examples.</p><p>😊 enjoy</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2859e3e3b4b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini API in Web application]]></title>
            <link>https://medium.com/@abbas7mohammed/gemini-api-in-web-application-518b4b2b4bd8?source=rss-4c1bfa196a5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/518b4b2b4bd8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[gemini-api]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Abbas Mohammed]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 14:17:43 GMT</pubDate>
            <atom:updated>2024-11-20T18:04:07.793Z</atom:updated>
            <content:encoded><![CDATA[<p>In this lesson we will learn how to use Gemini api in our web app</p><p><strong>Lesson title</strong>/ Using Gemini API in websites<br><strong>Specialization</strong>/ Artificial Intelligence<br><strong>Level</strong>/ All<br>Note: The language used in the lesson is JavaScript using React JS<br>Steps:<br>1- Create a new React project through the following lines:</p><pre>npx create-react-app gemini-api<br>cd my-app<br>npm start</pre><p>2- Install the Google AI package on the project as follows:</p><pre>npm i @google/generative-ai</pre><p>We need a developer API key to use Gemini AI and to create a developer API key, go to the following link <a href="https://aistudio.google.com/app/apikey">https://aistudio.google.com/app/apikey</a> Then we create the key.. Once created, copy it to a secure location within your system to use it later in the application.<br>3- By return to our project in react and open the App.js file and delete the code inside it, then we call the Google ai library as follows:</p><pre>import { GoogleGenerativeAI } from &#39;@google/generative-ai&#39;;</pre><p>4- Create a <em>genAI</em> object from the <em>GoogleGenerativeAI</em> class by passing the API key so that we can access all the functions it provides. As follows:</p><pre>const API_KEY = &quot;AIzaSyAAYmJ0_U61wa8toBUo_J_XXelgoNJz6-c&quot;; // put your api key here</pre><p>5- Use <em>useState </em>to enter questions into gemini and also to print the generated answer, through the following code:</p><pre>const [geminisearchValue, setsearchValue] = useState(&#39;&#39;);<br>const [geminiResponse, setgeminiResponse] = useState([]);<br>const handlesearchInput = (e)=&gt;{<br>setsearchValue(e.target.value);<br>}<br>&lt;input type=&quot;text&quot; class=&quot;form-control&quot;<br>value={geminisearchValue}<br>onChange={handlesearchInput}<br>placeholder=&quot;type here&quot; required<br>/&gt;</pre><p>6- Now back to the code for the gemini api and explain it in detail:<br>create a function <em>getResponseforGemini </em>and put the following lines inside it:<br>- Create a model for the gemini api and here we used gemini-1.5-flash as follows:</p><pre>const model = genAI.getGenerativeModel({ model: &quot;gemini-1.5-flash&quot; });</pre><p>- Create a variable <em>result </em>and assign it the input value to the model through <em>model.generateConten</em>t as follows:</p><pre>const result = await model.generateContent(geminisearchValue);</pre><p>- Create a variable <em>response </em>and assign it the value of the result coming out of the model through <em>result.respons</em>e as follows:</p><pre>const response = result.response;</pre><p>- Finally, convert the value of extracting the writing from the response through <em>response.text</em> as follows:</p><pre>const text = response.text();</pre><p>In this lesson, we used the Generate text from text-only input feature, which is the process of generating writing from writing only.<br>- Now we put the result in the <em>geminiResponse</em> variable in order to display it on the site as follows:</p><pre>setgeminiResponse([...geminiResponse,text]);</pre><p>Here is the full code:</p><pre>import { useState } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import { GoogleGenerativeAI } from &#39;@google/generative-ai&#39;;<br>import ReactQuill from &quot;react-quill&quot;;<br>import &#39;react-quill/dist/quill.snow.css&#39;;<br><br>function App() {<br><br><br>  const [geminisearchValue, setsearchValue] = useState(&#39;&#39;);<br>  const [geminiResponse, setgeminiResponse] = useState([]);<br><br><br>  const handlesearchInput = (e)=&gt;{<br>    setsearchValue(e.target.value);<br>  }<br><br><br><br>  const API_KEY = &quot;AIzaSyAAYmJ0_U61wa8toBUo_J_XXelgoNJz6-c&quot;;  // put your api key here<br>  const genAI = new GoogleGenerativeAI(API_KEY);<br><br>  const getResponseforGemini = async ()=&gt;{<br>    try{<br>const model = genAI.getGenerativeModel({ model: &quot;gemini-1.5-flash&quot; }); <br>const result = await model.generateContent(geminisearchValue);<br>const response = result.response;<br>const text = response.text();<br>console.log(text);<br>setgeminiResponse([...geminiResponse,text]);<br>    }<br>    catch (error) {<br>      console.log(error);<br>      console.log(&quot;Something Went Wrong&quot;);<br>    }<br>  };<br><br>  return (<br>    &lt;div style={{height:&#39;700px&#39;, backgroundColor: &#39;#F2F3F4&#39;}}&gt;<br>      &lt;ReactQuill theme=&#39;snow&#39;/&gt;<br>        &lt;div class=&quot;container&quot; style={{padding:&#39;70px&#39;}}&gt;<br>            &lt;div style={{display:&#39;flex&#39;, justifyContent: &#39;center&#39;}}&gt;<br>                &lt;h1&gt;<br>                    Hi Gemini!<br>                &lt;/h1&gt;<br>            &lt;/div&gt;<br>            &lt;div style={{marginTop: &quot;30px&quot;}}&gt;<br> <br>                    &lt;div class=&quot;col-md-4&quot; style={{padding:&#39;20px&#39;}}&gt;<br>                      &lt;label for=&quot;validationCustom01&quot; class=&quot;form-label&quot;&gt;ask what you want&lt;/label&gt;<br>                      &lt;input type=&quot;text&quot; class=&quot;form-control&quot;<br>                      value={geminisearchValue} <br>                      onChange={handlesearchInput} <br>                      placeholder=&quot;type here&quot; required <br>                      /&gt; <br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;col-12&quot;&gt;<br>                      &lt;button class=&quot;btn btn-primary&quot;<br>                      onClick={getResponseforGemini}<br>                      &gt;<br>                        GO<br>                      &lt;/button&gt;<br>                    &lt;/div&gt;<br>                    &lt;div class=&quot;form-floating&quot;&gt;<br>                      {<br>                        geminiResponse.map((geminiRes,index)=&gt;(<br>                          &lt;div key={index}&gt;<br>                            &lt;div className={`response-text ${index === geminiResponse.length - 1 ? &#39;fw-italic&#39; : &#39;&#39;}`}&gt;{geminiRes}&lt;/div&gt;<br>                          &lt;/div&gt;<br>                        ))<br>                      }<br>                        <br>                    &lt;/div&gt;<br><br>            &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;<br></pre><p>Final result in the image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I59mbIpnNiKQmgdF-hSLhw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518b4b2b4bd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>