You are on page 1of 13

AD22311-ARTIFICIAL INTELLIGENCE LABORATORY

EX.NO:7 B
DATE:
Implement resolution strategies in First-order logic

AIM :
To develop a Python program for implementing resolution in First-order logic.
ALGORITHM:

1. Defines a class Clause that represents a logical clause containing a set of literals.
2. Takes a literal and negates it if it's not already negated (using the "not" prefix).
3. Takes two clauses and attempts to resolve them by finding complementary literals. It generates
resolvents by creating a new clause that includes all literals except for the complementary pair.
4.This function initializes a knowledge base with facts and a hypothesis to prove. It uses the
resolution rule in a loop, attempting to derive new clauses from existing ones until a contradiction
(empty clause) is found or no new clauses can be derived.
5. A list of facts in the knowledge base provided as input.
6. The prove_likes_peanut function aims to prove whether John likes peanuts (("likes", "john",
"peanut")) or not (("not", ("likes", "john", "peanut"))) based on the facts and resolution inference. If
it finds a contradiction (an empty clause), it concludes that John's liking or not liking peanuts is
true, depending on the contradiction found.

PROGRAM:

Class Clause:

Def __init__(self, literals):

Self.literals = set(literals)

Def __repr__(self):

Return f”Clause({self.literals})”

Def negate_literal(literal):

If literal[0] == “not”:

Return literal[1]

Else:

Return (“not”, literal)

Def resolve(clause1, clause2):

Resolvents = set()

Roll Number: 2127220502005 Page No.:


For literal in clause1.literals:

Negated_literal = negate_literal(literal)

If negated_literal in clause2.literals:

Resolvent = Clause(

(x for x in (clause1.literals | clause2.literals) if x != literal and x != negated_literal)

Resolvents.add(resolvent)

Return resolvents

Def prove_likes_peanut(facts):

# Represent facts in the knowledge base

Knowledge_base = [

Clause([(“likes”, “john”, “peanut”)]),

Clause([(“not”, (“likes”, “john”, “peanut”))])

# Hypothesis to be proved

Hypothesis = [(“likes”, “john”, “peanut”)]

# Resolution loop

While True:

New_clauses = set()

For I in range(len(knowledge_base)):

For j in range(I + 1, len(knowledge_base)):

Resolvents = resolve(knowledge_base[i], knowledge_base[j])

New_clauses.update(resolvents)

If Clause([]) in new_clauses:

Return False # Contradiction found, hypothesis is true

Roll Number: 2127220502005 Page No.:


If not new_clauses.issubset(set(knowledge_base)):

Knowledge_base.extend(new_clauses)

Else:

Return True # No new clauses, hypothesis is false

# Facts in the knowledge base

Facts = [

(“likes”, “john”, “peanut”),

# Add more facts as needed

# Prove the hypothesis

Result = prove_likes_peanut(facts)

# Print the result

If result:

Print(“John likes peanuts.”)

Else:

Print(“Contradiction found. John does not like peanuts.”)

SAMPLE INPUT AND OUTPUT:

John likes peanuts

RESULT :
The Python program to implement resolution in first order logic was developed and
executed successfully.

Roll Number: 2127220502005 Page No.:


AD22311-ARTIFICIAL INTELLIGENCE LABORATORY

EX.NO:10
DATE:
Implementation of policy search in Reinforcement learning

AIM :
To develop a Python program for implementing policy search in Reinforcement Learning.

ALGORITHM:

1.Initialize the policy with random weights.


2.Reset the environment to its initial state.
3.Collect episode-specific states, actions, and rewards until the episode terminates.
4.Use the policy to select actions based on the current state.
5.Transition to the next state based on the selected action and collect the rreward.
6.After an episode terminate, compute the discounted rewards for each time step of the episode.
7.After collecting an episode’s experience, compute the gradient of the policy with respect to the
collected states and the discounted rewards.
8.Update the policy weights using the gradient and a specified learning rate.
9.Continue the above steps for a set number of episodes.

PROGRAM:

import numpy as np
import gym

class Policy:
def __init__(self, state_size, action_size):
self.weights = np.random.rand(state_size, action_size)

def get_action(self, state):


logits = np.dot(state, self.weights)
probabilities = self.softmax(logits)
action = np.random.choice(len(probabilities), p=probabilities)
return action

def softmax(self, x):


exp_x = np.exp(x - np.max(x))
return exp_x / exp_x.sum(axis=0, keepdims=True)

def compute_discounted_rewards(rewards, gamma=0.99):


discounted_rewards = np.zeros_like(rewards, dtype=np.float32)
running_add = 0
for t in reversed(range(len(rewards))):
running_add = running_add * gamma + rewards[t]
discounted_rewards[t] = running_add
return discounted_rewards

def policy_search(env, policy, num_episodes=1000, learning_rate=0.01):

Roll Number: 2127220502005 Page No.:


state_size = env.observation_space.shape[0]
action_size = env.action_space.n

for episode in range(num_episodes):


state = env.reset()
done = False
episode_states, episode_actions, episode_rewards = [], [], []

while not done:


action = policy.get_action(state)
next_state, reward, done, _ = env.step(action)

episode_states.append(state)
episode_actions.append(action)
episode_rewards.append(reward)

state = next_state

discounted_rewards = compute_discounted_rewards(episode_rewards)
episode_states = np.vstack(episode_states)
episode_actions = np.array(episode_actions)

# Policy gradient update


gradient = np.dot(episode_states.T, discounted_rewards[:, None]) # Use None to add an axis
policy.weights += learning_rate * gradient

total_reward = sum(episode_rewards)
print(f"Episode {episode + 1}/{num_episodes}, Total Reward: {total_reward}")

if __name__ == "__main__":
env = gym.make("CartPole-v1")
state_size = env.observation_space.shape[0]
action_size = env.action_space.n

policy = Policy(state_size, action_size)


policy_search(env, policy)

SAMPLE INPUT AND OUTPUT:

Episode 1/10, Total Reward: 28.0


Episode 2/10, Total Reward: 14.0
Episode 3/10, Total Reward: 9.0
Episode 4/10, Total Reward: 25.0
Episode 5/10, Total Reward: 13.0
Episode 6/10, Total Reward: 10.0
Episode 7/10, Total Reward: 18.0
Episode 8/10, Total Reward: 14.0
Episode 9/10, Total Reward: 18.0
Episode 10/10, Total Reward: 12.0

RESULT :
The Python program to implement policy search in Reinforcement Learning was

Roll Number: 2127220502005 Page No.:


developed and executed successfully.

Roll Number: 2127220502005 Page No.:


CS22311-DATABASE MANAGEMENT LABORATORY

EX.NO:

DATE:
PERSONAL BLOG MANAGEMENT

AIM
To create a dynamic and user-centric Personal blogging website using

PHP,MYSQL,HTML,JAVASCRIPT and CSS.

MODULES

User Authentication Module:


• User Registration: Allows visitors to create new accounts by providing necessary
details like username, email, password, etc. Validates and securely stores user
information in the database after ensuring uniqueness and validity of inputs.
• Login and Logout Functionality: Provides a login page where registered users can
authenticate themselves using their credentials. Upon successful login, generates and
manages session tokens to keep users logged in across pages until logout.
• Security Measures: Implements encryption techniques (e.g., bcrypt) to securely store
and manage user passwords. Handles password hashing and salting to prevent
unauthorized access. Ensures data validation and sanitization to prevent common
vulnerabilities such as SQL injection or cross-site scripting (XSS).

Dashboard Module:
• Personalized Interface:Upon successful login, redirects users to a personalized
dashboard where they can manage their blogging activities.
• Blog Management: Allows users to create new blog posts, providing text editors with
formatting options (e.g., bold, italics, images) to compose rich content. Enables editing,
updating, and deleting existing blog posts.
• Customization Options: Offers settings for users to manage their profiles, change
passwords, upload avatars, set preferences (e.g., theme, language), and manage other
personal information related to their accounts.

Blog Management Module:


• Content Creation: Enables users to write and publish blog posts, including
functionalities to add titles, content, images, and tags/categories for organization and
search purposes.
• Editing and Updating: Provides options to edit or update existing blog posts, allowing
authors to modify content, add new information, or make revisions as needed.
• Organizational Features: Includes features for categorizing and tagging blog posts,
making it easier for users to organize and classify their content. Allows sorting and
filtering of posts based on categories or tags for better navigation and retrieval.

Roll Number: 2127220502005 Page No.:


OUTPUT

• Logging into Personal Blogging website

• Entering User Personal Details

Roll Number: 2127220502005 Page No.:


• After updating user personal details

RESULT :

The a dynamic and user-centric Personal blogging website using


PHP,MYSQL,HTML,JAVASCRIPT and CSS is implemented successfully.

Roll Number: 2127220502005 Page No.:


CS22311-DATABASE MANAGEMENT SYSTEM LABORATORY
DATE:
EX.NO:

CASE STUDY ON BIG DATA AND NoSQL

AIM:
To study the concepts of Big Data and NoSQL.

BIG DATA:

Big Data in DBMS represents a shift in how organizations handle data. It involves adopting
technologies and strategies that can cope with the challenges posed by the volume, velocity,
variety, and other characteristics of large and diverse datasets. Technologies such as Hadoop,
NoSQL databases, and distributed computing frameworks play a crucial role in addressing
these challenges and unlocking the potential value within Big Data.

• Volume
Regular databases work well with organized information in small amounts but
struggle with the immense data produced today. Big Data, on the other hand, manages
huge volumes, handling all types of data—organized, semi-organized, or
unorganized—using technologies like Hadoop and NoSQL databases.

• Velocity
Velocity in Big Data refers to the speed at which data is generated, processed, and
analyzed in real-time. Technologies like Apache Spark and stream processing
frameworks allow organizations to handle high-velocity data.

• Variety
Regular databases handle organized data but face challenges with messy or partially
organized information. Big Data deals with all types of data—organized, messy, or
partially organized. Databases like MongoDB and Cassandra in the Big Data world
are built to handle these different data types.

• Veracity
Veracity in Big Data refers to the quality and trustworthiness of the data. Data
cleansing and validation processes are crucial in Big Data systems to ensure accurate
and reliable insights.

• Value
The ultimate goal of Big Data is to extract valuable insights from large and diverse
datasets. Technologies like data lakes and advanced analytics tools help organizations
derive meaningful value from their data.

• Scalability
Regular databases can be hard and costly to scale. Increasing power on a single
Roll No:2127220502005 Page |
machine (vertical scaling) has limits. Big Data tech is built for horizontal scalability.
Horizontal scalability is more flexible and can handle increased demand by adding
more machines, making it a preferred approach for large-scale systems.

• Flexibility
Regular databases need a fixed structure called a schema, which can be tough to
change when the data structure evolves. In Big Data, NoSQL databases are common,
offering flexibility without a fixed schema. They handle changes in data structures
seamlessly.

• Distributed Computing
Regular databases might use a single-server setup, restricting their capacity to spread
computing tasks. In Big Data, solutions use distributed computing, managing data
processing and analysis across numerous nodes or clusters. This ensures efficient
resource use.

Case Study

TechTrends is an online e-commerce platform that sells a variety of tech gadgets and
electronic devices. The company has been experiencing significant growth in customer
transactions and data volume.

Challenges:

• Data Volume: Traditional database struggles with growing customer data (purchases,
browsing, reviews).
• Real-time Analytics: TechTrends aims for instant insights into customer behavior for
personalized recommendations and improved marketing.
• Data Variety: Handling diverse data types – structured (profiles, transactions) and
unstructured (reviews, social interactions).

Implementation of Big Data:

• Database Restructuring: TechTrends shifts from traditional relational DB to


NoSQL (e.g., MongoDB) for efficient handling of diverse data types.
• Scalable Infrastructure: Adopting cloud services (AWS, Azure), TechTrends
ensures scalable infrastructure for horizontal scaling to meet growing data and user
demands.
• Real-time Analytics: Using Apache Kafka, TechTrends establishes a real-time
analytics pipeline for immediate customer interaction analysis, enabling prompt
responses to trends.
• Machine Learning for Personalization: Employing machine learning, TechTrends
analyzes customer behavior for personalized product recommendations and targeted
marketing.
• Data Lake for Unstructured Data: To manage unstructured data (reviews, social
interactions), TechTrends sets up a data lake (e.g., using Apache Hadoop) for efficient
storage and retrieval.
Roll No:2127220502005 Page |
Results

• Improved Performance: Migration to NoSQL and scalable infrastructure boosts e-


commerce platform performance for quick customer data access.
• Real-time Insights: Real-time analytics provides immediate customer behavior
insights, aiding data-driven decisions and swift responses to market trends.
• Enhanced Customer Experience: Machine learning-driven personalized
recommendations elevate customer experience, fostering increased satisfaction and
loyalty.
• Adaptability to Data Growth: Scalable infrastructure and a data lake ensure
seamless adaptation to growing data volume and variety from an expanding customer
base.

NoSQL:

NoSQL, which stands for "Not Only SQL," is a category of database systems that depart from
the traditional relational database management system (RDBMS) model. NoSQL databases
are designed to handle diverse and dynamic data types, offering flexibility and scalability
beyond what traditional relational databases provide.

• Schema-flexibility: NoSQL databases are schema-flexible, avoiding the need for a


rigid structure, unlike traditional relational databases. This flexibility allows easy
adaptation to changes in data structure without altering the database schema.
• Data Models:
NoSQL databases support diverse data models:
Document-Oriented: Flexible storage in JSON-like documents (e.g., MongoDB).
Key-Value Stores: Simple key-value pairs (e.g., Redis).
Column-Family Stores: Column-oriented for analytical queries (e.g., Apache
Cassandra).
Graph Databases: Designed for managing relationships (e.g., Neo4j).
• Scalability: Designed for horizontal scalability, NoSQL databases can scale by adding
more machines or nodes, distributing the workload across a server cluster as data and
user loads increase.
• High Performance: Optimized for specific use cases, many NoSQL databases excel
in tasks like read and write operations, crucial for quickly processing massive data
volumes.
• BASE Model: NoSQL databases often adhere to the BASE model as an alternative to
the strict ACID properties. BASE allows for more relaxed consistency models,
recognizing practical challenges in achieving absolute consistency in distributed
systems.

Roll No:2127220502005 Page |


Case Study

A thriving e-commerce platform, dealing with a burgeoning customer base, faces critical data
challenges with its traditional database system. The need for handling diverse data, scalability
concerns, and the aspiration for real-time insights drive the decision to explore advanced
database solutions.

Challenges

• Data Variety: The e-commerce giant manages a wealth of data types, ranging from
customer profiles and purchase history to reviews and clickstream data. The existing
traditional databases struggle to efficiently handle this diverse mix, impacting data
processing speed and adaptability.
• Scalability Issues: As the customer base expands, the traditional database encounters
challenges in scaling horizontally. This leads to performance bottlenecks during peak
times, affecting the user experience and potentially hindering business growth.
• Real-time Analytics: The company recognizes the growing importance of real-time
insights. To stay competitive, they aim to understand customer behavior instantly,
facilitating personalized recommendations and targeted marketing strategies for a
more dynamic and responsive customer experience..

Implementation using NoSQL

• Data Variety Solution: Adopts a NoSQL database (e.g., MongoDB) to handle


diverse data types seamlessly. The schema flexibility of NoSQL accommodates the
variability in data structures, allowing for efficient storage and retrieval.
• Scalability Enhancement: Shifts to a scalable cloud infrastructure (e.g., AWS or
Azure) to address scalability concerns. The move allows for horizontal scaling,
ensuring the ability to handle increased data loads during peak periods without
compromising performance.
• Real-time Analytics Implementation: Implements a real-time analytics pipeline
using Apache Kafka to process and analyze customer behavior data immediately. This
empowers the company to make data-driven decisions on-the-fly and offer
personalized recommendations in real-time.

Results
• Efficient Data Handling: The NoSQL database efficiently manages diverse data
types, overcoming the limitations of traditional databases. This ensures smoother data
processing and improved adaptability to evolving data structures.
• Scalability Success: The transition to a scalable cloud infrastructure resolves
horizontal scaling issues. The platform can now seamlessly expand to accommodate
the growing customer base, preventing performance bottlenecks during peak usage.
• Real-time Customer Insights: The implementation of real-time analytics provides
the company with immediate insights into customer behavior. This translates into the
ability to offer personalized recommendations and execute targeted marketing
strategies in real-time, enhancing the overall customer experience.

Roll No:2127220502005 Page |

You might also like