0% found this document useful (0 votes)
4 views

CS - LAB

The document outlines practical exercises for a Cognitive Science course at Einstein College of Engineering, including tasks such as demonstrating mathematical functions using WebPPL, implementing reasoning algorithms in Python, and developing applications using various models. Each exercise includes an aim, algorithm, program code, and results confirming successful execution. The exercises cover a range of programming techniques and applications in cognitive science.

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)
4 views

CS - LAB

The document outlines practical exercises for a Cognitive Science course at Einstein College of Engineering, including tasks such as demonstrating mathematical functions using WebPPL, implementing reasoning algorithms in Python, and developing applications using various models. Each exercise includes an aim, algorithm, program code, and results confirming successful execution. The exercises cover a range of programming techniques and applications in cognitive science.

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/ 17

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 : CCS337

COURSE NAME : COGNITIVE SCIENCE


CCS337 – COGNITIVE SCIENCE

PRACTICAL EXERCISES:

1. Demonstration of Mathematical Functions Using WebPPL.

2. Implementation of Reasoning Algorithms.

3. Developing an Application System Using Generative Model.

4. Developing an Application Using Conditional Inference

Learning Model.

5. Application Development Using Hierarchical Model.

6. Application Development Using Mixture Model.


1.Demonstration of Mathematical Functions Using WebPPL

AIM :

To write a java script program to demonstration of


Mathematical Functions Using WebPPL.

ALGORITHM :

1. Define functions for each mathematical operation.


2. Input values for variables.
3. Call the functions with the input values.
4. Perform the calculation inside the function and return the result.
5. Display the result using console.log or another output method.

PROGRAM :

var add = function(a, b) {


return a + b;
};
var subtract = function(a, b) {
return a - b;
};
var multiply = function(a, b) {
return a * b;
};
var divide = function(a, b) {
return a / b;
};
var power = function(a, b) {
return Math.pow(a, b);
};

var squareRoot = function(a) {


return Math.sqrt(a);
};
var log10 = function(a) {
return Math.log10(a);
};
var sinValue = function(x) {
return Math.sin(x);
};
var cosValue = function(x) {
return Math.cos(x);
};
var tanValue = function(x) {
return Math.tan(x);
};
var a = 10;
var b = 5;
print("Addition: " + add(a, b));
print("Subtraction: " + subtract(a, b));
print("Multiplication: " + multiply(a, b));
print("Division: " + divide(a, b));
print("Power: " + power(a, b));
print("Square Root: " + squareRoot(a));
print("Log10: " + log10(a));
print("Sin(a): " + sinValue(a));
print("Cos(a): " + cosValue(a));
print("Tan(a): " + tanValue(a));
OUTPUT :

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Power: 100000
Square Root: 3.1622776601683795
Log10: 1
Sin(a): -0.5440211108893698
Cos(a): -0.8390715290764524
Tan(a): 0.6483608274590866

RESULT :

Thus the java script program to demonstration of Mathematical


Functions Using WebPPL was executed successfully and the output is
verified.
2.Implementation of Reasoning Algorithms

AIM :

To write a python program to implementation of Reasoning


Algorithms.

ALGORITHM :

1. Define family facts by creating a dictionary with Parent-Child


pairs.
2. For a given Person, identify others who share at least one Parent to
find Siblings.
3. For a given Person, find the Parents of their Parents to identify
Grandparents.
4. Match relationships by using loops to check shared Parents or
Grandparents.
5. Output the results, displaying Siblings or Grandparents based on
the queries.

PROGRAM :

family = {
"parent": [
("John", "Mary"),
("John", "Peter"),
("Susan", "Mary"),
("Susan", "Peter"),
("Mary", "James"),
("Mary", "Sophia"),
]
}
def find_siblings(person):
siblings = set()
for p1, child1 in family["parent"]:
for p2, child2 in family["parent"]:
if p1 == p2 and child1 != child2 and child1 == person:
siblings.add(child2)
return siblings
def find_grandparents(person):
grandparents = set()
for grandparent, parent in family["parent"]:
for p, child in family["parent"]:
if parent == p and child == person:
grandparents.add(grandparent)
return grandparents
query1 = "Mary"
siblings_of_query1 = find_siblings(query1)
print(f"Siblings of {query1}: {siblings_of_query1}")
query2 = "James"
grandparents_of_query2 = find_grandparents(query2)
print(f"Grandparents of {query2}: {grandparents_of_query2}")

OUTPUT :

Siblings of Mary: {'Peter'}


Grandparents of James: {'Susan', 'John'}

RESULT :

Thus the python program to implementation of Reasoning


Algorithms was executed successfully and the output is verified.
3.Developing an Application System Using Generative Model

AIM :

To write a python program to developing an Application System


Using Generative Model.

ALGORITHM :

1.Initialize the GPT-3.5 Client.


2.Define the Writing Prompt Generation Function.
3.Set Up the Gradio Interface.
4. Add Example Prompts.
5.Launch the Web Interface.

PROGRAM :

from g4f.client import Client


import gradio as gr
client = Client()
def generate_writing_prompt(user_input):
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": user_input}],
)
return response.choices[0].message['content']
interface = gr.Interface(
fn=generate_writing_prompt,
inputs=gr.Textbox(lines=3, placeholder="Enter a genre, tone, or
initial plot point..."),
outputs="text",
title="Creative Writing Assistant",
description="Unleash your creativity! Get inspired with unique
story ideas, prompts, and plot twists.",
theme="huggingface",
examples=[
["A story about a lost civilization discovering technology."],
["Compose a poem about the changing seasons."],
["A suspense thriller set in an abandoned mansion."],
]
)
if __name__ == "__main__":
interface.launch()

OUTPUT :

RESULT :

Thus the python program to developing an Application System


Using Generative Model was executed successfully and the output is
verified.
4.Developing an Application Using Conditional Inference

Learning Model

AIM :

To write a python program to developing an Application Using


Conditional Inference Learning Model.

ALGORITHM :

1.Load and Prepare the Dataset.


2.Split the Data into Training and Testing Sets.
3.Train the Decision Tree Model.
4.Make Predictions and Evaluate Accuracy.
5.Visualize the Decision Tree.

PROGRAM :

from sklearn.tree import DecisionTreeClassifier, plot_tree


from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
import pandas as pd
import matplotlib.pyplot as plt
data = load_iris()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = pd.Series(data.target)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy * 100:.2f}%")
plt.figure(figsize=(12, 8))
plot_tree(clf, filled=True, feature_names=data.feature_names,
class_names=data.target_names)
plt.show()

OUTPUT :

Model Accuracy: 100.00%

RESULT :

Thus the python program to Developing an Application Using


Conditional Inference Learning Model was executed successfully and
the output is verified.
5.Application Development Using Hierarchical Model

AIM :

To write a python program to application Development Using


Hierarchical Model.

ALGORITHM :

1.Define the Employee Class.


2.Define the Department Class.
3.Define the Company Class.
4.Add Departments, Employees, and Sub-Departments
5.Display the Company Hierarchy.

PROGRAM :

class Employee:
def __init__(self, name, position):
self.name = name
self.position = position
def __repr__(self):
return f"Employee(name={self.name},
position={self.position})"
class Department:
def __init__(self, name):
self.name = name
self.employees = []
self.sub_departments = []
def add_employee(self, employee):
self.employees.append(employee)
def add_sub_department(self, department):
self.sub_departments.append(department)
def __repr__(self):
return f"Department(name={self.name},
employees={len(self.employees)},
sub_departments={len(self.sub_departments)})"
class Company:
def __init__(self, name):
self.name = name
self.departments = []
def add_department(self, department):
self.departments.append(department)
def display_hierarchy(self):
print(f"Company: {self.name}")
self._display_departments(self.departments, indent=2)
def _display_departments(self, departments, indent):
for department in departments:
print(" " * indent + f"Department: {department.name}")
for employee in department.employees:
print(" " * (indent + 2) + f"Employee: {employee.name},
Position: {employee.position}")
if department.sub_departments:
self._display_departments(department.sub_departments,
indent + 2)
my_company = Company("Tech Innovators")
sales_department = Department("Sales")
hr_department = Department("Human Resources")
sales_department.add_employee(Employee("Alice", "Sales
Manager"))
sales_department.add_employee(Employee("Bob", "Sales
Associate"))
hr_department.add_employee(Employee("Charlie", "HR Manager"))
recruitment_department = Department("Recruitment")
hr_department.add_sub_department(recruitment_department)
recruitment_department.add_employee(Employee("David",
"Recruiter"))
my_company.add_department(sales_department)
my_company.add_department(hr_department)
my_company.display_hierarchy()
OUTPUT :

Company: Tech Innovators


Department: Sales
Employee: Alice, Position: Sales Manager
Employee: Bob, Position: Sales Associate
Department: Human Resources
Employee: Charlie, Position: HR Manager
Department: Recruitment
Employee: David, Position: Recruiter

RESULT :

Thus the python program to Application Development Using


Hierarchical Model was executed successfully and the output is
verified.
6.Application Development Using Mixture Model

AIM :

To write a python program to application Development Using


Mixture Model.

ALGORITHM :

1.Generate Synthetic Data.


2.Fit the Gaussian Mixture Model.
3.Predict Cluster Labels.
4.Plot the Data and Clusters.
5.Overlay Ellipses for Gaussian Components.

PROGRAM :

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
X, _ = make_blobs(n_samples=500, centers=3, random_state=42)
gmm = GaussianMixture(n_components=3, covariance_type='full',
random_state=42)
gmm.fit(X)
labels = gmm.predict(X)
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', marker='o',
alpha=0.7)
ax = plt.gca()
for mean, covar in zip(gmm.means_, gmm.covariances_):
v, w = np.linalg.eigh(covar)
v = 2.0 * np.sqrt(2.0) * np.sqrt(v)
u = w[0] / np.linalg.norm(w[0])
angle = np.arctan(u[1] / u[0])
angle = 180.0 * angle / np.pi
angle = angle + 90
ell = plt.matplotlib.patches.Ellipse(mean, v[0], v[1], angle=180.0 +
angle, color='red', alpha=0.5)
ax.add_patch(ell)
plt.title('Gaussian Mixture Model Clustering', fontsize=16)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()

OUTPUT :

RESULT :

Thus the python program to Application Development Using


Mixture Model was executed successfully and the output is verified.

You might also like