ml lab
ml lab
Program:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def kernel(point, xmat, k):
m,n = np.shape(xmat)
weights = np.mat(np1.eye((m)))
for j in range(m):
diff = point - X[j]
weights[j,j] = np.exp(diff*diff.T/(-2.0*k**2))
return weights
def localWeight(point, xmat, ymat, k):
wei = kernel(point,xmat,k)
W = (X.T*(wei*X)).I*(X.T*(wei*ymat.T))
return W
def localWeightRegression(xmat, ymat, k):
m,n = np.shape(xmat)
ypred = np.zeros(m)
for i in range(m):
ypred[i] = xmat[i]*localWeight(xmat[i],xmat,ymat,k)
return ypred
# load data points
data = pd.read_csv('10-dataset.csv')
bill = np.array(data.total_bill)
tip = np.array(data.tip)
#preparing and add 1 in bill
mbill = np.mat(bill)
mtip = np.mat(tip)
m= np.shape(mbill)[1]
one = np.mat(np1.ones(m))
X = np.hstack((one.T,mbill.T))
#set k here
ypred = localWeightRegression(X,mtip,0.5)
SortIndex = X[:,1].argsort(0)
xsort = X[SortIndex][:,0]
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(bill,tip, color='green')
ax.plot(xsort[:,1],ypred[SortIndex], color = 'red', linewidth=5)
plt.xlabel('Total bill')
plt.ylabel('Tip')
plt.show();
2. Write a Python Program to Generate a Random Number.
import random
n = random.randint(0,50)
print(n)
Output:
40
import random
n = random.randint(100, 200)
print(n)
Output:
143
data = pd.read_csv('/content/Breast_cancer_data.csv')
data.head()
data.isna().sum()
data.describe()
data.info()
corr = data.corr()
fig = plt.figure(figsize=(15,12))
a = sns.heatmap(corr, cmap='Oranges')
a.set_title("Data Correlation")
y = data["diagnosis"].values
X=data.drop(["diagnosis"],axis=1)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,test_size = 0.3,random_state=1)
svc_diag = SVC(C=10,kernel='linear')
predicted=svc_diag.predict(X_test)
acc_svc=accuracy_score(y_test,predicted)
print('Accuracy Score of Linear Model: ',acc_svc)
svc_diag=SVC(C=10,kernel='rbf',gamma=2)
svc_diag.fit(X_train,y_train)
predicted=svc_diag.predict(X_test)
acc_svc=accuracy_score(y_test,predicted)
print('Accuracy Score of Gaussian Model: ',acc_svc)
Output:
Output:
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output
Output
371 is an Armstrong number
11.Creating and Visualizing a Random Forest Classification Model in Machine
Learning Using Python
Problem Statement: Use Machine Learning to predict cases of breast cancer using
patient treatment history and health data
Let us build the classification model with the help of a random forest algorithm.
Step 4: Import the random forest classifier function from sklearn ensemble
module. Build the random forest classifier model with the help of the random
forest classifier function
Output:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no
14.Calender
1. import calendar
2. And then apply the syntax
3. (calendar.month(yy,mm))
1. import calendar
2. # Enter the month and year
3. yy = int(input("Enter year: "))
4. mm = int(input("Enter month: "))
5.
6. # display the calendar
7. print(calendar.month(yy,mm))
Output:
15.Gradient Decent
# Importing Libraries
import numpy as np
import matplotlib.pyplot as plt
def mean_squared_error(y_true, y_predicted):
# Making predictions
y_predicted = (current_weight * x) + current_bias
if __name__=="__main__":
main()
Output:
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Output:
The sum is 136
Output
Enter N for N x N matrix : 3
Enter the element ::>
10
10
10
20
20
20
30
30
30
[[10, 10, 10], [20, 20, 20], [30, 30, 30]]
Display Array In Matrix Form
10 10 10
20 20 20
30 30 30
Enter N for N x N matrix : 3
Enter the element ::>
100
100
100
200
200
200
300
300
300
[[100, 100, 100], [200, 200, 200], [300, 300, 300]]
Display Array In Matrix Form
100 100 100
200 200 200
300 300 300
Resultant Matrix is ::> [110, 110, 110]
[220, 220, 220]
[330, 330, 330]
19.Write a python code for Multiple linear regression algorithm.
import numpy as np
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def generate_dataset(n):
x = []
y = []
random_x1 = np.random.rand()
random_x2 = np.random.rand()
for i in range(n):
x1 = i
x2 = i/2 + np.random.rand()*n
x.append([1, x1, x2])
y.append(random_x1 * x1 + random_x2 * x2 + 1)
return np.array(x), np.array(y)
x, y = generate_dataset(200)
mpl.rcParams['legend.fontsize'] = 12
fig = plt.figure()
ax = fig.add_subplot(projection ='3d')
ax.scatter(x[:, 1], x[:, 2], y, label ='y', s = 5)
ax.legend()
ax.view_init(45, 0)
plt.show()
Output: