Supervised Learning
Supervised learning is a machine learning technique where we train a model on a labelled dataset. Our model learns from seen results taken from the training set and uses it to predict the outcomes of the test set.
import os import numpy as np import pandas as pd from sklearn import linear_model, preprocessing, model_selection from sklearn.neighbors import KNeighborsClassifier data = pd.read_csv( 'https://desktop/supervised-learning/prash.csv') # Data Pre-processing proc = preprocessing.LabelEncoder() sepal_length = proc.fit_transform(list(data["sepal_length"])) sepal_width = proc.fit_transform(list(data["sepal_width"])) petal_length = proc.fit_transform(list(data["petal_length"])) petal_width = proc.fit_transform(list(data["petal_width"])) variety = proc.fit_transform(list(data["species"])) # Prediction predict = "species" x = list(zip(sepal_length, sepal_width, petal_length, petal_width)) y = list(variety) var = ['Setosa', 'Virginica', 'Versicolor'] best = 0 worst = 100 for i in range(100): x_train, x_test, y_train, y_test = model_selection.train_test_split( x, y, test_size=0.9) model = KNeighborsClassifier(n_neighbors=5) model.fit(x_train, y_train) accuracy = model.score(x_test, y_test) if accuracy > best: best = accuracy elif accuracy < worst: worst = accuracy prediction = model.predict(x_test) print(f"Prediction:\t{var[prediction[i]].ljust(10)}\tActual: {var[y_test[i]].ljust(10)}\tAccuracy: {str(round(accuracy*100, 2)).ljust(5)} % \t Data: {x_test[i]}") print(f"\nHighest Accuracy: {round((100*best), 2)}%") print(f"\nLowest Accuracy: {round((100*worst), 2)}%")
Talk to Expert Submit Assignment
Template
import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('positional', metavar='str', help='A positional argument') parser.add_argument('-a', '--arg', help='A named string argument', metavar='str', type=str, default='') parser.add_argument('-i', '--int', help='A named integer argument', metavar='int', type=int, default=0) parser.add_argument('-f', '--file', help='A readable file', metavar='FILE', type=argparse.FileType('r'), default=None) parser.add_argument('-o', '--on', help='A boolean flag', action='store_true') return parser.parse_args() # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() str_arg = args.arg int_arg = args.int file_arg = args.file flag_arg = args.on pos_arg = args.positional print(f'str_arg = "{str_arg}"') print(f'int_arg = "{int_arg}"') print('file_arg = "{}"'.format(file_arg.name if file_arg else '')) print(f'flag_arg = "{flag_arg}"') print(f'positional = "{pos_arg}"') # -------------------------------------------------- if __name__ == '__main__': main()
Talk to Expert Submit Assignment
Sudoku Solver
I will be following Backtracking Algorithm to solve this problem.
The algorithm works something like this:
- Pick empty box.
- Try all numbers.
- Find one that works.
- Backtrack when the sudoku rules are broken.
- Repeat the above steps until all the boxes are filled up.
b = [ [7,8,0,4,0,0,1,2,0], [6,0,0,0,7,5,0,0,9], [0,0,0,6,0,1,0,7,8], [0,0,7,0,4,0,2,6,0], [0,0,1,0,5,0,9,3,0], [9,0,4,0,6,0,0,0,5], [0,7,0,3,0,0,0,1,2], [1,2,0,0,0,7,4,0,0], [0,4,9,2,0,6,0,0,7] ] def solve(b): find = find_empty(b) # Check empty box if not find: return True # Final state of the board when every box is filled else: row, col = find for i in range(1,10): if valid(b, i, (row, col)): b[row][col] = i # Place the number in the board if its valid if solve(b): return True # Continue from that board state onwards b[row][col] = 0 return False def valid(b, num, pos): for i in range(len(b[0])): # Check row if b[pos[0]][i] == num and pos[1] != i: # Check element in row if its equal to the number added and if its the current position being added to then ignore it return False for i in range(len(b)): # Check column if b[i][pos[1]] == num and pos[0] != i: # Check element column-wise if it equals the number added and its not the position that the new number was just added into return False box_x = pos[1] // 3 # Check 3x3 box box_y = pos[0] // 3 for i in range(box_y*3, box_y*3 + 3): # Loop through the 3x3 boxes for j in range(box_x * 3, box_x*3 + 3): if b[i][j] == num and (i,j) != pos: # Check if same number exits in the 3x3 box and (i, j) was the position the new number was just added to return False return True def print_board(b): for i in range(len(b)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - ") # Separate sections of the board row-wise (Every 3x3 box) for j in range(len(b[0])): if j % 3 == 0 and j != 0: print(" | ", end="") # Separate sections of the board column-wise if j == 8: print(b[i][j]) else: print(str(b[i][j]) + " ", end="") def find_empty(b): for i in range(len(b)): for j in range(len(b[0])): if b[i][j] == 0: # Check if there is a 0 in each position of the box return (i, j) # Return the row and column return None print_board(b) print(" ") solve(b) print_board(b)
Talk to Expert Submit Assignment
Binary Search in Python (Recursive and Iterative)
Searching for an element’s presence in a list is usually done using linear search and binary search. Linear search is time-consuming and memory expensive but is the simplest way to search for an element. On the other hand, Binary search is effective mainly due to the reduction of list dimension with each recursive function call or iteration. A practical implementation of binary search is autocompletion.
Talk to Expert Submit Assignment
Acronyms Using Python
An acronym is a short form of a word created by long words or phrases such as NLP for natural language processing. In this article, I will walk you through how to write a program to create acronyms using Python.
To create acronyms using Python, you need to write a python program that generates a short form of a word from a given sentence. You can do this by splitting and indexing to get the first word and then combine it. Let’s see how to create an acronym using Python:
user_input = str(input("Enter a Phrase: ")) text = user_input.split() a = " " for i in text: a = a+str(i[0]).upper() print(a)
Talk to Expert Submit Assignment
Alarm Clock with Python
Before writing the program you should know that you also need an alarm tone which will ring at the time of the alarm. So you can download an alarm tune from here. Now as we are ready with the libraries and the alarm song, let’s see how to write a program to create an alarm clock with Python:
from datetime import datetime from playsound import playsound alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n") alarm_hour=alarm_time[0:2] alarm_minute=alarm_time[3:5] alarm_seconds=alarm_time[6:8] alarm_period = alarm_time[9:11].upper() print("Setting up alarm..") while True: now = datetime.now() current_hour = now.strftime("%I") current_minute = now.strftime("%M") current_seconds = now.strftime("%S") current_period = now.strftime("%p") if(alarm_period==current_period): if(alarm_hour==current_hour): if(alarm_minute==current_minute): if(alarm_seconds==current_seconds): print("Wake Up!") playsound('audio.mp3') break
Talk to Expert Submit Assignment
Python Program to Generate Password
To write a Python program to create a password, declare a string of numbers + uppercase + lowercase + special characters. Take a random sample of the string of a length given by the user:
import random passlen = int(input("enter the length of password")) s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?" p = "".join(random.sample(s,passlen )) print(p)
Talk to Expert Submit Assignment
Hangman Game in Python
The objective of our project is to implement the hangman game using Python. It doesn’t require any specific modules other than random and time. Python loops and functions are enough to build this game here.
import random import time # Initial Steps to invite in the game: print("\nWelcome to Hangman game by DataFlair\n") name = input("Enter your name: ") print("Hello " + name + "! Best of Luck!") time.sleep(2) print("The game is about to start!\n Let's play Hangman!") time.sleep(3)
Talk to Expert Submit Assignment
Get Live Weather Desktop Notifications Using Python
We know weather updates are how much important in our day-to-day life. So, We are introducing the logic and script with some easiest way to understand for everyone. Let’s see a simple Python script to show the live update for Weather information.
import requests from bs4 import BeautifulSoup from win10toast import ToastNotifier
Step 2: Create an object of ToastNotifier class.
n = ToastNotifier()
Step 3: Define a function for getting data from the given url.
def getdata(url): r = requests.get(url) return r.text
Step 4: Now pass the URL into the getdata function and Convert that data into HTML code.
htmldata = getdata("https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/") soup = BeautifulSoup(htmldata, 'html.parser') print(soup.prettify())
Talk to Expert Submit Assignment
Python | Simple GUI calculator using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
# Python program to create a simple GUI # calculator using Tkinter # import everything from tkinter module from tkinter import * # globally declare the expression variable expression = "" # Function to update expression # in the text entry box def press(num): # point out the global expression variable global expression # concatenation of string expression = expression + str(num) # update the expression by using set method equation.set(expression) # Function to evaluate the final expression def equalpress(): # Try and except statement is used # for handling the errors like zero # division error etc. # Put that code inside the try block # which may generate the error try: global expression # eval function evaluate the expression # and str function convert the result # into string total = str(eval(expression)) equation.set(total) # initialize the expression variable # by empty string expression = "" # if error is generate then handle # by the except block except: equation.set(" error ") expression = "" # Function to clear the contents # of text entry box def clear(): global expression expression = "" equation.set("") # Driver code if __name__ == "__main__": # create a GUI window gui = Tk() # set the background colour of GUI window gui.configure(background="light green") # set the title of GUI window gui.title("Simple Calculator") # set the configuration of GUI window gui.geometry("270x150") # StringVar() is the variable class # we create an instance of this class equation = StringVar() # create the text entry box for # showing the expression . expression_field = Entry(gui, textvariable=equation) # grid method is used for placing # the widgets at respective positions # in table like structure . expression_field.grid(columnspan=4, ipadx=70) # create a Buttons and place at a particular # location inside the root window . # when user press the button, the command or # function affiliated to that button is executed . button1 = Button(gui, text=' 1 ', fg='black', bg='red', command=lambda: press(1), height=1, width=7) button1.grid(row=2, column=0) button2 = Button(gui, text=' 2 ', fg='black', bg='red', command=lambda: press(2), height=1, width=7) button2.grid(row=2, column=1) button3 = Button(gui, text=' 3 ', fg='black', bg='red', command=lambda: press(3), height=1, width=7) button3.grid(row=2, column=2) button4 = Button(gui, text=' 4 ', fg='black', bg='red', command=lambda: press(4), height=1, width=7) button4.grid(row=3, column=0) button5 = Button(gui, text=' 5 ', fg='black', bg='red', command=lambda: press(5), height=1, width=7) button5.grid(row=3, column=1) button6 = Button(gui, text=' 6 ', fg='black', bg='red', command=lambda: press(6), height=1, width=7) button6.grid(row=3, column=2) button7 = Button(gui, text=' 7 ', fg='black', bg='red', command=lambda: press(7), height=1, width=7) button7.grid(row=4, column=0) button8 = Button(gui, text=' 8 ', fg='black', bg='red', command=lambda: press(8), height=1, width=7) button8.grid(row=4, column=1) button9 = Button(gui, text=' 9 ', fg='black', bg='red', command=lambda: press(9), height=1, width=7) button9.grid(row=4, column=2) button0 = Button(gui, text=' 0 ', fg='black', bg='red', command=lambda: press(0), height=1, width=7) button0.grid(row=5, column=0) plus = Button(gui, text=' + ', fg='black', bg='red', command=lambda: press("+"), height=1, width=7) plus.grid(row=2, column=3) minus = Button(gui, text=' - ', fg='black', bg='red', command=lambda: press("-"), height=1, width=7) minus.grid(row=3, column=3) multiply = Button(gui, text=' * ', fg='black', bg='red', command=lambda: press("*"), height=1, width=7) multiply.grid(row=4, column=3) divide = Button(gui, text=' / ', fg='black', bg='red', command=lambda: press("/"), height=1, width=7) divide.grid(row=5, column=3) equal = Button(gui, text=' = ', fg='black', bg='red', command=equalpress, height=1, width=7) equal.grid(row=5, column=2) clear = Button(gui, text='Clear', fg='black', bg='red', command=clear, height=1, width=7) clear.grid(row=5, column='1') Decimal= Button(gui, text='.', fg='black', bg='red', command=lambda: press('.'), height=1, width=7) Decimal.grid(row=6, column=0) # start the GUI gui.mainloop()