Posts Tagged ‘learn’

Flowers in my lens..6

Another beautiful flower in taken by Galaxy Note 9. Setup on a table with a coffee Mug. Follow me on Twitter @h_ta3kees




Another sketch challenge: The House

March 12, 2021 Leave a comment

This week sketch challenge @1hour1sketch is to Draw a Red House, so here is my sketch using pencil, black Pen and watercolour. More Sketches on my Sketch page .. also follow me on Twitter @h_ta3kees

Ali radwani drawing sketch challenge 1hour1sketch color watercolor pen pencil

Python: Data Visualization Part-1

January 6, 2021 1 comment

Learning : python, pygal, Data Visualization, Bar Chart
Subject: Data visualization using pygal library

pygal is a Data Visualization library in python to help us showing our Data as a graph. In coming several posts we will discover and learn how to use the pygal library in simple and easy configuration and style.

First we need to install pygal packeg, to do so write this:
pip install pygal

Now we need some Data to show, in this leson I am using aGalaxy Tab S4, so all the codes will be tested and applyed on website [ alow us to use pygal package online so we don’t need to install it on our divice]

Type of Chart:
pygal has several types of charts that we can use, here we will list them all then in coming posts will use each one with simple data. So what we have:
Line, Bar, Histogram, XY,
Pie, Radar, Box, Dot,
Funnel, SolidGauge, Gauge, Pyramid,
Treemap, Maps

Some of those charts has a sub-types such as in Bar char we have: Basic, Stacked and Horizontal. Also for each chart we can add a title and labels and we can use some styles.

So let’s start ..
First we will go for the Bar chart, and we have three sub-types as Basic, Stacked and Horizontal.

First chart: Bar chart:
In this part we will demonstrate the Bar Chart, it has three sub-types as Basic, Stacked and Horizontal.

We assume that our data is the Males and Female ages on first marage, the data will be as dictionary (later we will see how to customize each bar)

 # Basic Bar Chart using pygal

import pygal 
bar_chart = pygal.Bar() # To create a bar graph object
bar_chart.add('Females', [22,25,18,35,33,18]) 
bar_chart.add('Males', [30,20,23,31,39,44]) 

bar_chart.title = "Males and Females First Marage Age"

Sample code for Basic bar chart

Another sub-type in Bar chart is Horizontal-Bar, it is semelar to the Basic but as if fliped 90 degree. Here is the code ..

 # Horizontal Bar Chart using pygal

import pygal

# HorizontalBar()
HBar = pygal.HorizontalBar()
HBar.add('Females', [22,25,18,35,33,18]) 
HBar.add('Males', [30,20,23,31,39,44]) 

HBar.title = "Males and Females First Marage Age"



Sample code for Horizontal Bar chart

Last sub-type in Bar chart is Stacked Bar were all data of each element will be in one bar. Here is the code and example..

 # Stacked Bar Chart using pygal

import pygal 
# StackedBar() 
stackedbar = pygal.StackedBar()
stackedbar.add('Females', [22,25,18,35,33,18]) 
stackedbar.add('Males', [30,20,23,31,39,44]) 
stackedbar.title = "Males and Females First Marage Age"


If we say we have another data-set as “age in First-Divorces” and we want to add this set to the Stacked Bar chart, then we first will create the data-set as:
stackedbar.add(‘Divorses’, [35,22,45,33,40,38])
and we will arrange the code line to be at top,middle or bottom of the bar. Here is the code..

Sample code for stacke Bar chart with Divorce data

Next we will talk about Line chart.

:: Data Visualization using pygal ::

Part-2 Part-3 Part-4

Follow me on Twitter..

By: Ali Radwani

To The Freedom

August 3, 2020 Leave a comment

Another sketche I woke on with watercolor.

Follow me on Twitter

Python: Shares Speculation System – Part 4

July 19, 2020 3 comments

Learning : Python, DataBase, SQL, SQlite3
Subject: Plan, Design and Build a Shares Speculation System

Project Card:
Project Name: Shares Speculation System
By: Ali
Date: 2.7.2020
Version: V01-2.7.2020

Last time we worked on Budgets Managment for our system, now before we start Buying and Selling shares we need to create list of shares name so we can select from it, we have a table called shares_name this Table have the following fields :
s_id: as a PRIMARY KEY.
full_name: To hold the full name of the share.
abb_name: To hold the Abbreviation of a share name.
The Share Managment section will have four main Functions to Add, Edit, Delete and Show shares. .. Let’s start with it’s Main Menu ..

First Function we will work on will be to Add New Share to the system, we will call it def add_share(): , we will ask the user to input the Share Full Name and its Abbreviation. With Abbreviation we will apply the .upper() function to convert the user input to Upper-case, and for the Full Name we will will apply this code [“ “.join([word.capitalize() for word in user-input] to upper case each first character of the Name. The we will check if the Share Name exist in the DataBase If not we will add it.

 # Add New Share
def add_share() :
    print('\n   ====== Add New Share ======\n\n')
    while True :
        abb_name = input("   Enter the Abbreviation Name of the Share.. > ").upper() 
        full_name = " ".join([word.capitalize() for word in input('     Enter the Full Name of the Share.. > ').split(" ")])

        c.execute ("select * from shares_name where full_name ='{}' or abb_name = '{}'".format(full_name, abb_name)) 
        share_exist = c.fetchone ()
        if share_exist[0] > 0 :
            print('\n   It seams that the Share Exist in the Database, Name or Abbreviation CAN NOT be Duplicated.')
            print('   Try another Name. ')
        else :      
            c.execute ("INSERT INTO shares_name (full_name , abb_name)  VALUES(:full_name , :abb_name)",{"full_name":full_name, "abb_name":abb_name}) 
        if input ('\n   Do you want to Enter another Share Name?.  [Y,N]. >  ')  not in ['Y','y']: 
            input ('\n    .... Press any key to  Exit.  ')

After adding shares we want to see them and to make sure if every things are fine, so we will write the show_share function, and it will take one argument as inside with default value = ‘Yes’, if we call the function from inside another function the value will be Yes, otherwise it will be ‘No’. Here is the code ..

Next is Editing Share Name, in this function we will call the show_share (‘Yes’) so the user will select the ID of the Share Name to be Edit, then with each attribute we will ask the user ether to Enter the new Edit of the attribute or to press Enter to keep the exist variable. .. Here is a copy of the code ..

Last Function in this Artical is Delete def delete_share() : again we will call the Shoe function to display all the Shares Name on the screen and let the user to select the one to be Deleted by Entering it’s ID.

 # Delete Function.    
def delete_share() :
    print('\n   ====== Delete a Share  ======\n\n')
    print('   Here is a list of Shares we have in the System .. \n')
    del_share = input('\n\n   Enter the ID for the Share Name you want to Delete. [Q to Exit] >  ') 

    if del_share in ['q', 'Q'] :
        input ('\n\n    .... Press any key to  Exit.')
    elif del_share.isnumeric() :
        if (input ('   Are you SURE you want to DELETE Share ID {} ? [Y,N] >  '.format(del_share))) in ['y','Y'] :   
            c.execute ("delete from shares_name where s_id ={}".format(int(del_share))) 
            input ('\n    ....One Record DELETED. Press any key to  Exit.')
        else :
            input ('\n    ....Share will NOT be Deleted. Press any key to  Exit.')
    else :
        input ('\n    ....Invalid Inpout. Press any key to  Exit.')

Now we can create or Enter a Budget and Enter the Shares Name we have in our Stock Market and we are ready to write the functions to make the transactions.

Coming Up: In Next part we will write the Function to submit/Save Buying and Selling Transactions to our system.

1. Part-1 has no code file.
2. We are applying some basic Validations on some part of the code, and assuming that the user will not enter a messy data.

:: Shares Speculation System ::

Part 1 Part 2 Part 3 Part 4

To Download my Python code (.py) files Click-Here

Follow me on Twitter..

By: Ali Radwani

Python: Shares Speculation System – Part 3

July 14, 2020 4 comments

Learning : Python, DataBase, SQL, SQlite3
Subject: Plan, Design and Build a Shares Speculation System

Project Card:
Project Name: Shares Speculation System
By: Ali
Date: 2.7.2020
Version: V01-2.7.2020

In this part we will start writing some codes for our System, we will start with Budget Managment.

Budget: In the Shares Speculation System, and before the user can submit any Buying Transactions the system will check If there is enough money in the Budget Repository, so first we have to Insert a Budget. Therefore, we will start from Budget Managment.
Budget Managment will have five sub-menu as follow:
1. Add New Budget.
2. Withdraw Budget.
3. Edit a Budget.
4. Delete a Budget.
5. Show all Budget.
9. Exit.

So we will start writing the functions for each one.. let’s start with the Budget Menu, we use the while True: loop to keep the Menu until uer_choice == 9 where we return the user to the previous Menu. Here is the code:

Now, lets go through each Function..

Add New Budget: This Function will ask the user to Enter three pieces of information, The Date, The Budget Amount and if the user want to add some Notes such as cheque number or the source of the mouney/fund. For the Date, we want to make sure that the user entry is in the format we want and it is a date, so i wrote a function called date_validation () we will talk about this function later. For the Note part after the user enter the notes we will do (upper-case) for each first character in the text using this code: bud_note = ” “.join([word.capitalize() for word in bud_note.split(” “)]) Here is the full code ..

 # Add New Budget to the system.

def add_budget (): 
    print('\n   ====== Add New Budget ======\n\n') 
    print('   Enter the Details of the Budget..\n')
    while True :
        bud_date = input ('   Enter the Date as [dd-mm-yyyy].  >  ') 
        msg = (date_validation (bud_date))
        if msg !='valid' :
    bud_amount = input ('   Enter the Budget Amount.  >  ')
    bud_note = input ('   Enter any Notes if you want. [Hint: Cheque No.] >  ') 
    bud_note = " ".join([word.capitalize() for word in bud_note.split(" ")])    
    c.execute ("INSERT INTO budget_t (bud_date ,bud_amount, bud_note)  VALUES(:bud_date ,:bud_amount, :bud_note)",{"bud_date":bud_date ,"bud_amount":float(bud_amount), "bud_note":bud_note}) 
    input('\n\n        ... Press any Key to Exit')   

For the Budget Date we want the date to be in certain format, so we wrote a function that will take the user_input and check it’s format then return a message back, the message will be ‘Valid’ if the date format is correct, otherwise the message will give a hint if format error as:
Date Not Valid “Bad Year” or Date Not Valid “Bad Month” or Date Not Valid “Bad Day”. Here is the code for the Date Validation Function ..

Next we will write a function so we can withdraw some amount of money from the Budget, Why?? If we assume we start our Shares Speculation with 100,000$ and after several Buying and Selling we gain say 50,000$ as Profits, and we want to use this cash the [50,000$] to buy something; therefore we need to subtract / withdraw from the system. Here is the code to do this and the system will add [ WITHDRAW ] to the Note field.

 # To withdraw form the Budget

def sub_budget (): 
    print('\n   ====== Withdraw from Budget ======\n\n')
    print('   Enter the Details of Withdraw Amount..\n')
    while True :
        bud_date = input ('   Enter the Date as [dd-mm-yyyy].  >  ') 
        msg = (date_validation (bud_date))
        if msg !='valid' :
    bud_amount = input ('   Enter the Withdraw Amount.  >  ') 
    if int(bud_amount) > 0 : 
        bud_amount = int(bud_amount) * (-1)
    bud_note = input ('   Enter any Notes if you want. [Hint: Cheque No.] >  ')
    bud_note = "[ WITHDRAW ], " + bud_note 
    bud_note = " ".join([word.capitalize() for word in bud_note.split(" ")])
    c.execute ("INSERT INTO budget_t (bud_date ,bud_amount, bud_note)  VALUES(:bud_date ,:bud_amount, :bud_note)",{"bud_date":bud_date ,"bud_amount":bud_amount, "bud_note": bud_note}) 
    input('\n\n        ... Press any Ket to Exit')   

Now, in both Edit and Delete function we need to show the Budgets we have so the user will select the one for processing. So we will write the code to show Budgets in the system and we will present it as a Table. Here is the code ..

 # To show the Budget Table
def show_budget (inside='No'): 
    if inside =='No' :
        print('\n   ====== Show Budgets ======\n\n') 
        print('   List of Budgets ..\n')
    c.execute ("select * from budget_t where bud_id >0") 
    budgets = c.fetchall() 
    print('      {:<10}{:<13}{:<16}{}'.format('ID','Date','Amount','Note'))
    print("    ","-"*70)
        for x in range(0,len(budgets)) : 
           print("      {:<8}{:<14}{:,}{:0") 
        budget_amount = c.fetchone() 
        print('\n\n    The Total Amount Budgets in the Account is : {:,} '.format(budget_amount[0]))
        input('\n   ... Press any key to Exit')   

So we have another two Functions [Edit, Delete] to go, the easyer one is Deleting Budget. In Delete function we will display a table with all Budgets we have in the system and the user will enter the ID of the Budget to be Deleted, we will ask the user to confirm the action then if CONFIRMED the Budget will be Delete. .. Here is the code ..

Last function in this part is to Edit a Budget that we have in the system, to do this we first will display all Budgets we have and the user will Enter the ID of the one to be Edited, we will go through it’s attributes asking the user to Edit or just Press enter to skip and keep the current value. For the Date we will call the date_validation() after user input, and for the Note we will check the Amount if it is Negative we will add “[ WITHDRAW ]” in the beginning of the Note line.

 # Edit Budget Function

def edit_budget (): 
    print('\n   ====== Edit Budget ======\n\n') 
    show_budget (inside='Yes')
        edit_budget = input ('\n\n    Select the Budget ID to Edit.  > ')
        c.execute ("select * from budget_t where bud_id ={}".format(int(edit_budget))) 
        e_budget = c.fetchone()
        if e_budget != None: 
            print('\n    You Select to Edit this Budget ..') 
            print('\n    ID Not Valid ... ')
        print('\n       ID: ',e_budget[0])
        print('     Date: ',e_budget[1])
        print('   Amount:  {:,}'.format(e_budget[2]))
        print('     Note: ',e_budget[3])
        print('\n\n   Edit Each Attribute OR Press Enter to Skip.. \n')
        while True :
            new_b_date = input('   Enter the New Date as [dd-mm-yyyy]. > ')
            if new_b_date >"" : 
                msg = (date_validation (new_b_date))
                if msg !='valid' :
                    c.execute("update budget_t set bud_date = '{}' where bud_id = {}".format(new_b_date,int(e_budget[0]))) 
            elif new_b_date =="" :break
        new_b_amount = input('   Enter the New Amount > ')
        if new_b_amount > "" : 
            if input ('\n   You want to change the Budget Amount From {:,}  To {:,}. CONFIRM [Y,N] > '.format(float(e_budget[2]),float(new_b_amount))) in ['Y','y'] :
                c.execute("update budget_t set bud_amount = '{}' where bud_id = {}".format(float(new_b_amount),int(e_budget[0]))) 
            print('   Budget Amount Not changed..\n')
        new_b_note = input('\n   Enter the New Note: > ')
        if new_b_note > "" :
            new_b_note = " ".join([word.capitalize() for word in new_b_note.split(" ")])
            if (e_budget[3])[0] =='[' and int(new_b_amount) < 0 :
                new_b_note = "[ WITHDRAW ], " + new_b_note     
            c.execute("update budget_t set bud_note = '{}' where bud_id = {}".format(new_b_note,int(e_budget[0])))          
        input('\n   ... DONE ...  Press any key to Exit')
        input('\n       ... Error in User Input.  ... Press any key to Exit ...')

Coming Up: In Next part we will write the menu and the functions for the Shares Managment.

1. Part-1 has no code file.

:: Shares Speculation System ::

Part 1 Part 2 Part 3 Part 4

To Download my Python code (.py) files Click-Here

Follow me on Twitter..

By: Ali Radwani

Python: Library Managment System -P5

July 1, 2020 1 comment

Learning : Python, DataBase, SQlite
Subject: Create Simple Library Managment System

In this Part we will work on Books Managment Functions, New Book, Edit, Delete and Show Books. First, I want to mention that I did some modifications on:

  • Authors Functions:
    Update on show_Author, Edit_author, Delete_author and new_authors.
  • Classifications Functions:
    Update on Show_classification, Edit Classification, Delete Classification.

When I start writing the code for Adding New Book after that the code for Editing a Book, I notes that both are complex and going back or calling other functions such as show_authors, show_classification, I fond that we need to do some modifications on those functions, for all that I will not cover all codes in New and Edit functions. All the code IS available in the Download Page.

So lets start here with the easy functions, First we will see the show_book, in calling this function we will pass two parameters alone, list_type as def show_books(alone=’Yes’, list_type = “D”) both has default values.
alone: alone will be ‘No’ if we call the function within another function.
list_type: will have ‘D’ for Detail list of Book, list with Author data and Classifications. ‘T’ for Books list ID and Title only.
Here is the code ..

 # show books with two parameters

def show_books(alone='Yes', list_type = "D") : 
    c.execute ("select * from books where b_id > 0  order by b_name")     
    books_list = c.fetchall()           
    if list_type =="D":
        print('\n   ====== Show Books ======')
        print('\n   The List of Books We Have, Sorted by Book Title\n') 
        for book in range (0,(len(books_list))):
               print('\n             ID: {}'.format(books_list[book][0])) 
               print('     Name/Title: {}'.format(books_list[book][1]))
               print('      Book ISBN: {}'.format(books_list[book][3]))
               print('   Publish Date: {}'.format(books_list[book][4])) 
               print('   Book Edition: {}'.format(books_list[book][5]))
               # To get the Book Classification. 
               c.execute ("select class_name from classifi_list INNER JOIN b_class ON (classifi_list.class_l_id = b_class.class_id) AND (b_class.b_id ={})".format(books_list[book][0]))     
               b_class_list = c.fetchall()
               print('\n   Book Classification:')
                   for i in range(0,len(b_class_list),5) :
                       print(' '*15,b_class_list[i][0], end ="")
                       print(' | ',b_class_list[i+1][0], end ="")
                       print(' | ',b_class_list[i+2][0], end ="")
                       print(' | ',b_class_list[i+3][0])    
               auth_id = books_list[book][2]
               # To get the Author Data. 
               c.execute ("select * from authors where a_id = {}".format(int(auth_id)))     
               auth_list = c.fetchone()
               # To get the Author's Social Media Accounts. 
               c.execute ("select * from sma where a_id = {}".format(auth_id))  
               sma_list = c.fetchall()  
               # To print-out Author Data.
               print('\n\n   The Book Author:')
               print('           Name: {}'.format(auth_list[1]))
               print('          Email: {}'.format(auth_list[2]))
               print('          Social Media:')
               # Here we list the SMA for the Author.
               for each in sma_list :  
                  print('{:<14}{:<13} [ {} ]'.format('',each[2],each[3]))
        input('\n\n         ... Press any Key ..') 

    if list_type == "T" :
        for book in range (0,(len(books_list)),4):
                print('    {:<3}{:<27}'.format(books_list[book][0],books_list[book][1]),end="")
            #Exception for index out of range error.
        if alone =='Yes' :         
            input('\n\n         ... Press any Key ..')
        else : return    

Now the Delete Function, this is easy one, we just print print-out all the Book and the user will Select the one to be delete by Entaring it’s ID. To list the Books we will call the show_book function as here: show_books(‘No’,’T’) so parameter alone=’No’ and parameter list_type =’T’. Here is the code ..

 # Function to Delete a Book

def delete_book () :

    print('\n   ====== Delete a Book ======')
    print('\n   The List of Books We Have, Sorted by Book Title\n') 
    # First we show all Bookd so the user can select the One to be Deleted.
    # we Call show_books function and pass 'T'. 
    del_book = input('\n\n   Entert the Book ID that you want to Delete: [Q to Exit]  >  ') 
    if del_book not in ['q','Q'] :
            c.execute ("select b_name from books where b_id = {}".format(int(del_book)))     
            d_b_name = c.fetchone() 
            if input('\n   Are you Sure you want to Delete Book "{}"? [Y,N].  >   '.format(d_b_name[0])) in ['Y','y'] :             
                c.execute ("delete from books where b_id = {} ".format(int(del_book)))
                input('\n   One Book has been Deleted... Press any Key > ')    
                print('\n   You Select NOT To Delete The Book "{}" . '.format(d_b_name[0]))
                input('\n   To Exit ... Press any key ..') 
            input('\n   Not valid .. ')

Now lit’s start with Adding New Book to the Library System. In this process we will Enter New Book Name/Title, Book ISBN, Book Publish Date, Book Edition, and select an Author from the Authors List and if the Author is not exist we can Enter New Author, also to select a Classification and if we want we can Enter a new Classification.[If the one we want is not in the list]. As we can see in the Adding New Book we will call other functions to Show Authors then to Add new Author [If the one we have not on the list] also we will call the Show Classifications to select from and we may need to Add New classification.

The Editing the Books was really challenging, Showing all the the Books on the screen so the user will select the one to be edited, then once finished editing the Book attributes we will ask if the user want to edit the Author information if (YES) again will go through all Author attribute and ask if each one need to be Edit, IF the Author is not in the Authors list we will take the user to Add new Author to the system (if want to), after that we will ask if the user want to edit the classifications of the Book and if the classificatio is not in the list we will call the new_classification function.
Here are screen shot of the functions. ..

Part of Add New Book..
Part of Editing the Book.

What’s Next:
1. I will go through the code Run-Time tring to fix any errors.
2. I will write function for simple statistics on the Library.

[ NOTE ]
1. I am using Galaxy Tab and QPython3 App.
2. All the above codes are available in the Download Section/Page under the project name.
3. The application codes, Functions, Menus and other parts of the Application are subject of changes. In case of changes I will mention that.
4. This is a simple personal Library application, so i did not use any validations on Data Entry.

:: Library Managment System ::

Part 1 Part 2 Part 3 Part 4
Part 5

To Download my Python code (.py) files Click-Here

Follow me on Twitter..

By: Ali Radwani

Python: Cooking App P-7

Learning : Python, Data-Base, SQlite
Subject: Writing a Cooking Application

RECIPES MENU: Delete Recipe To Delete a recipe we need to point on it, we will do this by it’s ID. So we can show all recipes by names, then we select the one we want to delete and enter it’s ID, the system will ask to confirm this action by typing (y,Y) then it we will call the delete function. In Delete function “def del_recipe()” we need to delete all the data regarding this ID form three DB Tables, recipes, recipes_steps, rec_ingredient and photo. Although we did not use the photo table and and we just create it for future use, but er will write its code.

Future Plan: In coming weeks we will convert this application “Cooking Application” to GUI “Graphical User Interface” application using tkinter library (Tkinter: is a Python binding to the Tk GUI toolkit) .

Coding: So to Delete a recipe we will show all Recipes and there ID’s sorted by it’s Name and ask the user to enter the ID of the Recipe he/she want to delete.

 # Code to Delete a Recipe

def del_recipe():
    print('\n ====== Delete a Recipe =====')

    # Start to list down all the Recipes Name.
    print("\n\n  List of ALL Recipes we have.")
    c.execute("select r_id,r_name from recipes where r_id > 0")
    for each_r_name in c.fetchall():
        print('   ID:',each_r_name[0], 'Name:',each_r_name[1])

    # Now we ask the user to Enter the Recipe ID. 
    rec_del = input('\n\n   Enter an Recipe ID to be Deleted: ')
    # Now we ask the user to Confirm Deleting Recipe.
    sure_remove = input('\n The Recipe will be DELETE and can''t be Rolled-Back.
Are you sure you want to Remove it [Y,N] ') if sure_remove in ['y','Y']: c.execute ("Delete from recipes_steps where r_id = {}".format(rec_del)) db_conn.commit() c.execute ("Delete from recipes where r_id = {}".format(rec_del)) db_conn.commit() c.execute ("Delete from rec_ingredient where r_id = {}".format(rec_del)) db_conn.commit() c.execute ("Delete from photo where r_id = {}".format(rec_del)) db_conn.commit() elif sure_remove in ['n','N']: # If the user decide not to delete and select N print('\n You select NOT to remove the Recipe.') else :# If the user enter anything else than Y or N print('\n You must select (Y or N).') input('\n .. One Recipe Removed .. Press any key .. ')

To Download my Python code (.py) files Click-Here

Follow me on Twitter..

By: Ali Radwani

Python: Machine Learning – Part 3

December 3, 2019 Leave a comment

Learning :Python and Machine Learning Part 3
Subject: Implementation and saving ML-Model

After creating a data-set and use it to train a ML model and make sure that it works fine and give a height accuracy predictions (Click here to read: Python and Machine Learning Part 2 ), we may or say we need to keep this model trained and re-use it on any actual data. In many real-life ML to training the model may take time with huge train data in image recognition or voice recognition models, so we need to keep the model trained even if we exit the application. To do this in sklearn we will use the “Model persistence” document page and use the joblib serialization.

First we need to import joblib , also import so to print out the file name and the path, we will use two functions in joblib (dump and load) in save_trained_model we will use the dump. Her is the code.

 # Function to save a trained ML-Model

  import joblib, os  # To Import  joblib and os
  def save_trained_model(model_name):
      print('\n  You select to save the trained ML model.')
      ml_name = input('  Enter a file name: ')
      joblib.dump(model_name, ml_name)
      print('\n  --> ML Model been saved.\n')
      print('   File Name is :',ml_name)  # To print-out the file name 
      print('   File Path is :',os.path.abspath(ml_name))  # To print-out the file path
      print('\n\n Do you want to save the ML trained Model? (Y,N): ' )
      if input('') in ['y','Y'] :

Now after we save our trained ML-Model we want to load it and use it in our ML program without training our machine. I will use the function new_test_data() from part 2 and pass the ML trained model to it. And to do this, first we need to load the trained ML-Mode. So let’s do it.

 # Function to load trained ML-Model
def load_ML_Model(ML_filename):
    the_trained_model= joblib.load(ML_filename)
    return the_trained_model

# we call the function in the main application code.
ML_model = load_ML_Model(ML_t_model_filename)

And now we will call our new_test_data() function and pass ML_model to see the prediction.

 # Function to load trained ML-Model

def new_test_data(ML_model):
    print('---------  START PREDICTION  for New Data Set ---------')
    print('\n   In this function a new data set will be generated, ')
    print('  and a trained ML-Model for "mouse on the coordinate plane" ')
    print('  will be loaded from the disk. So we will not train the Model.')
    #print('  So we will not train the Model. ')
    #print('  will use the IF loops.')
    new_data_size = 1000 
    new_data_range = 100
    print('\n\n  The new data range is {}, and the new data size is {}.'.format(new_data_range,new_data_size))
    # generate new data 
    new_test_data1= []
    for x in range (new_data_size):
    print('\n  This is the prediction for the New Data set..\n')
    # Do prediction using ML_model.
    prediction = ML_model.predict(new_test_data1)
    cot = 0
    # check the predictions accuracy .
    for i in range (len(prediction)) :
        if prediction[i] =='Up_r':
          if ((new_test_data1[i][0]) > 0 and (new_test_data1[i][1]) > 0) :
            cot = cot + 1
        elif  prediction[i] =='Up_l':
          if ((new_test_data1[i][0])  0) :
            cot = cot + 1
        elif  prediction[i] =='D_r':
          if ((new_test_data1[i][0]) > 0 and (new_test_data1[i][1]) < 0) :
            cot = cot + 1
        elif  prediction[i] =='D_l':
          if ((new_test_data1[i][0]) < 0 and (new_test_data1[i][1]) < 0) :
            cot = cot + 1
    print('\n  We count {} correct prediction out of {} Instances.'.format(cot,(new_data_size)))
    print('\n  The Accuracy is:',round((cot/len(prediction))*100,3),'%')


To Download my Python code (.py) files Click-Here

Follow me on Twitter..

By: Ali Radwani