Cognitive Science Manual
Cognitive Science Manual
Aim:
To write a WebPPL program to demonstrate mathematical functions.
Algorithm:
Program:
Output:
The Value is: 1
Result:
Aim:
To implement a backward chaining reasoning algorithm.
Algorithm:
Program:
class Rule:
def __init__(self, conclusion, premises):
self.conclusion = conclusion
self.premises = premises
class KnowledgeBase:
def __init__(self):
self.rules = []
return False
# Example usage:
if __name__ == "__main__":
# Create a knowledge base
kb = KnowledgeBase()
# 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:
Result:
Thus the program for implementing the reasoning algorithm has been
successfully executed.
Ex:3 Developing an Application system using generative model
Aim:
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
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])
# Decoder
latent_inputs = Input(shape=(latent_dim,))
x = Dense(intermediate_dim, activation='relu')(latent_inputs)
outputs = Dense(input_dim, activation='sigmoid')(x)
# 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:
Program:
# 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
# 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
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:
Program:
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
# 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:
Result:
Thus the program for developing an Application using hierarchical model has been
successfully executed.
Ex:6 Application development using Mixture model
Aim:
Algorithm:
Program:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
# 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.