0% found this document useful (0 votes)
26 views51 pages

ML Lab

Machine learning

Uploaded by

Piyush Sahu
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)
26 views51 pages

ML Lab

Machine learning

Uploaded by

Piyush Sahu
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/ 51

GOVERNMENT ENGINEERING COLLEGE

BILASPUR (C.G)

Department of Computer Science Engineering


2022-2023
MACHINE LEARNING LAB
(ML)
D022721(022)

Submitted to: Submitted by:


Prof. Prince Sahu Arwaz Khan
300702219010
7th Semester, CSE
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB
D022721 (022)

INDEX
SUBJECT: MACHINE LEARNING LAB

Lab Lab Content Page Date of Remarks


Id No. Experiment
1 Write programs to understand the use of Matplotlib 1-5 19-09-2022
for Simple Interactive Chart, Set the Properties of the
Plot, matplotlib and NumPy.

2 Write programs to understand the use of Matplotlib 6-10 26-09-2022


for working with multiple figures and Axes,
Adding Text, adding a Grid and Adding a legend.

3 Write a program in Python to implement Dataset 11-14 10-10-2022


Normalization for wine quality dataset.
Data Source: -
(https://www.kaggle.com/datasets/yasserh/wine-
quality-dataset).

4 Write a program in Python to implement Linear 15-18 17-10-2022


Regression for house price prediction.
Data Source: -
(https://forge.scilab.org/index.php/p/rdatase
t/source/file/master/csv/MASS/Boston).

5 Write a program in Python to implement 19-22 07-11-2022


Polynomial Regression for employee salary
prediction.
Data Source: -
(https://www.kaggle.com/datasets/kagg le/sf-
salaries).

6 Write a program in Python to implement K Nearest 23-28 14-11-2022


Neighbour classifier for diabetes classification.
Data Source: -
(https://www.kaggle.com/uciml/pimaindians-
diabetes-database/data).
7 Write a Python code to implement the feature 29-30 05-12-2022
selection technique using Correlation Matrix.
Data Source: -
(https://www.kaggle.com/datasets/imakash
3011/rental-bike-sharing)

8 Write a Python code to predict if a person would 31-37


buy life insurance based on his age using Logistic
Regression.
Data
Source:(https://www.kaggle.com/datasets/sharathc
handra4545/insurance-data)

9 Write a program in Python to implement Support 38-43


Vector Machine for diabetes classification.
Data
Source:(https://www.kaggle.com/uciml/pimaindian
s-diabetes-database/data).

10 Demonstrate the application of Artificial Neural 44-48


Network using Python.

(Prof In-charge)

Prof. Prince Sahu


9
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 1
Aim:
Write programs to understand the use of Matplotlib for Simple Interactive Chart,
Set the Properties of the Plot, Matplotlib and NumPy.

Code and Output:


Code:

import matplotlib.pyplot as plt


import numpy as np
import pandas as pd

#Plot size and 1st plot

fig_size = plt.rcParams["figure.figsize"]
print ("Current size:", fig_size)

# set figure width to 10 and height to 7


fig_size[0] = 5
fig_size[1] = 5
plt.rcParams["figure.figsize"] = fig_size
print ("Current size:", fig_size)

x = [1, 2, 3, 4, 5]
y = [25, 32, 34, 20, 25]
# plot
plt.plot(x, y)

Output:

1|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:

#Change color, line style and markers

x = [1, 2, 3, 4, 5]
y = [25, 32, 34, 20, 25]
plt.plot(x, y, color='green' , marker='o', markersize=20, linestyle='--', linewidth=4)

Output:

2|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:

# Scatter plot
# specifying the type of marker (dots) and its sizes
plt.scatter(x, y, marker='o')

Output:

3|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
#Bar plot
# specifying the bar colors
plt.bar(x, y, color='cyan')

Output:

Code:
#piechart
days = [1,2,3,4,5]
Enfield =[50,40,70,80,20]
Honda = [80,20,20,50,60]
Yahama =[70,20,60,40,60]
KTM = [80,20,20,50,60]
slices = [8,5,5,6]
activities = ['BMW','AUDI','TATA','MAHINDRA']
cols = ['c','g','y','b']
plt.pie(slices,
labels=activities,
colors=cols,
startangle=90,
shadow= True,

4|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('Car details in Pie Plot')

Output:

5|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 2
Aim:
Write programs to understand the use of Matplotlib for Working with Multiple
Figures and Axes, Adding Text, Adding a Grid and Adding a Legend.

Code and Output:


Code:
#Combine several plots in one
x = [1, 2, 3, 4, 5]
y = [25, 32, 34, 20, 25]
plt.plot(x, y, color='blue', lw=4, alpha=0.5)
plt.scatter(x, y, marker='o', s=400, color='red',alpha=0.5)
plt.bar(x, y, color='green',alpha=0.5)

Output:

6|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:

x = [1, 2, 3, 4, 5]
y = [25, 32, 34, 20, 25]
plt.plot(x, y)
# here we modify the axes, specifying min and max for x and y axes.
plt.axis(xmin=-1, xmax=10, ymin=0, ymax=40)

Output:

Code:
plt.plot(x, y)
plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)
plt.xticks(np.arange(0,13,1))

Output:

7|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

8|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
# Add grid and legend
plt.plot(x, y)
plt.grid(True)

Output:

Code:
plt.plot(x, y,label='Nice Blue Line')
plt.axis(xmin=-1, xmax=12, ymin=0, ymax=40)
plt.grid(True)
plt.legend(loc='upper right',prop={'size':12})

Output:

9|Page
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
x = np.arange(0, 10, 0.1)
y = np.sin(x)

plt.plot(x,y)

plt.text(3.0, 0.9, 'Sine wave', fontsize = 23)

plt.xlabel('X-axis', fontsize = 15)


plt.ylabel('Y-axis', fontsize = 15)

plt.show()

Output:

10 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 3
Aim:

Write a program in Python to implement Dataset Normalization for wine quality dataset.

Code and Output:


Code:
#to ignore warnings
import warnings
warnings.filterwarnings('ignore')

import pandas as pd
import seaborn as sns

df=pd.read_csv("Datasets/WineQuality.csv")
df.head()

Code:
df.describe()

Output:

11 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:
sns.distplot(df['free sulfur dioxide'])

Output:

Code:
# value/ max value
df_temp=df.copy()

df_temp['free sulfur dioxide']=df_temp['free sulfur dioxide']/df_temp['free sulfur dioxide']

12 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
sns.distplot(df['alcohol'])
Output:

Code:
df_temp['alcohol']=df_temp['alcohol']/df_temp['alcohol'].abs().max()

sns.distplot(df['alcohol'])

Output:

13 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
sns.distplot(df['total sulfur dioxide'])
Output:

Code:
df_temp=df.copy()
import numpy as np

df_temp['total sulfur dioxide']=np.log(df_temp['total sulfur dioxide']+1)

sns.distplot(df_temp['total sulfur dioxide']) Output:

14 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 4
Aim:
To understand the use of multiline statements in Python. Write a program
in Python to implement Linear Regression for house price prediction.

Code and Output:


Code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model

df=pd.read_csv("Datasets/homeprices.csv")

df.head()

Output:

Code:
df.shape

Output:

15 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
%matplotlib inline

plt.xlabel("Area(sqr feet)",fontsize=20)
plt.ylabel("Price($ Dollar)",fontsize=20)
plt.scatter(df.area,df.price,color='red',marker='+')

Output:

Code:
model=linear_model.LinearRegression()

model.fit(df[['area']],df.price)
Output:

Code:
model.predict([[3500]])

Output:

Code:
model.coef_
16 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Output:

Code:
model.intercept_

Output:

Code:
y= 118.29495955*3500+257056.627255756 y

Output:

Code:
%matplotlib inline

plt.xlabel("Area(sqr feet)",fontsize=20)
plt.ylabel("Price($ Dollar)",fontsize=20)
plt.scatter(df.area,df.price,color='red',marker='+')
plt.grid()

plt.plot(df.area,model.predict(df[['area']]),color='blue')

Ouput:

17 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
d=pd.read_csv("Datasets/predicted_prices.csv")
d.head(5)

Output:

Code:
model.predict(d)

Output:

Code:
p = model.predict(d)
d['predicted prices']=p
d.to_csv('Datasets/prediction2.csv', index= False)

Output: [A excel file will be created with name prediction2]

18 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 5
Aim:
Write a program in Python to implement Polynomial Regression for
employee salary prediction.

Code and Output:


Code:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df=pd.read_csv("Datasets/Position_Salaries.csv")

df.head()

Output:

Code:
X=df.iloc[:,1:2]
X

Output:

19 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:
X=df.iloc[:,1:2].values
X

Output:

Code:
y=df.iloc[:,2].values

Output:

20 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
plt.scatter(X,y)
Output:

Code:
sns.lmplot(x='Level',y='Salary',data=df)

Output:

21 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
from sklearn.linear_model import LinearRegression

model=LinearRegression()

model.fit(X,y)

Output:

Code:
model.predict([[6.5]])

Output:

Code:
from sklearn.preprocessing import PolynomialFeatures

poly=PolynomialFeatures(degree=2)

X_poly=poly.fit_transform(X)

from sklearn.linear_model import LinearRegression

model2=LinearRegression()

model2.fit(X_poly,y)

Output:

Code:
model2.predict(poly.fit_transform([[6.5]]))
Output:

22 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 6
Aim:
Write a program in Python to implement K Nearest Neighbor classifier for
diabetes classification.

Code and Output:


Code:
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler from
sklearn.model_selection import train_test_split from
sklearn import svm
from sklearn.metrics import accuracy_score

diabetes_dataset = pd.read_csv('Datasets/diabetes.csv')

diabetes_dataset.head()

Output:

Code:
diabetes_dataset.shape

Output:

23 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
diabetes_dataset.describe()

Output:

Code:
diabetes_dataset['Outcome'].value_counts()

Output:

Code:
diabetes_dataset.groupby('Outcome').mean()

Output:

Code:
X = diabetes_dataset.drop(columns = 'Outcome', axis=1) Y =
diabetes_dataset['Outcome']

print(X)

Output:
24 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:
print(Y)

Output:

25 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
scaler = StandardScaler()

scaler.fit(X)

Output:

Code:
standardized_data = scaler.transform(X)

print(standardized_data)

Output:

Code:
X = standardized_data
Y = diabetes_dataset['Outcome']

X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.2, stratify=Y, random_state=2)

print(X.shape, X_train.shape, X_test.shape)

26 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Output:

Code:
from sklearn.neighbors import KNeighborsClassifier

knn=KNeighborsClassifier(n_neighbors=1)

knn.fit(X_train, Y_train)

Output:

Code:
X_train_prediction = knn.predict(X_train)
training_data_accuracy = accuracy_score(X_train_prediction, Y_train)

print('Accuracy score of the training data : ', training_data_accuracy)

Output:

Code:
X_test_prediction = knn.predict(X_test)
test_data_accuracy = accuracy_score(X_test_prediction, Y_test)

print('Accuracy score of the test data : ', test_data_accuracy)

Output:

Code:
input_data = (5,166,72,19,175,25.8,0.587,51)

# changing the input_data to numpy array


input_data_as_numpy_array = np.asarray(input_data)

# reshape the array as we are predicting for one instance


input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)

27 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
# standardize the input data
std_data = scaler.transform(input_data_reshaped)

#print(std_data)
prediction = knn.predict(std_data)
print(prediction)

if (prediction[0] == 0):
print('The person is not diabetic')
else:
print('The person is diabetic')

Output:

28 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 7
Aim:
Write a Python code to implement the feature selection technique using
Correlation Matrix.

Code and Output:


Code:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

df=pd.read_csv("Datasets/bike_sharing_dataset.csv")
df.head()

Output:

Code:
corr=df.corr()

corr

29 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:
corr=df.corr()
plt.figure(figsize=(12,6))
sns.heatmap(corr,annot=True,cmap='coolwarm')
Output:

30 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 8
Aim:
Write a Python code to predict if a person would buy life insurance based
on his age using Logistic Regression.

Code and Output:


Code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df=pd.read_csv("Datasets/insurance_data.csv")
df.head()

Output:

Code:
plt.scatter(df.age,df.bought_insurance,marker='+',color='red')

Output:

31 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:
from sklearn.model_selection import train_test_split

X=df.iloc[:,0:1]

Output:

32 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
X=df.iloc[:,0:1].values
X
Output:

Code:
y=df.iloc[:,1]

Output:

33 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Code:
y=df.iloc[0:,1].values

Output:

34 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
X_train, X_test, y_train, y_test =train_test_split(X,y,train_size=0.8)

X_test

Output:

Code:
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()

model.fit(X_train,y_train)

Output:

Code:
X_test

Output:

Code:
y_predicted = model.predict(X_test)
model.predict_proba(X_test)

35 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Output:

Code:
model.score(X_test,y_test)

Output:

Code:
y_predicted

Output:

Code:
X_test

Output:

Code:
model.coef_

Output:

Code:
model.intercept_

Output:

36 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
import math
def sigmoid(x):
return 1/(1+math.exp(-x))

def prediction_function(age):
z=0.042*age - 1.53
y=sigmoid(z)
return y

age = 35
prediction_function(age)

Output:

Code:
age = 43
prediction_function(age)

Output:

37 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 9
Aim:
Write a program in Python to implement Support Vector Machine for
diabetes classification.

Code and Output:


Code:
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler from
sklearn.model_selection import train_test_split from
sklearn import svm
from sklearn.metrics import accuracy_score

diabetes_dataset = pd.read_csv('Datasets/diabetes.csv')

diabetes_dataset.head()

Output:

Code:
diabetes_dataset.shape

Output:

38 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
diabetes_dataset.describe()

Output:

Code:
diabetes_dataset['Outcome'].value_counts()

Output:

Code:
diabetes_dataset.groupby('Outcome').mean()

Output:

Code:
X = diabetes_dataset.drop(columns = 'Outcome', axis=1) Y =
diabetes_dataset['Outcome']

print(X)

39 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Output:

Code:
print(Y)

Output:

40 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
scaler = StandardScaler()

scaler.fit(X)

Output:

Code:
standardized_data = scaler.transform(X)

print(standardized_data)

Output:

Code:
X = standardized_data
Y = diabetes_dataset['Outcome']

X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size = 0.2, stratify=Y, random_state=2)

print(X.shape, X_train.shape, X_test.shape)

Output:

41 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
classifier = svm.SVC()

classifier.fit(X_train, Y_train)
Output:

Code:
X_train_prediction = classifier.predict(X_train)
training_data_accuracy = accuracy_score(X_train_prediction, Y_train)

print('Accuracy score of the training data : ', training_data_accuracy)

Output:

Code:
X_test_prediction = classifier.predict(X_test)
test_data_accuracy = accuracy_score(X_test_prediction, Y_test)

print('Accuracy score of the test data : ', test_data_accuracy)

Output:

Code:
input_data = (5,166,72,19,175,25.8,0.587,51)

# changing the input_data to numpy array


input_data_as_numpy_array = np.asarray(input_data)

# reshape the array as we are predicting for one instance


input_data_reshaped = input_data_as_numpy_array.reshape(1,-1)

# standardize the input data


std_data = scaler.transform(input_data_reshaped)

#print(std_data)

prediction = classifier.predict(std_data)

42 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
print(prediction)

if (prediction[0] == 0):
print('The person is not diabetic')
else:
print('The person is diabetic')

Output:

43 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)

Experiment No: 10
Aim:

Demonstrate the application of Artificial Neural Network using Python.

Code and Output:


1. Data Preprocessing

1.1 Import the Libraries-

Code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

1.2 Load the Dataset

dataset = pd.read_csv("/content/Churn_Modelling.csv")

dataset.head()

Output:

1.3 Split Dataset into X and Y

Code:
X = pd.DataFrame(dataset.iloc[:, 3:13].values)
y = dataset.iloc[:, 13].values

44 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Output:

Code:
y

Output:

1.4 Encode Categorical Data

Code:
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer labelencoder_X_2
= LabelEncoder()
X.loc[:, 2] = labelencoder_X_2.fit_transform(X.iloc[:, 2])

labelencoder_X_1 = LabelEncoder()
X.loc[:, 1] = labelencoder_X_1.fit_transform(X.iloc[:, 1])

onehotencoder = ColumnTransformer([("Country", OneHotEncoder(), [1])], remainder =


'passthrough')
labelencoder_X_1 = LabelEncoder()
45 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
X.loc[:, 1] = labelencoder_X_1.fit_transform(X.iloc[:, 1])
X = onehotencoder.fit_transform(X)
X = X[:, 1:]

1.5 Split the X and Y Dataset into the Training set and Test set

Code:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

1.6 Perform Feature Scaling

Code:
from sklearn.preprocessing import StandardScaler sc
= StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

2.1 Import the Keras libraries and packages

Code:
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense

2.2 Initialize the Artificial Neural Network

Code:
classifier = Sequential()

2.3 Add the input layer and the first hidden layer

Code:
classifier.add(Dense(6, activation = 'relu', input_dim = 11)) 2.4

Add the second hidden layer Code:

classifier.add(Dense(6, activation = 'relu'))

46 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
2.5 Add the output layer

Code:
classifier.add(Dense(1, activation = 'sigmoid'))

3.1 Compile the ANN

Code:
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy' ])

3.2 Fit the ANN to the Training set

Code:
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)

Output:

4. Predict the Test Set Results

Code:
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)

Output:

47 | P a g e
Government Engineering College, Bilaspur
Department of Computer Science and Engineering
MACHINE LEARNING LAB: D022721 (022)
Code:
y_pred

Output:

5. Make the Confusion Matrix

Code:
from sklearn.metrics import confusion_matrix, accuracy_score cm
= confusion_matrix(y_test, y_pred) print(cm)

accuracy_score(y_test,y_pred)

Output:

48 | P a g e

You might also like