0% found this document useful (0 votes)
15 views8 pages

Programs

ML programs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views8 pages

Programs

ML programs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

program1

December 22, 2023

Python Program to Print Hello world!


[1]: print('Hello, world!') #If you don't know this, consider dropping from life

Hello, world!
Python Program to Add Two Numbers
[2]: num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

The sum of 1.5 and 6.3 is 7.8


Add Two Numbers With User Input
[3]: # Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

The sum of 1 and 1 is 2.0


Python Program to Find the Square Root
[4]: num = 8
# To take the input from the user
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

The square root of 8.000 is 2.828


Python Program to Find the Square Root (For real or complex numbers)

1
[5]: import cmath
num = 1+2j
# To take input from the user
#num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.
↪real,num_sqrt.imag))

The square root of (1+2j) is 1.272+0.786j


Python Program to Calculate the Area of a Triangle
[7]: a = 5
b = 6
c = 7
# Uncomment below to take inputs from the user
# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

The area of the triangle is 14.70


Python Program to Solve Quadratic Equation
[8]: import cmath
a = 1
b = 5
c = 6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

The solution are (-3+0j) and (-2+0j)


Python Program to Swap Two Variables
[9]: x = 5
y = 10
# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

2
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

The value of x after swapping: 10


The value of y after swapping: 5
Python Program to Generate a Random Number
[10]: import random
print(random.randint(0,9))

6
Python Program to Convert Kilometers to Miles
[11]: kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))

100.00 kilometers is equal to 62.14 miles

1 EXPERIMENT 2
1.1 Arrays, lists - Slicing, reshaping, matrix operations,etc
[13]: import numpy as np

l=[1,2,3] #this is a list.

a=np.array(l) #now this is a numpy array


print('array a is: ',a)
print('the shape of numpy array a is : ',np.shape(a))

array a is: [1 2 3]
the shape of numpy array a is : (3,)
Combining numpy arrays
[14]: a=np.array([1,2,3,4])
b=np.array([5,6,7,8])
x=np.vstack((a,b))
y=np.hstack((a,b))

3
print('vertically stacked: ',x)
print('horizontally stacked: ',y)

vertically stacked: [[1 2 3 4]


[5 6 7 8]]
horizontally stacked: [1 2 3 4 5 6 7 8]
Boradcasting
[19]: a = np.array([17, 11, 19]) # 1x3 Dimension array
print(a)
b = 3
print(b)

y=a+b #here b is broadcasted into the shape of a


print('y is :',y)

[17 11 19]
3
y is : [20 14 22]
Slicing
[34]: a = np.array([[17, 11, 19],[20, 15, 8],[1, 12, 49],[42, 15, 78]]) #a's shape is␣
↪(4x3)

print('rows sliced\n',a[0:2]) #slicing in rows. Slicing from row 0 to row 1


print('columns sliced\n',a[:,0:2])

rows sliced
[[17 11 19]
[20 15 8]]
columns sliced
[[17 11]
[20 15]
[ 1 12]
[42 15]]
reshaping
[99]: a = np.array([[17, 11, 19],[20, 15, 8],[1, 12, 49],[42, 15, 78]]) #a's shape is␣
↪(4x3)

print(a.shape)
a=np.reshape(a,(3,4))
print(a.shape)

(4, 3)
(3, 4)

4
2 Linear regression
[103]: import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

def fit(X, y):


num_samples, num_features = X.shape # X shape [N, f] where N is the␣
↪samples and f is features here 2

weights = np.zeros(num_features) # W shape [f, 1]


bias = 0
n_iters=1000 #number of iterations
lr=0.01 #learning rate

for i in range(n_iters):
y_pred = np.dot(X, weights) + bias
dw = (1 / num_samples) * np.dot(X.T, y_pred - y) #derivative of Loss␣
↪with respect to weights w

db = (1 / num_samples) * np.sum(y_pred - y) #derivative of loss with␣


↪respect to bias

weights = weights - lr * dw #weights update


bias = bias - lr * db

return weights,bias

def predict(X):
return np.dot(X,weights) + bias

X, y = datasets.make_regression(n_samples=500, n_features=1, random_state=4)␣


↪#to create a random dataset of two features and one target

x_train,x_test,y_train,y_test=train_test_split(X,y)

weights,bias=fit(x_train,y_train)
print('weights are:\n',weights,'\n\nBias is :\n',bias)

predictions=predict(x_test)
loss=np.mean(np.abs(predictions-y_test)) #mean absolute error
print('\nMAE is ',loss)

plt.scatter(x_test,y_test,color='m')
plt.plot(x_test,predictions)

5
weights are:
[67.17516321]

Bias is :
0.00336403250300076

MAE is 0.008391426389049123

[103]: [<matplotlib.lines.Line2D at 0x212fb001d50>]

3 Logistic Regression
[138]: import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

def sigmoid(z):
return 1 / (1 + np.exp(-z))

6
def fit(X, y):
# weights initialization
m = np.zeros(X.shape[1])
num_iter=1000
lr=0.01

for i in range(num_iter):
z = np.dot(X, m)
y_pred = sigmoid(z)
gradient = np.dot(X.T, (y_pred - y)) / y.size
m -= lr * gradient

return m

def predict(X):
prdns=sigmoid(np.dot(X,weights)) >= 0.5
return (prdns).astype(int)

X, y = datasets.make_classification(n_samples=500,␣
↪n_features=1,n_informative=1,n_redundant=0,n_repeated=0,n_clusters_per_class=1,␣

↪n_classes=2,random_state=4)

x_train,x_test,y_train,y_test=train_test_split(X,y)

weights=fit(x_train,y_train)
print('weights are:\n',weights)

predictions=predict(x_test)
acc=np.mean(predictions==y_test)
print('\naccuracy is ',acc)

plt.scatter(x_test,y_test,color='blue')
plt.scatter(x_test,predictions,color='red')
x=np.linspace(min(x_test),max(x_test),125)
y=sigmoid(np.dot(x,weights))
plt.plot(x,y)

weights are:
[1.91348263]

accuracy is 0.984

[138]: [<matplotlib.lines.Line2D at 0x212fcea93f0>]

7
8

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy