0% found this document useful (0 votes)
779 views17 pages

Cognitive Science Manual

CCS337 COGNITIVE SCIENCE lab manual anna university 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.

Uploaded by

cse girls
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
779 views17 pages

Cognitive Science Manual

CCS337 COGNITIVE SCIENCE lab manual anna university 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.

Uploaded by

cse girls
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Ex:1 Demonstration of Mathematical functions using WebPPL

Aim:
To write a WebPPL program to demonstrate mathematical functions.

Algorithm:

1. Define a function named `two_coins`.


2. Within the function, initialize a variable `c1` to the result of flipping a coin with a
probability of heads (success) being 0.5.
3. Within the function, initialize another variable `c2` to the result of flipping
another coin with the same probability.
4. Return the sum of `c1` and `c2`.
5. Note: In Webppl, the addition operation coerces Booleans (true/false) to
integers (1/0) when they are added together.

Program:

var two_coins = function() {


var c1 = flip(0.5);
var c2 = flip(0.5);
var output = c1 + c2; // adding Booleans coerces them to integers
print("The value is: " + output);
};

// sample outcome of two coin flips (added together)


two_coins();

Output:
The Value is: 1

Result:

Thus a WebPPL program to demonstrate mathematical functions has been successfully


executed.
Ex:2 Implementation of reasoning algorithms

Aim:
To implement a backward chaining reasoning algorithm.

Algorithm:

1. Initialize a KnowledgeBase class to store rules and a backward chaining


inference engine.
2. Define a Rule class with a conclusion and premises representing logical
implications.
3. Implement a method to add rules to the knowledge base.
4. Create a backward_chain method to infer whether a goal can be derived from
known facts.
5. Check if the goal is already in the known facts; if so, return True.
6. Iterate through each rule in the knowledge base.
7. If the conclusion of a rule matches the goal, check if all premises are true
recursively.
8. If all premises are true, return True, indicating the goal can be inferred.
9. If none of the rules satisfy the goal, return False, indicating it cannot be
inferred.
10. Demonstrate the reasoning algorithm with an example usage, prompting the
user for a goal and evaluating whether it can be derived from the known facts.

Program:

class Rule:
def __init__(self, conclusion, premises):
self.conclusion = conclusion
self.premises = premises

class KnowledgeBase:
def __init__(self):
self.rules = []

def add_rule(self, rule):


self.rules.append(rule)

def ask(self, goal, known_facts):


return self.backward_chain(goal, known_facts)

def backward_chain(self, goal, known_facts):


if goal in known_facts:
return True

for rule in self.rules:


if rule.conclusion == goal:
all_premises_true = True
for premise in rule.premises:
if premise not in known_facts:
if not self.backward_chain(premise, known_facts):
all_premises_true = False
break
if all_premises_true:
return True

return False

# Example usage:
if __name__ == "__main__":
# Create a knowledge base
kb = KnowledgeBase()

# Define some rules


rule1 = Rule("C", ["A", "B"])
rule2 = Rule("B", ["A"])
rule3 = Rule("A", [])

# Add rules to the knowledge base


kb.add_rule(rule1)
kb.add_rule(rule2)
kb.add_rule(rule3)

# Known facts
known_facts = ["A"]

# Query
goal = input("enter the goal:")
result = kb.ask(goal, known_facts)
if result:
print(f"The goal '{goal}' can be inferred from the known facts.")
else:
print(f"The goal '{goal}' cannot be inferred from the known facts.")

Output:

Enter the goal:C


The goal 'C' can be inferred from the known facts.

Result:
Thus the program for implementing the reasoning algorithm has been
successfully executed.
Ex:3 Developing an Application system using generative model

Aim:

To Develop an Application system using generative model.

Algorithm:

1. Import necessary libraries including NumPy, Matplotlib, and Keras modules for
building and training a Variational Autoencoder (VAE) model.
2. Load the MNIST dataset and preprocess it by scaling the pixel values to the
range [0, 1].
3. Define the architecture of the VAE model including the encoder, decoder, and
the entire VAE.
4. Implement a custom sampling function for the latent space using the
reparameterization trick.
5. Build the encoder and decoder models separately and then construct the VAE
by connecting them.
6. Define the loss function for the VAE, comprising both the reconstruction loss
and the KL divergence loss.
7. Compile the VAE model using the Adam optimizer.
8. Train the VAE model using the training data, specifying the number of epochs
and batch size.
9. Create a function to generate images from random points in the latent space
using the decoder model.
10. Implement an interface for user interaction, allowing them to either generate
images or quit the program based on their choice.

Program:

import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
from keras.models import Model
from keras.layers import Input, Dense, Lambda
from keras import backend as K

# Load MNIST dataset


(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))
x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))

# Define VAE model


input_dim = x_train.shape[1]
latent_dim = 2 # 2-dimensional latent space for visualization
intermediate_dim = 256

def sampling(args):
z_mean, z_log_var = args
epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim),
mean=0., stddev=1.)
return z_mean + K.exp(0.5 * z_log_var) * epsilon

# Encoder
inputs = Input(shape=(input_dim,))
h = Dense(intermediate_dim, activation='relu')(inputs)
z_mean = Dense(latent_dim)(h)
z_log_var = Dense(latent_dim)(h)
z = Lambda(sampling)([z_mean, z_log_var])

encoder = Model(inputs, [z_mean, z_log_var, z])

# Decoder
latent_inputs = Input(shape=(latent_dim,))
x = Dense(intermediate_dim, activation='relu')(latent_inputs)
outputs = Dense(input_dim, activation='sigmoid')(x)

decoder = Model(latent_inputs, outputs)

# VAE
outputs = decoder(encoder(inputs)[2])
vae = Model(inputs, outputs)

# Loss function
reconstruction_loss = K.sum(K.binary_crossentropy(inputs, outputs), axis=-1)
kl_loss = -0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
vae_loss = K.mean(reconstruction_loss + kl_loss)
vae.add_loss(vae_loss)
vae.compile(optimizer='adam')
# Train VAE
vae.fit(x_train, epochs=50, batch_size=128, validation_data=(x_test, None))

# Generate images
def generate_images(n=10):
random_latent_vectors = np.random.normal(size=(n, latent_dim))
generated_images = decoder.predict(random_latent_vectors)
plt.figure(figsize=(n * 2, 2))
for i in range(n):
ax = plt.subplot(1, n, i + 1)
plt.imshow(generated_images[i].reshape(28, 28), cmap='gray')
plt.axis('off')
plt.show()

# Interface
def main():
while True:
print("Press 'g' to generate images, or 'q' to quit.")
choice = input("Enter your choice: ")
if choice == 'g':
generate_images()
elif choice == 'q':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

Output:
Result:

Thus the program for developing an Application system using generative model has
been successfully executed.
Ex:4 Developing an Application system using generative model

Aim:
To Develop an Application system using generative model

Algorithm:

1. Import required modules from the scikit-learn library including DecisionTreeClassifier


for building a decision tree classifier, accuracy_score for evaluating model performance, and
train_test_split for splitting the dataset.
2. Define sample dataset including input features, conditional information, and labels
(output).
3. Split the dataset into training and testing sets using train_test_split, considering a
specified test size and random state for reproducibility.
4. Train the decision tree classifier using the training data, where input features and
conditional information are concatenated horizontally.
5. Evaluate the trained model by making predictions on the testing data and calculating
the accuracy of the predictions.
6. Define an application interface function predict_class() to predict the class of a new
data point based on user input.
7. Implement a main loop for user interaction, allowing them to either predict a class for
new data or quit the program based on their choice.
8. Prompt the user to input data and conditional information for prediction and display
the predicted class.
9. Provide an option to exit the program or continue predicting classes based on user
input.
10. Ensure proper handling of invalid choices within the main loop, prompting the user to
try again if an incorrect choice is made.

Program:

from sklearn.tree import DecisionTreeClassifier


from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import numpy as np

# Sample dataset: Input data (features) and conditional information (additional features)
# Replace this with your actual dataset
input_data = np.array([[
5.1, 3.5], [4.9, 3.0], [6.0, 3.2], [6.7, 3.1], [5.6, 3.0]])
conditional_info = np.array([[0, 1], [1, 0], [0, 1], [1, 0], [0, 1]]) # Example: Two classes
# Sample labels (output)
labels = np.array([0, 1, 0, 1, 0]) # Example: Binary classification

# Split dataset into training and testing sets


X_train, X_test, cond_train, cond_test, y_train, y_test = train_test_split(
input_data, conditional_info, labels, test_size=0.2, random_state=42)

# Train the decision tree classifier


clf = DecisionTreeClassifier()
clf.fit(np.hstack((X_train, cond_train)), y_train)

# Evaluate the model


y_pred = clf.predict(np.hstack((X_test, cond_test)))
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

# Application interface
def predict_class():
print("Enter input data:")
input_data = [float(x) for x in input("Enter space-separated values: ").split()]
print("Enter conditional information:")
conditional_info = [int(x) for x in input("Enter space-separated values (0 or 1): ").split()]
prediction = clf.predict([input_data + conditional_info])
print("Predicted class:", prediction[0])

# Main loop
while True:
print("\nPress 'p' to predict a class or 'q' to quit.")
choice = input("Enter your choice: ")
if choice == 'p':
predict_class()
elif choice == 'q':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")

Output:

Accuracy: 1.0

Press 'p' to predict a class or 'q' to quit.


Enter your choice: p
Enter input data:
Enter space-separated values: 4.9 3.0
Enter conditional information:
Enter space-separated values (0 or 1): 1 0
Predicted class: 1

Press 'p' to predict a class or 'q' to quit.


Enter your choice: q
Exiting...

Result:

Thus the program for developing an Application using conditional inference learning
model has been successfully executed.
Ex:5 Application development using hierarchical model

Aim:
To Develop application using hierarchical model.

Algorithm:

1. Import necessary modules including NumPy, Matplotlib, and hierarchical clustering


functions from scipy.
2. Define sample data points to be clustered using hierarchical clustering.
3. Perform hierarchical clustering using single-linkage method on the sample data
points.
4. Visualize the resulting dendrogram representing the hierarchical clustering.
5. Define an application interface function predict_cluster() to predict the cluster of a new
data point entered by the user.
6. Implement a main loop for user interaction, allowing them to either predict a cluster for
a new data point or quit the program based on their choice.
7. Prompt the user to input a data point for cluster prediction and display the predicted
cluster.
8. Offer an option to exit the program or continue predicting clusters based on user input,
handling invalid choices appropriately within the main loop.

Program:

import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage

# Sample data points


X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11], [8, 2], [10, 2], [9, 3]])

# Perform hierarchical clustering


linked = linkage(X, 'single') # Single-linkage clustering

# Plot dendrogram
plt.figure(figsize=(10, 5))
dendrogram(linked, orientation='top', labels=range(1, 10), distance_sort='descending',
show_leaf_counts=True)
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('Data Points')
plt.ylabel('Distance')
plt.show()
# Application interface
def predict_cluster():
print("Enter a data point to predict its cluster:")
data_point = [float(x) for x in input("Enter space-separated values: ").split()]
cluster = np.argmin(np.sum((X - np.array(data_point))**2, axis=1)) + 1
print("Predicted cluster:", cluster)

# Main loop
while True:
print("\nPress 'p' to predict a cluster or 'q' to quit.")
choice = input("Enter your choice: ")
if choice == 'p':
predict_cluster()
elif choice == 'q':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")

Output:

Press 'p' to predict a cluster or 'q' to quit.


Enter your choice: p
Enter a data point to predict its cluster:
Enter space-separated values: 5 8
Predicted cluster: 3

Press 'p' to predict a cluster or 'q' to quit.


Enter your choice: q
Exiting...

Result:

Thus the program for developing an Application using hierarchical model has been
successfully executed.
Ex:6 Application development using Mixture model

Aim:

To develop application using Mixture model.

Algorithm:

1. Import necessary modules including NumPy, Matplotlib, and Gaussian Mixture


Model from scikit-learn.
2. Generate sample data points from two normal distributions and concatenate them to
create a synthetic dataset.
3. Fit a Gaussian Mixture Model (GMM) to the sample data with two components using
the expectation-maximization algorithm.
4. Predict cluster labels for the data points based on the trained GMM.
5. Visualize the data points colored by their predicted clusters on a scatter plot.
6. Define an application interface function predict_cluster() to predict the cluster of a
new data point entered by the user using the trained GMM.
7. Implement a main loop for user interaction, allowing them to either predict a cluster
for a new data point or quit the program based on their choice.
8. Prompt the user to input a data point for cluster prediction and display the predicted
cluster.
9. Offer an option to exit the program or continue predicting clusters based on user
input, handling invalid choices appropriately within the main loop.

Program:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture

# Sample data points


X = np.concatenate([np.random.normal(0, 1, size=(100, 2)),
np.random.normal(3, 1, size=(100, 2))])
# Fit Gaussian Mixture Model
gmm = GaussianMixture(n_components=2, random_state=42)
gmm.fit(X)
# Predict clusters
labels = gmm.predict(X)
# Plot data points and clusters
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', alpha=0.5)
plt.colorbar(label='Cluster')
plt.title('Gaussian Mixture Model')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()

# Application interface
def predict_cluster():
print("Enter a data point to predict its cluster:")
data_point = [float(x) for x in input("Enter space-separated values: ").split()]
cluster = gmm.predict([data_point])[0]
print("Predicted cluster:", cluster)

while True:
print("\nPress 'p' to predict a cluster or 'q' to quit.")
choice = input("Enter your choice: ")
if choice == 'p':
predict_cluster()
elif choice == 'q':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")

Output:
Press 'p' to predict a cluster or 'q' to quit.
Enter your choice: p
Enter a data point to predict its cluster:
Enter space-separated values: 0 2
Predicted cluster: 1
Press 'p' to predict a cluster or 'q' to quit.
Enter your choice: q
Exiting...

Result:
Thus the program for developing an Application using mixture model has been
successfully executed.

You might also like