0% found this document useful (0 votes)
21 views20 pages

Ke - Lab

The document is a lab manual for the Knowledge Engineering course at Einstein College of Engineering for the academic year 2024-2025. It outlines practical exercises including Evidence Based Reasoning, Probability Based Reasoning, Believability Analysis, Rule Learning, and Ontology construction, along with algorithms and sample Python programs for each exercise. Each exercise is structured with aims, algorithms, programs, outputs, and results to verify successful execution.

Uploaded by

pathisiva2004
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)
21 views20 pages

Ke - Lab

The document is a lab manual for the Knowledge Engineering course at Einstein College of Engineering for the academic year 2024-2025. It outlines practical exercises including Evidence Based Reasoning, Probability Based Reasoning, Believability Analysis, Rule Learning, and Ontology construction, along with algorithms and sample Python programs for each exercise. Each exercise is structured with aims, algorithms, programs, outputs, and results to verify successful execution.

Uploaded by

pathisiva2004
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/ 20

EINSTEIN COLLEGE OF ENGINEERING

SIR C.V.RAMAN NAGAR , TIRUNELVELI – 627012

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUVAL

ACADEMIC YEAR : 2024 – 2025 (REGULATION – 2021)

STUDENT NAME :

REGISTER NUMBER :

PROGRAMME : UG

YEAR / SEMESTER : III / VI

COURSE CODE : CCS350

COURSE NAME : KNOWLEDGE ENGINEERING

1
CCS350 - KNOWLEDGE ENGINEERING

PRACTICAL EXERCISES:

1. Perform operations with Evidence Based Reasoning.

2. Perform Evidence based Analysis.

3. Perform operations on Probability Based Reasoning.

4. Perform Believability Analysis.

5. Implement Rule Learning and refinement.

6. Perform analysis based on learned patterns.

7. Construction of Ontology for a given domain.

2
TABLE OF CONTENT

Serial Page Staff


Date Name of the Experiment
No No Initial

1 Perform operations with Evidence Based


4
Reasoning

Perform Evidence based Analysis 6


2

3 Perform operations on Probability Based 9


Reasoning

Perform Believability Analysis 12


4

Implement Rule Learning and refinement 15


5

Perform analysis based on learned patterns 17


6

Construction of Ontology for a given 19


7
domain

3
EX.NO:01

DATE: Perform operations with Evidence Based Reasoning

AIM :

To write a python program to perform operations with Evidence


Based Reasoning.

ALGORITHM :

STEP : 1 Import the necessary libraries.


STEP : 2 Create the dataset as a dictionary.
STEP : 3 Convert the dictionary to a DataFrame.
STEP : 4 Define features (X) and target variable (y).
STEP : 5 Split the data into training and testing sets.
STEP : 6 Initialize the LinearRegression model.
STEP : 7 Train the model using the training data.
STEP : 8 Create a DataFrame for the new project.
STEP : 9 Predict the success rate for the new project using the model.
STEP : 10 Print the predicted success rate.

PROGRAM :

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Create the dataset
data = {
'Project': ['Project_A', 'Project_B', 'Project_C', 'Project_D',
'Project_E'],
'Number_of_Workers': [10, 15, 20, 25, 30],
'Years_of_Experience': [5, 7, 9, 6, 8],
'Success_rate': [80, 85, 75, 90, 88]
}
df = pd.DataFrame(data)

4
# Define features and target variable
X = df[['Number_of_Workers', 'Years_of_Experience']]
y = df['Success_rate']
# 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 and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Predict the success rate for the new project
new_project = pd.DataFrame({
'Number_of_Workers': [15],
'Years_of_Experience': [6]
})
new_success_pred = model.predict(new_project)
print(f'Predicted success for the new project: {new_success_pred[0]}')

OUTPUT :

Predicted success for the new project: 81.0

RESULT :

Thus the python program to perform operations with Evidence


Based Reasoning was executed successfully and the output is verified.

5
EX.NO:02

DATE: Perform Evidence based Analysis

AIM :

To write a python program to perform Evidence based Analysis.

ALGORITHM :

STEP : 1 Import necessary libraries.


STEP : 2 Create a dataset as a dictionary.
STEP : 3 Convert the dictionary to a DataFrame.
STEP : 4 Define features (X) and target variable (y).
STEP : 5 Split data into training and testing sets.
STEP : 6 Initialize the LinearRegression model.
STEP : 7 Train the model using the training data.
STEP : 8 Create a DataFrame for the new project.
STEP : 9 Predict the success rate for the new project using the model.
STEP : 10 Plot and display line plots for 'Number of Workers' and
'Years of Experience' vs 'Success Rate'.

PROGRAM :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Sample data
data = {
'Project': ['Project_A', 'Project_B', 'Project_C', 'Project_D',
'Project_E'],
'Number_of_Workers': [10, 15, 20, 25, 30],
'Years_of_Experience': [5, 7, 9, 6, 8],
'Success_rate': [80, 85, 75, 90, 88]
}
# Create a DataFrame
6
df = pd.DataFrame(data)
# Define features and target variable
X = df[['Number_of_Workers', 'Years_of_Experience']]
y = df['Success_rate']
# 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 and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Predict the success rate for the new project
new_project = pd.DataFrame({
'Number_of_Workers': [15],
'Years_of_Experience': [6]
})
new_success_pred = model.predict(new_project)
print(f'Predicted success rate for the new project:
{new_success_pred[0]}')
# Create line plots
plt.figure(figsize=(14, 6))
# Line plot for Number of Workers vs. Success Rate
plt.subplot(1, 2, 1)
plt.plot(df['Number_of_Workers'], df['Success_rate'], marker='o')
plt.xlabel('Number of Workers')
plt.ylabel('Success Rate')
plt.title('Number of Workers vs Success Rate')
# Line plot for Years of Experience vs. Success Rate
plt.subplot(1, 2, 2)
plt.plot(df['Years_of_Experience'], df['Success_rate'], marker='o')
plt.xlabel('Years of Experience')
plt.ylabel('Success Rate')
plt.title('Years of Experience vs Success Rate')
plt.tight_layout()
plt.show()

7
OUTPUT :

Predicted success rate for the new project: 81.0

RESULT :

Thus the python program to perform Evidence based Analysis


was executed successfully and the output is verified.

8
EX.NO:03
Perform operations on Probability Based Reasoning
DATE:

AIM :

To write a python program to Perform operations on Probability


Based Reasoning.

ALGORITHM :

STEP : 1 Import the necessary libraries.


STEP : 2 Create the dataset as a dictionary.
STEP : 3 Convert the dictionary to a DataFrame.
STEP : 4 Define features (X) and the target variable (y).
STEP : 5 Split the data into training and testing sets.
STEP : 6 Initialize and train the LinearRegression model.
STEP : 7 Predict the success rate for the new project using the model.
STEP : 8 Define the prior probability and likelihoods for Bayesian
Inference.
STEP : 9 Calculate the posterior probability using Bayes' Theorem.
STEP : 10 Print the predicted and updated success probabilities for
the new project.

PROGRAM :

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Create the dataset
data = {
'Project': ['Project_A', 'Project_B', 'Project_C', 'Project_D',
'Project_E'],
'Number_of_Workers': [10, 15, 20, 25, 30],
'Years_of_Experience': [5, 7, 9, 6, 8],
'Success_rate': [80, 85, 75, 90, 88]

9
}
# Create a DataFrame
df = pd.DataFrame(data)
# Define features and target variable
X = df[['Number_of_Workers', 'Years_of_Experience']]
y = df['Success_rate']
# 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 and train the model
model = LinearRegression()
model.fit(X_train, y_train)
# Predict the success rate for the new project
new_project = pd.DataFrame({
'Number_of_Workers': [15],
'Years_of_Experience': [6]
})
new_success_pred = model.predict(new_project)
print(f'Predicted success for the new project: {new_success_pred[0]}')
# Bayesian Inference
# Prior probability of success (based on past data)
prior_success_prob = 0.8 # Initial belief (e.g., 80% success rate)
# Likelihood of evidence given success (P(E|S))
likelihood_given_success = 0.95 # Probability of having this
evidence if the project is successful
# Likelihood of evidence given failure (P(E|~S))
likelihood_given_failure = 0.4 # Probability of having this evidence
if the project is not successful
# Posterior probability using Bayes' Theorem
posterior_success_prob = (likelihood_given_success *
prior_success_prob) / (
(likelihood_given_success * prior_success_prob) +
(likelihood_given_failure * (1 - prior_success_prob)))
print(f'Updated success probability for the new project:
{posterior_success_prob * 100:.2f}%')

10
OUTPUT :

Predicted success for the new project: 81.0

Updated success probability for the new project: 90.48%

RESULT :

Thus the python program to perform operations on Probability


Based Reasoning was executed successfully and the output is verified.

11
EX.NO:04

DATE: Perform Believability Analysis

AIM :

To write a python program to perform Believability Analysis.

ALGORITHM :

STEP : 1 Import nltk, requests, bs4, and SentimentIntensityAnalyzer.


STEP : 2 Download the Vader lexicon using
nltk.download('vader_lexicon').
STEP : 3 Initialize SentimentIntensityAnalyzer() as sid.
STEP : 4 Define analyze_believability(text) to compute believability
using sentiment scores.
STEP : 5 Define analyze_source_credibility(url) to fetch webpage
content and return credibility score.
STEP : 6 Use requests.get(url) to retrieve webpage content in
analyze_source_credibility().
STEP : 7 Handle exceptions in analyze_source_credibility(url) using
a try-except block.
STEP : 8 Compute believability_score by calling
analyze_believability(text).
STEP : 9 Compute source_credibility_score by calling
analyze_source_credibility(url).
STEP : 10 Print the final believability score as the average of both
scores.

PROGRAM :

pip install nltk


pip install requests
pip install beautifulsoup4
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import requests

12
from bs4 import BeautifulSoup
nltk.download('vader_lexicon')
sid = SentimentIntensityAnalyzer()
def analyze_believability(text):
sentiment_scores = sid.polarity_scores(text)
believability = 1.0 - sentiment_scores['neg']
return believability
def analyze_source_credibility(url):
try:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
source_credibility = 0.7
return source_credibility
except Exception as e:
print(f"Error fetching or analyzing the source: {e}")
return None
if __name__ == "__main__":
text = "This is a sample text that you want to analyze for
believability."
source_url = "https://www.example.com/sample-article"
believability_score = analyze_believability(text)
source_credibility_score = analyze_source_credibility(source_url)
if believability_score is not None and source_credibility_score is
not None:
final_believability_score = (believability_score +
source_credibility_score) / 2
print(f"Believability Score: {final_believability_score}")
else:
print("Unable to calculate believability due to errors.")

13
OUTPUT :

Believability Score: 0.85

RESULT :

Thus the python program to perform Believability Analysis was


executed successfully and the output is verified.

14
EX.NO:05

DATE: Implement Rule Learning and refinement

AIM :

To write a python program to implement Rule Learning and


refinement.

ALGORITHM :

STEP : 1 Import required libraries from sklearn.


STEP : 2 Load the Iris dataset using load_iris().
STEP : 3 Extract features and labels as X and y.
STEP : 4 Split the dataset into training and testing sets.
STEP : 5 Initialize the Decision Tree Classifier.
STEP : 6 Train the classifier using clf.fit(X_train, y_train).
STEP : 7 Predict on the test set using clf.predict(X_test).
STEP : 8 Compute initial accuracy using accuracy_score().
STEP : 9 Retrain the classifier on the same training data.
STEP : 10 Compute and print refined accuracy.

PROGRAM :

from sklearn.datasets import load_iris


from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
data = load_iris()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
initial_accuracy = accuracy_score(y_test, y_pred)

15
print(f"Initial Model Accuracy: {initial_accuracy:.2f}")
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
refined_accuracy = accuracy_score(y_test, y_pred)
print(f"Refined Model Accuracy: {refined_accuracy:.2f}")

OUTPUT :

Initial Model Accuracy: 1.00

Refined Model Accuracy: 1.00

RESULT :

Thus the python program to implement Rule Learning and


refinement was executed successfully and the output is verified.

16
EX.NO:06

DATE: Perform analysis based on learned patterns

AIM :

To write a python program to perform analysis based on learned


patterns.

ALGORITHM :

STEP : 1 Identify the dependent and independent variables to model


their relationship.
STEP : 2 Gather relevant data samples for both variables.
STEP : 3 Handle missing values and outliers; ensure data quality.
STEP : 4 Create scatter plots to observe potential linear relationships.
STEP : 5 Divide data into training and testing sets.
STEP : 6 Use the training set to fit the linear regression model.
STEP : 7 Apply the model to the testing set to predict values.
STEP : 8 Calculate metrics like Mean Squared Error to assess
performance.
STEP : 9 Plot regression line over data to visualize fit.
STEP : 10 Analyze the model coefficients to understand variable
impact.

PROGRAM :

import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
study_hours = np.array([2, 4, 6, 8, 10, 12]).reshape(-1, 1)
exam_scores = np.array([30, 40, 55, 60, 75, 85])
model = LinearRegression()
model.fit(study_hours, exam_scores)
predicted_scores = model.predict(study_hours)
plt.scatter(study_hours, exam_scores, label='Actual scores')

17
plt.plot(study_hours, predicted_scores, color='red', label='Predicted
scores')
plt.xlabel('Study Hours')
plt.ylabel('Exam Scores')
plt.legend()
plt.show()

OUTPUT :

RESULT :

Thus the python program to perform analysis based on learned


patterns was executed successfully and the output is verified.

18
EX.NO:07

DATE: Construction of Ontology for a given domain

AIM :

To write a python program to construction of Ontology for a


given domain.

ALGORITHM :

STEP : 1 Start with an unsorted list of numbers.


STEP : 2 Set a flag to check if swaps are needed.
STEP : 3 Repeat until no swaps are needed.
STEP : 4 Iterate through the list from the first to the second-last
element.
STEP : 5 Compare the current element with the next element.
STEP : 6 If the current element is greater, swap them.
STEP : 7 Set the swap flag to true if a swap occurs.
STEP : 8 Continue until the end of the list is reached.
STEP : 9 If no swaps occurred, the list is sorted.
STEP : 10 Print or return the sorted list.

PROGRAM :

from rdflib import Graph, Namespace, RDF, RDFS, Literal


EX = Namespace("http://example.org/university#")
g = Graph()
g.add((EX.University, RDF.type, RDFS.Class))
g.add((EX.Professor, RDF.type, RDFS.Class))
g.add((EX.Student, RDF.type, RDFS.Class))
g.add((EX.Course, RDF.type, RDFS.Class))
g.add((EX.teaches, RDF.type, RDF.Property))
g.add((EX.enrolledIn, RDF.type, RDF.Property))
g.add((EX.offers, RDF.type, RDF.Property))
g.add((EX.teaches, RDFS.domain, EX.Professor))
g.add((EX.teaches, RDFS.range, EX.Course))

19
g.add((EX.enrolledIn, RDFS.domain, EX.Student))
g.add((EX.enrolledIn, RDFS.range, EX.Course))
g.add((EX.offers, RDFS.domain, EX.University))
g.add((EX.offers, RDFS.range, EX.Course))
g.serialize("university_ontology.ttl", format="turtle")
print(g.serialize(format="turtle"))

OUTPUT :

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .


@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

<http://example.org/university#Course> a rdfs:Class .

<http://example.org/university#Professor> a rdfs:Class .

<http://example.org/university#Student> a rdfs:Class .

<http://example.org/university#University> a rdfs:Class .

<http://example.org/university#enrolledIn> a rdf:Property ;
rdfs:domain <http://example.org/university#Student> ;
rdfs:range <http://example.org/university#Course> .

<http://example.org/university#offers> a rdf:Property ;
rdfs:domain <http://example.org/university#University> ;
rdfs:range <http://example.org/university#Course> .

<http://example.org/university#teaches> a rdf:Property ;
rdfs:domain <http://example.org/university#Professor> ;
rdfs:range <http://example.org/university#Course> .

RESULT :

Thus the python program to construction of Ontology for a


given domain was executed successfully and the output is verified.

20

You might also like