You are on page 1of 11

MUMBAI EDUCATIONAL TRUST

MET Institute of Computer Science


UNIVERSITY OF MUMBAI
Practical Examination –July 2021
M.C.A Semester – 2

Subject : AIML Lab


Roll No : 1163
Name of Student : SARIKA ASHOK SINGH
Date: 29-07-2021
Instructions:

1) Subject Name is Mentioned in the Topic


2) Copy Questions
3) Add Source Code/Output as Answer
4) Repeat the Process for all Questions
5) If the answer is handwritten, Scan and Paste the image

Q 1 : Write a PROLOG program to display travelling distance.

The knowledge base given is as follows


road(mumbai,indore,601).
road(indore,gwalior,505).
road(gwalior,agra,121).
road(agra,delhi,222).
road(mumbai,surat,300).
road(surat,vadodara,154).
road(vadodara,jodhpur,554).
road(jodhpur,jaipur,357).
Write a predicate route(Town1,Town2,Distance), which will find distance between Town1 and Town2.
The route may be direct or indirect(i.e. visiting different towns and reaching to goal)
If the goal is route(mumbai,indore,Distance) then it should display Distance=601.
If the goal is route(indore,delhi,Distance) then it should display Distance=848 (i.e. 505+121+222=848)

Ans:

road(mumbai,indore,601).

road(indore,gwalior,505).

road(gwalior,agra,121).

1
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science
road(agra,delhi,222).

road(mumbai,surat,300).

road(surat,vadodara,154).

road(vadodara,jodhpur,554).

road(jodhpur,jaipur,357).

route(X,Y,Distance):-

road(X,Y,Distance),

write('Distance Between '),write(X),write(' and '),write(Y),write(' is '),

write(Distance),write(' km.'),nl.

route(X,Y,Distance):-

road(X,Z,Distance1),

route(Z,Y,Distance2),

Distance is Distance1+Distance2,!,

write('Cumulative Distance Between '),write(X),write(' and '),write(Y),write(' is '),

write(Distance),write(' km.'),nl.

Output :

2
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science

3
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science

Q 2 : Perform the following on dataset headbrain.csv

Ans:

(i) import necessary libraries and read the data from the file

#(i) import necessary libraries and read the data from the file
from mpl_toolkits.mplot3d import Axes3D
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
%matplotlib inline

#upload data file headbrain.csv


from google.colab import files
files.upload()

(ii) Display the first 5 records from the dataset.

# Reading Data from the 'headbrain.csv' and store in dataframe 'data'


data = pd.read_csv("headbrain.csv")
#(ii) Display the first 5 records from the dataset.
data.head()

4
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science

(iii) Display number of rows and columns in the data


#(iii) Display number of rows and columns in the data
data.shape

(iv) Display statistical summary of data

#(iv) Display statistical summary of data

data.describe()

5
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science

(v) Display scatter plot of Head size vs Brain weight

#(v) Display scatter plot of Head size vs Brain weight


plt.scatter(X, Y, color='green', label='Data Points')
plt.xlabel('Head Size in cm3')
plt.ylabel('Brain Weight in grams')
plt.legend()
plt.show()

(vi) Apply splitting on the dataset as 80% for training and 20% for testing.

#(vi) Apply splitting on the dataset as 80% for training and 20% for testing.
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
X=data['Head Size(cm^3)'].values
Y=data['Brain Weight(grams)'].values
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2)
#splitting the data into training and test
msk = np.random.rand(len(data)) < 0.8

6
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science
train = data[msk]
test = data[~msk]
print(train)
print('-------------------------------------')
print(test)

7
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science
(vii) Assigning ‘X’ as independent variable and ‘y’ as dependent variable. Use input as Head Size and
output Brain weight

#(vii) Assigning ‘X’ as independent variable and ‘y’ as dependent variable. Use input
as Head Size and output Brain weight
X=data['Head Size(cm^3)'].values
Y=data['Brain Weight(grams)'].values
sns.scatterplot(data=data, x="Head Size(cm^3)", y="Brain Weight(grams)")
plt.show()

(viii)Apply linear regression algo. with default parameters

#(viii)Apply linear regression algo. with default parameters


def Linear_Regression(X,Y):
mean_x = np.mean(X)
mean_y = np.mean(Y)
n = len(X)
numerator= 0
denominator=0
for i in range(n):
numerator += ((X[i] - mean_x) * (Y[i] - mean_y))
denominator += ((X[i] - mean_x) ** 2)
m = numerator/ denominator
c = mean_y - m * mean_x
return(m,c)
def predict(X,m,c):
pred_y=[]

8
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science
for i in range(len(X)):
pred_y.append(c + m * X[i])
return(pred_y)
def r2score(y_obs,y_pred):
yhat = np.mean(y_obs)
ss_res = 0.0
ss_tot = 0.0
for i in range(len(y_obs)):
ss_tot += (y_obs[i]-yhat)**2
ss_res += (y_obs[i]-y_pred[i])**2
r2 = 1 - (ss_res/ss_tot)
return r2

plt.title("Linear Regression Plot of HeadSize Vs Brain Weight")


X_train,X_test,y_train,y_test = train_test_split(X,Y,test_size=0.2)
m,c = Linear_Regression(X_train,y_train)
print("slope = ", m)
print('intercept = ',c)
y_pred = predict(X_test,m,c)
print(y_pred)
print("R-squared :",r2score(y_test,y_pred))
plt.plot(X_test,y_pred,color='red',label='Linear Regression')
plt.scatter(X_train,y_train,c='b',label='Scatter Plot')
plt.xlabel("Head Size")
plt.ylabel("Brain Weight")
plt.legend()
plt.show()

9
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science
(ix) Train the model

#(ix) Train the model

from sklearn import metrics


from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Cannot use Rank 1 matrix in scikit learn


X = X.reshape((-1, 1))
# Creating Model
reg = LinearRegression()
# Fitting training data
reg = reg.fit(X, Y)
# Y Prediction
Y_pred = reg.predict(X)

print("Prediction by Model :\t" , reg.predict([[4100]]))

10
MUMBAI EDUCATIONAL TRUST
MET Institute of Computer Science
(x)Display rmse, r2_score

#(x)Display rmse, r2_score


from sklearn import metrics
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Cannot use Rank 1 matrix in scikit learn
X = X.reshape((-1, 1))
# Creating Model
reg = LinearRegression()
# Fitting training data
reg = reg.fit(X, Y)
# Y Prediction
Y_pred = reg.predict(X)
# Calculating RMSE and R2 Score
mse = mean_squared_error(Y, Y_pred)
rmse = np.sqrt(mse)
r2_score = reg.score(X, Y)
print('RMSE:', np.sqrt(metrics.mean_squared_error(Y, Y_pred)))
print('R2 Score :', r2_score)

11

You might also like