Description

I would like to share and discuss about Engineering Subjects, Technical Seminars, Softwares Explantion and General Knowledge Discussions in this Blog.

Tuesday, 21 January 2025

MP MC Lab Codes (8086 Emulator, MASM/TASM and Keil Softwares)

MICRO PROCESSORS AND MICRO CONTROLLERS LAB 
DOS-BOX Commands (Double Click on DOS-BOX Icon)
Use the command mount d d:\8086 to mount your directory and switch to the respective drive (D:).
Open Notepad or use the edit hello.asm command to write your code and save it as hello.asm.
Use masm hello.asm; to assemble the code and generate the object file.
Use link hello.obj; to link the object file and create an executable (hello.exe).
Use debug hello.exe to run the program in Debug mode.
Type q to quit Debug when you're finished.
END START
END START

3. Implement Sorting an array of random 8-bit binary numbers. 
DATA SEGMENT
ORG 3000H
STR DB 0D2H,3EH,76H,12H,0E3H,44H,2AH,69H
LEN EQU ($-STR)
DATA ENDS
CODE SEGMENT
START:
    MOV AX, DATA
    MOV DS, AX
    MOV CL, LEN-1
UPP:
    MOV DL, CL
    LEA SI, STR
UP:
    MOV AL, [SI]
    CMP AL, [SI+1]
    JBE LI
    XCHG AL, [SI+1]
    XCHG [SI], AL
LI:
    INC SI
    DEC DL
    JNZ UP
    DEC CL
    JNZ UPP
    INT 03
CODE ENDS
END START

Drive Link : Software Link

8086 Emulator codes

Addition:

start:

MOV AX, 0X2C

MOV BX, 0X98

ADD AX, BX

INT 03


Subtraction:

start:

MOV AX, 0XCC

MOV BX, 0X98

SUB AX, BX

INT 03

 

Multiplication:

start:

MOV AX, 0X2C

MOV BX, 0X98

MUL BX

INT 03

 

Division:

start:

MOV AX, 0X2C

MOV BX, 0X98

DIV BX

INT 03

·         Mount the directory:

·         Create the assembly file:

·         Assemble the code:

·         Link the object file:

·         Run the program:

·         Use Debug commands:

Type t to trace: Perform single-step verification (execute one instruction at a time).

Type g to run: Execute the complete code without pausing.

Type u to verify opcodes: Check and validate the compiled opcodes of the code.

Type r to view the registers: Displays the current values of registers.

Type d ds: Address: Dump the memory contents starting at the specified segment and address.

·         Exit Debug:

8086 MASM Codes

1. Perform simple arithmetic operations.

Addition -1

ASSUME CS: CODE

CODE SEGMENT

ORG 2000H

START:

    MOV AL, 5

    MOV BL, 3

    ADD AL, BL

    INT 03

CODE ENDS

END START

Addition -2(Clear AX)

ASSUME CS: CODE

CODE SEGMENT

ORG 2000H

START:

    MOV AX, 0000

    MOV AL, 5

    MOV BL, 3

    ADD AL, BL

    INT 03

CODE ENDS

END START

Subtraction Code

 

ASSUME CS: CODE

CODE SEGMENT

ORG 2000H

START:

    MOV AX, 0000H

    MOV AL, 05H

    MOV BL, 03H

    SUB AL, BL

    INT 03H

CODE ENDS

END START

Multiplication

ASSUME CS: CODE

CODE SEGMENT

ORG 2000H

START:

    MOV AX, 0000H

    MOV AL, 05H

    MOV BL, 03H

    MUL BL

    INT 03H

CODE ENDS

END START

Division

ASSUME CS: CODE

CODE SEGMENT

ORG 2000H

START:

    MOV AX, 0000H

    MOV AL, 05H

    MOV BL, 03H

    DIV BL

    INT 03H

CODE ENDS

1. Perform simple arithmetic operations.

 ADDITION:

ASSUME CS:CODE, DS:DATA

DATA SEGMENT

ORG 3000H

NUM1 DB 0A7H,23H,67H,9CH,5DH,2EH,0ECH

ORG 4000H

NUM2 DB 7CH,0BAH,4FH,77H,3AH,0E6H,48H

LEN EQU ($-NUM2)

ORG 5000H

RES DB LEN+1 DUP(0)

 DATA ENDS

CODE SEGMENT

ORG 2000H

START:           MOV AX,DATA

MOV DS,AX

MOV SI,OFFSET NUM1

 MOV DI,OFFSET NUM2

 MOV BP,OFFSET RES

CLC

MOV CX,LEN

UP:      MOV AL,[SI]

MOV BL,[DI]

 ADC AL,BL

MOV DS:[BP],AL

INC SI

INC DI

INC BP

LOOP UP

LAHF

AND AH,01

MOV DS:[BP],AH

INT 03

 CODE ENDS

END START

 

SUBTRACTION:

ASSUME CS:CODE, DS:DATA

DATA SEGMENT

ORG 3000H

NUM1 DB 0A7H,23H,67H,9CH,5DH,2EH,0ECH ORG 4000H

NUM2 DB 7CH,0BAH,4FH,77H,3AH,0E6H,48H

LEN EQU ($-NUM2)

ORG 5000H

 

RES DB LEN+1 DUP(0)

DATA ENDS

CODE SEGMENT

ORG 2000H

START:           MOV AX,DATA

MOV DS,AX

MOV SI,OFFSET NUM1

MOV DI,OFFSET NUM2

MOV BP,OFFSET RES

 CLC

MOV CX,LEN

UP:      MOV AL,[SI]

MOV BL,[DI]

 SBB AL,BL

MOV DS:[BP],AL

INC SI

INC DI

INC BP

 LOOP UP

MOV AH,00

 JNC L1

INC AH

L1:       MOV DS:[BP],AH

INT 03

CODE ENDS

 END START

MULTIPLICATION:

ASSUME CS:SEG2,DS:SEG1

SEG1 SEGMENT       

ORG 5000H

N1 DW 45B3H

 ORG 6000H

N2 DW 0A599H

ORG 6500H

RES DW 02 DUP(0)

 SEG1 ENDS

SEG2 SEGMENT

 ORG 2000H

START: MOV AX,SEG1

 MOV DS,AX

LEA BX,N1

LEA SI,N2

MOV AX,[BX]

MOV CX,[SI]

MUL CX

LEA SI,RES

 MOV [SI],AX

 ADD SI,02

MOV [SI],DX

INT 03

SEG2 ENDS

 END START

DIVISION:

32BIT/16BIT UNSIGNED DIVISION:

ASSUME CS:PROG, DS:INFO

 INFO SEGMENT

ORG 3000H

DIVDEN DD 855D0100H

ORG 4000H

DIVSOR DW 411AH

ORG 5000H

RES DW 02 DUP(0)

INFO ENDS

PROG SEGMENT

ORG 2000H

START:           MOV AX,INFO

MOV DS,AX

MOV SI,OFFSET DIVDEN

 MOV DI,OFFSET DIVSOR

MOV BX,[DI]

MOV AX,[SI]

ADD SI,02

MOV DX,[SI]

 DIV BX

MOV SI,OFFSET

RES MOV [SI],AX

ADD SI,02

MOV [SI],DX

 INT 03

PROG ENDS

 END START

2. Construct program for Addition of an array of BCD numbers stored in packed form.

ASSUME CS:PROG,DS:INFO

INFO SEGMENT

ORG 3000H

 HOW DB 05H

ORG 3500H

 

NUMS DB 23H,45H,67H,56H,89H

ORG 5000H

RES DB 02 DUP(0)

 INFO ENDS

PROG SEGMENT

START: MOV AX,INFO

MOV DS,AX

MOV AH,00

 MOV CL,HOW-1

MOV SI,OFFSET NUMS

MOV AL,[SI]

CONTINUE:ADD AL,[SI+1]

DAA

JNC NOUPDATE

INC AH

NOUPDATE:INC SI

DEC CL

JNZ CONTINUE

 LEA DI,RES

 MOV [DI],AX

INT 03

PROG ENDS


Exp- 4 Produce the reverse of the given string.

ASSUME CS:CODE,DS:DATA,ES:DATA
DATA SEGMENT
ORG 4000H
STR1 DB "MICROPROCESSORS"
LEN EQU ($-STR1)
ORG 5000H
STR2 DB 20H DUP(00)
DATA ENDS

CODE SEGMENT
START:  MOV AX,DATA
MOV DS,AX
MOV ES,AX
LEA SI,STR1
MOV DI, OFFSET STR2
ADD DI,LEN
DEC DI
MOV CX,LEN

LI: CLD
LODSB
STD
STOSB
LOOP LI
INT 03

CODE ENDS
END START

Verification at 
-d ds: 4000
-d ds: 5000

Exp-5 Show the Deletion of a Character from a String.

ASSUME CS:CODE,DS:DATA,ES:EXTRA
DATA SEGMENT
ORG 3000H
MSG DB "MICROPROCESSORS"
LEN EQU ($-MSG)
DATA ENDS
EXTRA SEGMENT
ORG 4000H
NEW DB 20H DUP(00)
EXTRA ENDS

CODE SEGMENT
START:  
MOV AX,DATA
MOV DS,AX
MOV AX, EXTRA
MOV ES, AX
MOV CX, LEN
LEA SI, MSG
LEA DI, NEW
CLD
UP:
LODSB
CMP AL, 'P'
JNZ L1
JMP L2
L1:STOSB
L2:LOOP UP
INT 03

CODE ENDS
END START

Verification at

-D 076A:3000

-D 0A6B:4000



Monday, 10 July 2023

Python and Machine Learning Lab Programs

List of Experiments for Python and Machine Learning Lab using NVIDIA Jetson Nano Boards

 Part-A

1. Basic Calculator by using functions

2. Create the detail form of the students with Name, ID, Class, Branch, Hostel Room, contact, Remarks etc…

3. Write a program for ATM machine with fallowing options.

a. To maintain the balance 

b. Deposit the money

c. For Withdrawal, while withdrawal system need to ask the available notes, provide the customer to select required notes and display the balance after transaction

d. In addition, other options available in ATM.

4. Write a program for a scientific calculator using Numpy

5. Create a own library for different mathematical functions.

6. Create a data frame of the student details with Name, ID, Class, Branch, Hostel Room, contact, Remarks etc..

7. Write a python program by creating function of different plots using matplot library and plot the data by user option.

8. Access the webcam, click the image by using any keyboard input, and store the data in pc.

9. Access the microphone and record the voice and store in the pc.

10. Read the Titanic Data and Display the Same information using Pandas

11. Develop class with following criteria Class Name: Flower, Objects: Lilly, Rose, Hibiscus, Properties: price, color, smell Methods: get(), display()

12. Design a Python Program using filter(), map() and reduce() functions to find division of three, square of each element and sum of the squared elements for the following list 

lis=[3, 5, 6, 9, "Lendi", “Kiran”, 20, 21, 24]

Part-B

1. Sample Machine Learning Code between Ad Spending and Sales

2. Linear Regression :

            a. Linear Regression Python Code without Dataset

            b. Linear Regression Python Code with Weather Dataset

3. Logistic regression : 

a. Logistic regression Python Code without Dataset

            b. Logistic regression Python Code with Breast Cancer Dataset

4. Polynomial regression : 

a. Polynomial regression Python Code without Dataset

            b. Polynomial regression Python Code with Position Salaries Dataset

5. K-means clustering: 

a. K-means clustering Python Code without Dataset

            b. K-means clustering Python Code with Breast Cancer Dataset

6. Classification : Classify the hand written digits using ANN- MNIST dataset & Classification algorithm

 

Part-C

Tasks/Mini Project Implementations by the Students

 1. Linear regression: Predict the profit of a company/House price from a dataset using the concept of linear regression 

2. Logistic regression: Identify whether the patient has diabetes or not from diabetes dataset using Logistic regression 

3. Polynomial regression: Determine the quality of wine using wine dataset with the help of polynomial regression 

4. K-means clustering: Apply the concept of K-means clustering for image segmentation problem 

5. Decision Tree: Predict whether a person need a loan (or) Buy a car/not

6. Image Classification using CNN: Classify cats and dogs using CNN from the given dataset.  

 

Part-A

 

1. Basic Calculator by using functions

 

Code: 

def add(num1, num2):

    return num1 + num2

 def subtract(num1, num2):

    return num1 - num2

 def multiply(num1, num2):

    return num1 * num2

 def divide(num1, num2):

    return num1 / num2

print("Please select an operation:")

print("1. Add")

print("2. Subtract")

print("3. Multiply")

print("4. Divide")

print("5. Exit")

 

while True:

    choice = input("Enter your choice (1/2/3/4/5): ")

 

    if choice == '5':

        print("Goodbye!")

        break

 

    if choice in ('1', '2', '3', '4'):

        num1 = float(input("Enter first number: "))

        num2 = float(input("Enter second number: "))

 

        if choice == '1':

            print(num1, "+", num2, "=", add(num1, num2))

 

        elif choice == '2':

            print(num1, "-", num2, "=", subtract(num1, num2))

 

        elif choice == '3':

            print(num1, "*", num2, "=", multiply(num1, num2))

 

        elif choice == '4':

            print(num1, "/", num2, "=", divide(num1, num2))


    else:

        print("Invalid Input")1.py

Open with Anyfile No

 

2. Create the detail form of the students with Name ,ID ,Class ,Branch ,Hostel Room,contact, Remarks etc…

 

Code:


 import pandas as pd

data={
          "first_person":["Madhu",440,"A_sec","ECE",123456],
           "second_person":["Jyotshna",455,"A_sec","ECE",567890],
           "third_person":["Dharani",458,"A_sec","ECE",4567832]
          }

data1=pd.DataFrame(data,index=["NAME","ID","SECTION","BRANCH","MOBILE"])
#print(data1)
ch=int(input("Enter the choice:"))
if (ch==1):
print(data1.first_person)
elif (ch==2):
print(data1.second_person)
elif (ch==3):
print(data1.third_person)
elif(ch==4):
print(data1)

#GUI Based

import tkinter as tk

from tkinter import ttk

 

# create the main window

root = tk.Tk()

root.title("Student Details")

 

# create a frame for the form

form_frame = ttk.Frame(root, padding=20)

form_frame.grid()

 

# create labels and entry fields for the form

name_label = ttk.Label(form_frame, text="Name:")

name_label.grid(column=0, row=0, sticky=tk.W)

name_entry = ttk.Entry(form_frame)

name_entry.grid(column=1, row=0)

 

id_label = ttk.Label(form_frame, text="ID:")

id_label.grid(column=0, row=1, sticky=tk.W)

id_entry = ttk.Entry(form_frame)

id_entry.grid(column=1, row=1)

 

class_label = ttk.Label(form_frame, text="Class:")

class_label.grid(column=0, row=2, sticky=tk.W)

class_entry = ttk.Entry(form_frame)

class_entry.grid(column=1, row=2)

 

contact_label = ttk.Label(form_frame, text="Contact:")

contact_label.grid(column=0, row=3, sticky=tk.W)

contact_entry = ttk.Entry(form_frame)

contact_entry.grid(column=1, row=3)

 

remarks_label = ttk.Label(form_frame, text="Remarks:")

remarks_label.grid(column=0, row=4, sticky=tk.W)

remarks_entry = ttk.Entry(form_frame)

remarks_entry.grid(column=1, row=4)

 

# create a button to submit the form

submit_button = ttk.Button(form_frame, text="Submit")

submit_button.grid(column=1, row=5)

 

# function to handle form submission

def submit_form():

    # get the values from the entry fields

    name = name_entry.get()

    id = id_entry.get()

    class_ = class_entry.get()

    contact = contact_entry.get()

    remarks = remarks_entry.get()

    # do something with the values (e.g. store in a database)

    print(f"Name: {name}, ID: {id}, Class: {class_}, Contact: {contact}, Remarks: {remarks}")

    

    # clear the entry fields

    name_entry.delete(0, tk.END)

    id_entry.delete(0, tk.END)

    class_entry.delete(0, tk.END)

    contact_entry.delete(0, tk.END)

    remarks_entry.delete(0, tk.END)

    

    # give focus to the first field

    name_entry.focus()

 

# bind the button to the submit_form function

submit_button.config(command=submit_form)

 

# run the main loop

root.mainloop()

 

3. Write a program for ATM machine with fallowing options.

a. To maintain the balance 

b. Deposit the money

c. For Withdrawal, while withdrawal system need to ask the available notes, 

provide the customer to select required notes and display the balance after 

transaction

d. In addition, other options available in ATM.

 

Code

 

balance = 10000

 

# Function to display the available balance

def display_balance():

    print(f"Your current balance is {balance}.")

 

# Function to deposit money

def deposit_money():

    global balance

    amount = int(input("Enter the amount to deposit: "))

    balance += amount

    print(f"Deposit of {amount} successful.")

    display_balance()

 

# Function to withdraw money

def withdraw_money():

    global balance

    amount = int(input("Enter the amount to withdraw: "))

    if amount > balance:

        print("Insufficient balance.")

    else:

        # ask for the available notes

        print("Available notes: 100, 200, 500, 2000")

        notes = [int(x) for x in input("Enter the notes you require (separated by space): ").split()]

        total_amount = sum(notes)

        if total_amount != amount:

            print("Invalid notes provided.")

        else:

            balance -= amount

            print("Please collect your cash.")

            display_balance()

 

# Main program loop

while True:

    print("Welcome to the ATM.")

    print("1. Display balance")

    print("2. Deposit money")

    print("3. Withdraw money")

    print("4. Quit")

    choice = int(input("Enter your choice: "))

    

    if choice == 1:

        display_balance()

    elif choice == 2:

        deposit_money()

    elif choice == 3:

        withdraw_money()

    elif choice == 4:

        print("Thank you for using the ATM.")

        break

    else:

        print("Invalid choice.")

 

4. Write a program for a scientific calculator using Numpy

Code:

 

import numpy as np

 

# Display options to user

print("Please select an operation:")

print("1. Addition")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

print("5. Square root")

print("6. Exponentiation")

print("7. Logarithm")

print("8. Trigonometric functions")

print("9. Exit")

 

# Get user input

option = int(input())

 

# Process user input

while option != 9:

    if option == 1:

        # Addition

        num1 = float(input("Enter first number: "))

        num2 = float(input("Enter second number: "))

        result = np.add(num1, num2)

        print("Result:", result)

 

    elif option == 2:

        # Subtraction

        num1 = float(input("Enter first number: "))

        num2 = float(input("Enter second number: "))

        result = np.subtract(num1, num2)

        print("Result:", result)

 

    elif option == 3:

        # Multiplication

        num1 = float(input("Enter first number: "))

        num2 = float(input("Enter second number: "))

        result = np.multiply(num1, num2)

        print("Result:", result)

 

    elif option == 4:

        # Division

        num1 = float(input("Enter numerator: "))

        num2 = float(input("Enter denominator: "))

        result = np.divide(num1, num2)

        print("Result:", result)

 

    elif option == 5:

        # Square root

        num = float(input("Enter number: "))

        result = np.sqrt(num)

        print("Result:", result)

 

    elif option == 6:

        # Exponentiation

        num1 = float(input("Enter base: "))

        num2 = float(input("Enter exponent: "))

        result = np.power(num1, num2)

        print("Result:", result)

 

    elif option == 7:

        # Logarithm

        num = float(input("Enter number: "))

        result = np.log10(num)

        print("Result:", result)

 

    elif option == 8:

        # Trigonometric functions

        num = float(input("Enter angle in degrees: "))

        sin_result = np.sin(np.radians(num))

        cos_result = np.cos(np.radians(num))

        tan_result = np.tan(np.radians(num))

        print("Sine:", sin_result)

        print("Cosine:", cos_result)

        print("Tangent:", tan_result)

 

    else:

        # Invalid option

        print("Invalid option.")

 

    # Display options to user again

    print("\nPlease select an operation:")

    print("1. Addition")

    print("2. Subtraction")

    print("3. Multiplication")

    print("4. Division")

    print("5. Square root")

    print("6. Exponentiation")

    print("7. Logarithm")

    print("8. Trigonometric functions")

    print("9. Exit")

 

    # Get user input again

    option = int(input())

 

# Exit

print("Thank you for using our scientific calculator.")



5. Create a own library for different mathematical functions.

Code:

import mathlib

 

result = mathlib.add(2, 3)

print(result)

 

result = mathlib.multiply(4, 5)

print(result)

 

result = mathlib.divide(10, 2)

print(result)

 

result = mathlib.square_root(16)

print(result)

 

OWN LIBRARY:

# mathlib.py

 

import math

 

def add(x, y):

    """

    Adds two numbers and returns the result

    """

    return x + y

 

def subtract(x, y):

    """

    Subtracts two numbers and returns the result

    """

    return x - y

 

def multiply(x, y):

    """

    Multiplies two numbers and returns the result

    """

    return x * y

 

def divide(x, y):

    """

    Divides two numbers and returns the result

    """

    if y == 0:

        return "Error: Cannot divide by zero"

    else:

        return x / y

 

def square_root(x):

    """

    Returns the square root of a number

    """

    return math.sqrt(x)

 

def power(x, y):

    """

    Raises a number to a power and returns the result

    """

    return x ** y

 

x=int(input('enter the number:'))

y=int(input('enter the number:'))

print(f" the addition of {x} and {y} is :{add(x,y)}")

print(f" the subtraction of {x} and {y} is :{subtract(x, y)}")

print(f" the multiplication of {x} and {y} is :{multiply(x,y)}")

print(f" the divide of {x} and {y} is :{divide(x,y)}")

print(f" the square root of {x} is :{square_root(x)}")

print(f" the power of {x} and {y} is :{power(x, y)}")

 

6. Create a data frame of the student details with Name, ID, Class, Branch, Hostel Room, contact, Remarks etc…

Code:

 

import pandas as pd

 

# create a dictionary of student details

students = {

    'Name': ['John', 'Sarah', 'Tom', 'Emily'],

    'ID': [1001, 1002, 1003, 1004],

    'Class': ['A', 'B', 'A', 'B'],

    'Branch': ['Computer Science', 'Electronics', 'Mechanical', 'Civil'],

    'Hostel Room': ['A101', 'B202', 'A102', 'B201'],

    'Contact': ['123-456-7890', '234-567-8901', '345-678-9012', '456-789-0123'],

    'Remarks': ['Good student', 'Needs improvement', 'Excellent', 'Average']

}

 

# create a data frame from the dictionary

df = pd.DataFrame(students)

 

# print the data frame

print(df)

 

7. Write a python program by creating function of different plots using matplot library and plot the data by user option.

Code:

import matplotlib.pyplot as plt

import numpy as np

 

def line_plot(x, y):

    """

    Creates a line plot with the given x and y data.

    """

    plt.plot(x, y)

    plt.title("Line Plot")

    plt.xlabel("X-axis")

    plt.ylabel("Y-axis")

    plt.show()

 

def scatter_plot(x, y):

    """

    Creates a scatter plot with the given x and y data.

    """

    plt.scatter(x, y)

    plt.title("Scatter Plot")

    plt.xlabel("X-axis")

    plt.ylabel("Y-axis")

    plt.show()

 

def bar_plot(x, y):

    """

    Creates a bar plot with the given x and y data.

    """

    plt.bar(x, y)

    plt.title("Bar Plot")

    plt.xlabel("X-axis")

    plt.ylabel("Y-axis")

    plt.show()

 

# Prompt user to enter data for the plot

x = np.array(input("Enter x data (separated by spaces): ").split(), dtype=int)

y = np.array(input("Enter y data (separated by spaces): ").split(), dtype=int)

 

# Prompt user to choose which type of plot to create

print("Which type of plot would you like to create?")

print("1. Line plot")

print("2. Scatter plot")

print("3. Bar plot")

choice = int(input("Enter your choice (1, 2, or 3): "))

 

# Create the chosen type of plot

if choice == 1:

    line_plot(x, y)

elif choice == 2:

    scatter_plot(x, y)

elif choice == 3:

    bar_plot(x, y)

else:

    print("Invalid choice. Please enter 1, 2, or 3.")

 

8. Access the webcam, click the image by using any keyboard input, and store the data in pc.

Code:

 

import cv2

cap = cv2.VideoCapture(0)

print("To save picture click on 'S' key")

while True:

    ret, frame = cap.read()

    cv2.imshow("Webcam", frame)  

    key = cv2.waitKey(1) & 0xFF

    if key == ord('s'):

        File = "C:/Users/Lenovo/Desktop/python programs jetson nano/captured_image.jpg"

        cv2.imwrite(f"{File}", frame)

        print("Image captured Succuess fully...")

        print(f"Image is saved in the folder {File}")

        break

cap.release()  

cv2.destroyAllWindows()

 

9. Access the microphone and record the voice and store in the pc.

Code:

import pyaudio

import wave

 

FORMAT = pyaudio.paInt16

CHANNELS = 1

RATE = 44100

CHUNK = 1024

RECORD_SECONDS = int(input("Enter Record time(in seconds): "))

WAVE_OUTPUT_FILENAME = "C:/Users/Lenovo/Desktop/python programs jetson nano/2output.wav"

audio = pyaudio.PyAudio()

stream = audio.open(format=FORMAT,

                    channels=CHANNELS,

                    rate=RATE,

                    input=True,

                    frames_per_buffer=CHUNK)

 

print("Recording audio...")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):

    data = stream.read(CHUNK)

    frames.append(data)

 

print("Finished recording audio.")

 

stream.stop_stream()

stream.close()

 

audio.terminate()

 

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')

wf.setnchannels(CHANNELS)

wf.setsampwidth(audio.get_sample_size(FORMAT))

wf.setframerate(RATE)

wf.writeframes(b''.join(frames))

wf.close()

 

print(f"Saved audio to the file:  {WAVE_OUTPUT_FILENAME}.")

 

10. Read the Titanic Data and Display the Same information using Pandas

 

Code: 

import pandas as pd

data=pd.read_csv("titanic.csv")

print(data)

 

11. Develop class with following criteria Class Name: Flower, Objects: Lilly, Rose, Hibiscus, Properties: price, color, smell Methods: get(), display()

 

Code:

class fruits():

            def __init__(self, price, color, smell):

            self.price=price

            self.color=color

            self.smell=smell

            def get(self):

            self.price=float(input("Enter the Price of Fruit: "))

            self.color=input("Enter the Fruit Color Name:  ")

            self.smell=input("Enter the Fruit Color Name:  ")

            def disp(self):

            print("Fruit Price: ", self.price)

            print("Fruit Color: ", self.color)

            print("Fruit Smell: ", self.smell)

 Jasmin=fruits(0.00, "", "")

Lilly=fruits(0.00, "", "")

Rose=fruits(0.00, "", "")

Jasmin.get()

Lilly.get()

Rose.get()

 Jasmin.disp()

Lilly.disp()

Rose.disp()

 

12. Design a Python Program using filter(), map() and reduce() functions to find division of three, square of each element and sum of the squared elements for the following list 

lis=[3, 5, 6, 9, "Lendi", 20, “Kiran”, 21, 24]

 

Code:

from functools import reduce

 

def div(a):

    if(isinstance(a,(int,float)) and a%3==0):

        return a

def square(a):

    return a**2

def sum_sqr(a,b):

    return a+b

 

lis=[3, 5, 6, 9, "Lendi", 20, "Kiran", 21, 24]

lis=list(filter(div,lis))

squares=list(map(square,lis))

sum_squares=reduce(sum_sqr,squares)

 

print("list of elements divisible by 3: ",lis)

print("list of squares: ",squares) 

print("sum of sqauares: ",sum_squares)

 

 

Part-B

1. Sample Machine Learning Code between Ad Spending and Sales

 

Code: 

import numpy as np

import matplotlib.pyplot as plt

#x=np.array([0,1,2,3,4,5,6,7,8,9])

#y=np.array([1,3,2,5,7,8,8,9,10,12])

x=np.array([1,50,100,150,200,250])

#y=np.array([2.4,18.4,33,46,60,80])

y=np.array([90,190,300,450,570,750])

 

#x=np.array([95,85,80,70,60])

#y=np.array([85,95,70,65,70])

n=np.size(x)

m_x,m_y=np.mean(x),np.mean(y)

ss_xy=np.sum(y*x)-n*m_x*m_y

ss_xx=np.sum(x*x)-n*m_x*m_x

b0_1=ss_xy/ss_xx

b0_0=m_y-b0_1*m_x

y_pred=b0_0+b0_1*x

 

print(b0_0)

print(b0_1)

plt.scatter(x,y)

plt.xlabel('Ad spending')

plt.ylabel('Sales')

plt.show()

plt.figure

plt.scatter(x,y)

plt.plot(x,y_pred, color='r',marker='o')

plt.xlabel('Ad spending')

plt.ylabel('Sales')

from sklearn.metrics import r2_score

r2=r2_score(y, y_pred)

print(r2)

plt.show()

 

2. Linear Regression :

            a. Linear Regression Python Code without Dataset

 

Code:

# Importing required libraries

import numpy as np

import matplotlib.pyplot as plt

from sklearn.linear_model import LinearRegression

 

# Creating a dataset

# Input Feature

X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)

# Output Label

Y = np.array([2, 4, 5, 4, 5])

 

# Creating a Linear Regression model

model = LinearRegression()

 

# Training the model

model.fit(X, Y)

 

# Making predictions

X_new = np.array([6]).reshape(-1, 1)

Y_pred = model.predict(X_new)

 

print(f"Prediction for input 6 is: {Y_pred}")

 

# Plotting the regression line

plt.scatter(X, Y, color='red')

plt.plot(X, model.predict(X), color='blue')

plt.xlabel("Input Feature")

plt.ylabel("Output Label")

plt.show()

 

 

            b. Linear Regression Python Code with Weather Dataset

 

Code:

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

#import seaborn as seabornInstance

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

from sklearn import metrics

 

#step2: load data into program

#%matplotlib inline

#dataset = pd.read_csv(r'C:\Users\lenovo\Desktop\Weather.csv')

dataset = pd.read_csv('Weather.csv')

#dataset.shape

#dataset.describe()

dataset.plot(x='MinTemp', y='MaxTemp', style='o')

plt.title('MinTemp vs MaxTemp')

plt.xlabel('MinTemp')

plt.ylabel('MaxTemp')

plt.show()

#step3: data cleaning

#b = np.arange(10).reshape((-1,1))

X = dataset['MinTemp'].values.reshape(-1,1)

y = dataset['MaxTemp'].values.reshape(-1,1)

# step4: divide the data set into training data and testing data

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

 

# step 5: Apply the training data to algorithm

regressor = LinearRegression()

regressor.fit(X_train, y_train) #training the algorithm

#To retrieve the intercept:

print(regressor.intercept_) #c

#For retrieving the slope:

print(regressor.coef_) #m

#MaxTemp=0.92033997*MinTemp+10.66185201;

#step 6: Test the trained model on testing data

y_pred = regressor.predict(X_test) #y=mx+c

 

df = pd.DataFrame({'Actual': y_test.flatten(), 'Predicted': y_pred.flatten()})

print(df)

 

plt.scatter(X_test, y_test,  color='gray')

plt.plot(X_test, y_pred, color='red', linewidth=2)

plt.show()

# step7: Calculate the metrics

#print('slope=%f'%regressor.intercept_)

#print('intercept=%f'%regressor.coef_)

score=metrics.r2_score(y_test,y_pred)

print('accuracy=%f'%score)

 

 

3. Logistic regression : 

a. Logistic regression Python Code without Dataset

Code:

import numpy as np

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression

from sklearn.metrics import accuracy_score, confusion_matrix

 

# Generate random data for demonstration

# Replace this section with your own data loading and preprocessing steps

X = np.random.randn(100, 2# Input features

y = np.random.randint(0, 2, 100# Target variable

 

# Split the data into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

 

# Create a logistic regression model

model = LogisticRegression()

 

# Train the model

model.fit(X_train, y_train)

 

# Make predictions on the test set

y_pred = model.predict(X_test)

 

# Evaluate the model

accuracy = accuracy_score(y_test, y_pred)

print('Accuracy:', accuracy)

 

# Plot the confusion matrix

cm = confusion_matrix(y_test, y_pred)

fig, ax = plt.subplots()

im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)

ax.figure.colorbar(im, ax=ax)

ax.set(xticks=np.arange(cm.shape[1]),

       yticks=np.arange(cm.shape[0]),

       xticklabels=np.arange(2),

       yticklabels=np.arange(2),

       title='Confusion Matrix',

       xlabel='Predicted label',

       ylabel='True label')

plt.show()

 

 

            b. Logistic regression Python Code with Breast Cancer Dataset

Code:

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from sklearn.linear_model import LogisticRegression

from sklearn.model_selection import train_test_split

from sklearn import metrics

import seaborn as sns

 

data=pd.read_csv('breast_cancer.csv')

 

data['diagnosis'].replace('M',1,inplace=True)

data['diagnosis'].replace('B',0,inplace=True)

 

df=data.drop(columns=['id'])

 

X=df.drop(columns=['diagnosis'])

#X= df.drop(columns=['diagnosis','Unnamed 32'])

y=df['diagnosis']

 

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)

 

logreg=LogisticRegression()

logreg.fit(X_train,y_train)

 

y_pred=logreg.predict(X_test)

 

df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})

print(df)

 

conf_matrix=metrics.confusion_matrix(y_test,y_pred)

print(conf_matrix)

sns.heatmap(conf_matrix,annot=True)

 

plt.title('confusion matrix')

plt.ylabel('Actual label')

plt.xlabel('Predicted label')

print("Accuracy:", metrics.accuracy_score(y_test,y_pred))

 

 

4. Polynomial regression : 

a. Polynomial regression Python Code without Dataset.

Code:

import numpy as np

import matplotlib.pyplot as plt

from sklearn.preprocessing import PolynomialFeatures

from sklearn.linear_model import LinearRegression

from sklearn.metrics import mean_squared_error, r2_score

 

# Generate synthetic dataset

np.random.seed(0)

X = np.linspace(-3, 3, 100).reshape(-1, 1)

y = 0.5 * X**2 + X + np.random.normal(0, 1, X.shape)

 

# Create polynomial features

degree = 2

poly_features = PolynomialFeatures(degree=degree)

X_poly = poly_features.fit_transform(X)

 

# Train the polynomial regression model

model = LinearRegression()

model.fit(X_poly, y)

 

# Make predictions on the training set

y_pred = model.predict(X_poly)

 

# Evaluate the model

mse = mean_squared_error(y, y_pred)

r2 = r2_score(y, y_pred)

 

# Print evaluation metrics

print('Mean Squared Error:', mse)

print('R-squared:', r2)

 

# Plot the results

plt.scatter(X, y, label='Actual')

plt.plot(X, y_pred, color='red', label='Predicted')

plt.xlabel('X')

plt.ylabel('y')

plt.title('Polynomial Regression')

plt.legend()

plt.show()

 

 

            b. Polynomial regression Python Code with Position Salaries Dataset

Code:

 

import numpy as np

import matplotlib.pyplot as plt

import pandas as pd

 

dataset = pd.read_csv('/content/Position_Salaries.csv')

X = dataset.iloc[:, 1:2].values

y = dataset.iloc[:, 2].values

 

from sklearn.linear_model import LinearRegression

lin_reg = LinearRegression()

lin_reg.fit(X, y)

 

 

from sklearn.preprocessing import PolynomialFeatures

poly_reg = PolynomialFeatures(degree = 4)

X_poly = poly_reg.fit_transform(X)

poly_reg.fit(X_poly, y)

lin_reg_2 = LinearRegression()

lin_reg_2.fit(X_poly, y)

 

plt.scatter(X, y, color = 'red')

plt.plot(X, lin_reg.predict(X), color = 'blue')

plt.title('Truth or Bluff (Linear Regression)')

plt.xlabel('Position level')

plt.ylabel('Salary')

plt.show()

 

plt.scatter(X, y, color = 'red')

plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'blue')

plt.title('Truth or Bluff (Polynomial Regression)')

plt.xlabel('Position level')

plt.ylabel('Salary')

plt.show()

 

X_grid = np.arange(min(X), max(X), 0.1)

X_grid = X_grid.reshape((len(X_grid), 1))

plt.scatter(X, y, color = 'red')

plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')

plt.title('Truth or Bluff (Polynomial Regression)')

plt.xlabel('Position level')

plt.ylabel('Salary')

plt.show()

 

lin_reg.predict([[6.5]])

 

lin_reg_2.predict(poly_reg.fit_transform([[6.5]]))

 

5. K-means clustering: 

a. K-means clustering Python Code without Dataset

Code:

import numpy as np

import matplotlib.pyplot as plt

from sklearn.cluster import KMeans

#data for n_clusters=3

#x=np.array([12, 20, 28, 18, 29, 33, 24, 45, 45, 52, 51, 52, 55, 53, 55, 61, 64, 69, 72])

#y=np.array([39, 36, 30, 52, 54, 46, 55, 59, 63, 70, 66, 63, 58, 23, 14, 8, 19, 7, 24])

x=np.array([185,170,168,179,182,188])

y=np.array([72,56,60,68,72,77])

df = np.array(list(zip(x, y)))

plt.scatter(x,y)

kmeans=KMeans(n_clusters=2)

kmeans.fit(df)

centroids=kmeans.cluster_centers_

labels=kmeans.predict(df)

print(centroids)

plt.scatter(centroids[:,0],centroids[:,1],c='r')

plt.show()

 

            b. K-means clustering Python Code with Breast Cancer Dataset

Code:

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from sklearn.cluster import KMeans

from sklearn.model_selection import train_test_split

from sklearn import metrics

np.random.seed(200)

 

data=pd.read_csv('/content/drive/MyDrive/ML Experiments/ml/ml/breast_cancer.csv')

 

data['diagnosis'].replace('M',1,inplace=True)

data['diagnosis'].replace('B',0,inplace=True)

df=data.drop(columns=['id'])

df.head()

X=df.drop(columns=['diagnosis'])

y=df['diagnosis']

kmeans=KMeans(n_clusters=2)

kmeans.fit(X)

 

X=np.array(X)

correct = 0

print('1-indicates cancer, 0-indicates no cancer')

for i in range(len(X)):

    predict_me = np.array(X[i].astype(float))

    predict_me = predict_me.reshape(-1, len(predict_me))

    prediction = kmeans.predict(predict_me)

    print('patient{},pred={},actual={}'.format(i,prediction[0],y[i]))

    if prediction[0] == y[i]:

        correct += 1

print('Prediction Accuracy')

print(correct/len(X))

 

6. Classification : Classify the hand written digits using ANN- MNIST dataset & Classification algorithm

 

Code:

#importing libraries

import numpy as np

import matplotlib.pyplot as plt

from keras.layers import Dense, Flatten

from keras.models import Sequential

from keras.utils import to_categorical

from keras.datasets import mnist

 

# Load MNIST handwritten digit data

(X_train, y_train), (X_test, y_test) = mnist.load_data()

 

print(X_train.shape)

print(X_test.shape)

print(y_train.shape)

print(y_test.shape)

 

import matplotlib.pyplot as plt

plt.imshow(X_test[25])

 

#obtain input image row and column lenghts

input_img_row=X_train[0].shape[0]

input_img_col=X_train[0].shape[1]

print(input_img_row)

print(input_img_col)

 

# Display some images

fig, axes = plt.subplots(ncols=5, sharex=True,

       sharey=False, figsize=(10, 4))

for i in range(5):

  axes[i].set_title(y_train[i])

  axes[i].imshow(X_train[i], cmap='gray')

  axes[i].get_xaxis().set_visible(False)

  axes[i].get_yaxis().set_visible(False)

plt.show()

 

# Convert y_train into one-hot format

temp = []

for i in range(len(y_train)):

    temp.append(to_categorical(y_train[i], num_classes=10))

 

y_train = np.array(temp)

 

# Convert y_test into one-hot format

temp = []

for i in range(len(y_test)):

    temp.append(to_categorical(y_test[i], num_classes=10))

 

y_test = np.array(temp)

 

# Display some images

fig, axes = plt.subplots(ncols=5, sharex=True,

       sharey=False, figsize=(10, 4))

for i in range(5):

  axes[i].set_title(y_train[i])

  axes[i].imshow(X_train[i], cmap='gray')

  axes[i].get_xaxis().set_visible(False)

  axes[i].get_yaxis().set_visible(False)

plt.show()

 

 

import numpy as np

import cv2

from tensorflow import keras

from tensorflow.keras import layers

from tensorflow.keras.models import load_model

 

model = keras.Sequential(

    [

 

    layers.Flatten(input_shape=(28,28)),

        layers.Dense(5, activation='sigmoid'),

        layers.Dense(10, activation='softmax'),

    ]

)

 

model.summary()

 

 

 

 

model.compile(loss='categorical_crossentropy',

        optimizer='adam',

        metrics=['acc'])

 

# Train the Neural Network model

train = model.fit(X_train, y_train, epochs=5, validation_data=(X_test,y_test))

 

 

 

# Making predictions using our trained model

predictions = model.predict(X_test)

predictions = np.argmax(predictions, axis=1)

 

print(predictions)

 

# Display some predictions on test data

fig, axes = plt.subplots(ncols=10, sharex=False,

       sharey=True, figsize=(20, 4))

for i in range(10):

  axes[i].set_title(predictions[i])

  axes[i].imshow(X_test[i], cmap='gray')

  axes[i].get_xaxis().set_visible(False)

  axes[i].get_yaxis().set_visible(False)

plt.show()

 

score=model.evaluate(X_test, y_test, verbose=0)

print('Test loss:',score[0])

print('Test accuracy:',score[1])

 

# Commented out IPython magic to ensure Python compatibility.

import pandas as pd

import matplotlib.pyplot as plt

# %matplotlib inline

 

pd.DataFrame(train.history).plot()

plt.show()

 

# list all data in history

print(train.history.keys())

# summarize history for accuracy

plt.plot(train.history['acc'])

plt.plot(train.history['val_acc'])

plt.title('model accuracy')

plt.ylabel('accuracy')

plt.xlabel('epoch')

plt.legend(['train', 'test'], loc='upper left')

plt.show()

# summarize history for loss

plt.plot(train.history['loss'])

plt.plot(train.history['val_loss'])

plt.title('model loss')

plt.ylabel('loss')

plt.xlabel('epoch')

plt.legend(['train', 'test'], loc='upper left')

plt.show()

 

model.save("ann_model1")

from keras.models import load_model

loaded_model=load_model("ann_model1")

score=loaded_model.evaluate(X_test, y_test, verbose=0)

print('Test loss:',score[0])

print('Test accuracy:',score[1])

 

import numpy as np

input_image1=X_test[30]

input_image1=input_image1.reshape(1,28,28,1)

predict_x=loaded_model.predict(input_image1)

classes_x=np.argmax(predict_x,axis=1)

classes_x

#results=str(loaded_model.predict_classes(input_image1,batch_size=1,verbose=0))

#results

 

#results

import matplotlib.pyplot as plt

plt.show()

plt.imshow(X_test[25])