0% found this document useful (0 votes)
20 views13 pages

Exe 1

The document discusses using fuzzy logic to control a fan's speed based on temperature and humidity inputs. It defines fuzzy membership functions for temperature, humidity and fan speed, establishes fuzzy rules relating the inputs and output, simulates the fuzzy controller and prints the resulting fan speed.

Uploaded by

jaya pandi
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)
20 views13 pages

Exe 1

The document discusses using fuzzy logic to control a fan's speed based on temperature and humidity inputs. It defines fuzzy membership functions for temperature, humidity and fan speed, establishes fuzzy rules relating the inputs and output, simulates the fuzzy controller and prints the resulting fan speed.

Uploaded by

jaya pandi
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/ 13

Exe 1:

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# Example dataset
temperature = np.arange(0, 101, 1)
humidity = np.arange(0, 101, 1)
fan_speed = np.arange(0, 101, 1)

# Define fuzzy variables


temp = ctrl.Antecedent(temperature, 'temperature')
humid = ctrl.Antecedent(humidity, 'humidity')
speed = ctrl.Consequent(fan_speed, 'fan_speed')

# Define fuzzy membership functions


temp['low'] = fuzz.trimf(temp.universe, [0, 0, 50])
temp['medium'] = fuzz.trimf(temp.universe, [0, 50, 100])
temp['high'] = fuzz.trimf(temp.universe, [50, 100, 100])

humid['low'] = fuzz.trimf(humid.universe, [0, 0, 50])


humid['medium'] = fuzz.trimf(humid.universe, [0, 50, 100])
humid['high'] = fuzz.trimf(humid.universe, [50, 100, 100])

speed['slow'] = fuzz.trimf(speed.universe, [0, 0, 50])


speed['medium'] = fuzz.trimf(speed.universe, [0, 50, 100])
speed['fast'] = fuzz.trimf(speed.universe, [50, 100, 100])

# Define fuzzy rules


rule1 = ctrl.Rule(temp['low'] | humid['low'], speed['slow'])
rule2 = ctrl.Rule(temp['medium'] | humid['medium'], speed['medium'])
rule3 = ctrl.Rule(temp['high'] | humid['high'], speed['fast'])

# Create control system


fan_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
fan_speed_ctrl = ctrl.ControlSystemSimulation(fan_ctrl)

# Input values
fan_speed_ctrl.input['temperature'] = 35
fan_speed_ctrl.input['humidity'] = 70

# Compute output
fan_speed_ctrl.compute()

# Print output
print("Fan speed:", fan_speed_ctrl.output['fan_speed'])
speed.view(sim=fan_speed_ctrl)
Output:

Fan speed: 51.39291465378427


Exe 2:

import numpy as np

class DiscretePerceptron:
def __init__(self, input_size, learning_rate=0.1, epochs=100):
self.weights = np.zeros(input_size + 1) # +1 for the bias
self.learning_rate = learning_rate
self.epochs = epochs

def activation_function(self, x):


return 1 if x >= 0 else 0

def predict(self, inputs):


summation = np.dot(inputs, self.weights[1:]) + self.weights[0] # dot product + bias
return self.activation_function(summation)

def train(self, training_inputs, labels):


for _ in range(self.epochs):
for inputs, label in zip(training_inputs, labels):
prediction = self.predict(inputs)
self.weights[1:] += self.learning_rate * (label - prediction) * inputs
self.weights[0] += self.learning_rate * (label - prediction) # update bias

# Generate sample dataset


training_inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
labels = np.array([0, 1, 1, 1]) # OR function

# Create and train the perceptron


perceptron = DiscretePerceptron(input_size=2)
perceptron.train(training_inputs, labels)

# Test the perceptron


test_inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
print("Test Inputs | Predictions|")
print("-----------------------------")
for inputs in test_inputs:
prediction = perceptron.predict(inputs)
print(f"{inputs} | {prediction} |")
print("-----------------------------")

Ouput:
Exe 3:

import numpy as np

class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size, learning_rate=0.1):
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size

# Initialize weights
self.weights_input_hidden = np.random.uniform(-1, 1, (self.input_size, self.hidden_size))
self.weights_hidden_output = np.random.uniform(-1, 1, (self.hidden_size, self.output_size))

# Initialize biases
self.bias_hidden = np.zeros(self.hidden_size)
self.bias_output = np.zeros(self.output_size)

self.learning_rate = learning_rate

def sigmoid(self, x):


return 1 / (1 + np.exp(-x))

def sigmoid_derivative(self, x):


return x * (1 - x)

def forward(self, x):


# Input to hidden layer
hidden_input = np.dot(x, self.weights_input_hidden) + self.bias_hidden
hidden_output = self.sigmoid(hidden_input)

# Hidden to output layer


output_input = np.dot(hidden_output, self.weights_hidden_output) + self.bias_output
predicted_output = self.sigmoid(output_input)

return predicted_output, hidden_output

def backward(self, x, y, output, hidden_output):


# Backpropagation
output_error = y - output
output_delta = output_error * self.sigmoid_derivative(output)

hidden_error = np.dot(output_delta, self.weights_hidden_output.T)


hidden_delta = hidden_error * self.sigmoid_derivative(hidden_output)

# Update weights and biases


self.weights_hidden_output += np.dot(hidden_output.T, output_delta) * self.learning_rate
self.weights_input_hidden += np.dot(x.T, hidden_delta) * self.learning_rate

self.bias_output += np.sum(output_delta) * self.learning_rate


self.bias_hidden += np.sum(hidden_delta) * self.learning_rate
def train(self, x, y, epochs):
for _ in range(epochs):
output, hidden_output = self.forward(x)
self.backward(x, y, output, hidden_output)

# XOR dataset
X = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])

Y = np.array([[0],
[1],
[1],
[0]])

# Create and train the neural network


np.random.seed(42) # for reproducibility
nn = NeuralNetwork(input_size=2, hidden_size=5, output_size=1, learning_rate=0.1)
nn.train(X, Y, epochs=10000)

# Test the trained model


print("Test predictions:")
for inputs in X:
predicted_output, _ = nn.forward(inputs)
print("\n")
print(f"Input: {inputs},\nPredicted Output: {predicted_output}")

Output:
Exe 4:

import numpy as np
import matplotlib.pyplot as plt
from minisom import MiniSom

# Load an image
image = plt.imread('nature-jpg-format-download-1920x1200-wallpaper-preview.jpg')

# Reshape the image to a 2D array (width * height, 3)


data = np.reshape(image, (image.shape[0] * image.shape[1], 3))

# Normalize the data to values between 0 and 1


data = data / 255.0

# Define the size of the SOM grid


grid_width = 10
grid_height = 10

# Initialize the SOM


som = MiniSom(grid_width, grid_height, 3, sigma=1.0, learning_rate=0.5)

# Train the SOM


som.train_random(data, 1000)

# Get the clustered colors (weights of the SOM)


clustered_colors = som.get_weights()

# Reshape the clustered colors to the original image shape


quantized_image = np.zeros_like(image)
for i in range(image.shape[0]):
for j in range(image.shape[1]):
quantized_image[i, j] = clustered_colors[som.winner(data[i*image.shape[1] + j])]

# Display the original and quantized images


plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(image)
plt.axis('off')

plt.subplot(1, 2, 2)
plt.title('Quantized Image')
plt.imshow(quantized_image)
plt.axis('off')

plt.show()
Output:

Exe 5:

import numpy as np

# Define the function to maximize


def fitness_function(x):
return x**2 - 4*x + 4

# Define the chromosome representation (binary encoding)


def create_chromosome():
return np.random.randint(2, size=4) # 4 bits for encoding x, assuming x in [0, 15]

# Decode chromosome to get the value of x


def decode_chromosome(chromosome):
x=0
for i in range(len(chromosome)):
x += chromosome[i] * 2**i
return x

# Initialize population
def initialize_population(population_size):
population = []
for _ in range(population_size):
population.append(create_chromosome())
return population

# Calculate fitness of each chromosome in the population


def calculate_fitness(population):
fitness_scores = []
for chromosome in population:
x = decode_chromosome(chromosome)
fitness_scores.append(fitness_function(x))
return fitness_scores
# Selection: Roulette wheel selection
def roulette_wheel_selection(population, fitness_scores):
total_fitness = sum(fitness_scores)
probabilities = [score / total_fitness for score in fitness_scores]
selected_indices = np.random.choice(len(population), size=len(population), p=probabilities)
return [population[i] for i in selected_indices]

# Crossover: Single-point crossover


def single_point_crossover(parent1, parent2):
crossover_point = np.random.randint(1, len(parent1))
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
return child1, child2

# Mutation: Bit flip mutation


def bit_flip_mutation(chromosome, mutation_rate):
mutated_chromosome = chromosome.copy()
for i in range(len(mutated_chromosome)):
if np.random.rand() < mutation_rate:
mutated_chromosome[i] = 1 - mutated_chromosome[i] # Flip the bit
return mutated_chromosome

# Genetic algorithm
def genetic_algorithm(population_size, mutation_rate, generations):
population = initialize_population(population_size)
for generation in range(generations):
fitness_scores = calculate_fitness(population)

# Select parents
selected_parents = roulette_wheel_selection(population, fitness_scores)

# Create offspring through crossover


offspring = []
for i in range(0, len(selected_parents), 2):
parent1 = selected_parents[i]
parent2 = selected_parents[i+1]
child1, child2 = single_point_crossover(parent1, parent2)
offspring.append(child1)
offspring.append(child2)

# Apply mutation
for i in range(len(offspring)):
offspring[i] = bit_flip_mutation(offspring[i], mutation_rate)

population = offspring

best_chromosome = max(population, key=lambda x: fitness_function(decode_chromosome(x)))


best_x = decode_chromosome(best_chromosome)
best_fitness = fitness_function(best_x)

return best_x, best_fitness


# Parameters
population_size = 100
mutation_rate = 0.1
generations = 100

# Run the genetic algorithm


best_x, best_fitness = genetic_algorithm(population_size, mutation_rate, generations)

print(f"Optimal solution found: x = {best_x}, Fitness = {best_fitness}")

Output:

Exe 6:

import numpy as np

# Define the fitness function (maximum value of sine function)


def fitness_function(x, y):
return np.sin(x) * np.sin(y)

# Define the chromosome representation


def create_chromosome():
return np.random.uniform(-np.pi, np.pi, size=2) # Random values between -π and π for both x and y

# Initialize population
def initialize_population(population_size):
population = []
for _ in range(population_size):
population.append(create_chromosome())
return population

# Calculate fitness of each chromosome in the population


def calculate_fitness(population):
fitness_scores = []
for chromosome in population:
x, y = chromosome
fitness_scores.append(fitness_function(x, y))
return fitness_scores

# Selection: Roulette wheel selection


def roulette_wheel_selection(population, fitness_scores):
total_fitness = sum(fitness_scores)
probabilities = [max(score / total_fitness, 0) for score in fitness_scores]

# Ensure probabilities sum to 1


sum_probabilities = sum(probabilities)
if sum_probabilities != 0:
probabilities = [prob / sum_probabilities for prob in probabilities]

selected_indices = np.random.choice(len(population), size=len(population), p=probabilities)


return [population[i] for i in selected_indices]

# Crossover: Single-point crossover


def single_point_crossover(parent1, parent2):
crossover_point = np.random.randint(1, len(parent1))
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
return child1, child2

# Mutation: Random mutation within a small range


def mutate(chromosome, mutation_rate, mutation_range):
mutated_chromosome = chromosome.copy()
for i in range(len(mutated_chromosome)):
if np.random.rand() < mutation_rate:
mutated_chromosome[i] += np.random.uniform(-mutation_range, mutation_range)
mutated_chromosome[i] = max(-np.pi, min(mutated_chromosome[i], np.pi)) # Ensure within range
[-π, π]
return mutated_chromosome

# Genetic algorithm
def genetic_algorithm(population_size, mutation_rate, mutation_range, generations):
population = initialize_population(population_size)
for generation in range(generations):
fitness_scores = calculate_fitness(population)

# Select parents
selected_parents = roulette_wheel_selection(population, fitness_scores)

# Create offspring through crossover


offspring = []
for i in range(0, len(selected_parents), 2):
parent1 = selected_parents[i]
parent2 = selected_parents[i+1]
child1, child2 = single_point_crossover(parent1, parent2)
offspring.append(child1)
offspring.append(child2)

# Apply mutation
for i in range(len(offspring)):
offspring[i] = mutate(offspring[i], mutation_rate, mutation_range)

population = offspring

best_chromosome = max(population, key=lambda x: fitness_function(*x))


best_fitness = fitness_function(*best_chromosome)

return best_chromosome, best_fitness

# Parameters
population_size = 100
mutation_rate = 0.1
mutation_range = 0.1
generations = 100

# Run the genetic algorithm


best_chromosome, best_fitness = genetic_algorithm(population_size, mutation_rate, mutation_range,
generations)

# Print formatted output


print(f"Optimal solution found:\n(x, y) = {best_chromosome}\nFitness = {best_fitness}")

Output:

Exe 7:

import numpy as np

# Define the fitness function (maximum value of non-linear function)


def fitness_function(x, y, z):
return np.sin(x) + np.cos(y) + np.tan(z)

# Define the chromosome representation


def create_chromosome():
return np.random.uniform(-np.pi, np.pi, size=3) # Random values between -π and π for x, y, and z

# Initialize population
def initialize_population(population_size):
population = []
for _ in range(population_size):
population.append(create_chromosome())
return population

# Calculate fitness of each chromosome in the population


def calculate_fitness(population):
fitness_scores = []
for chromosome in population:
x, y, z = chromosome
fitness_scores.append(fitness_function(x, y, z))
return fitness_scores
# Selection: Roulette wheel selection
def roulette_wheel_selection(population, fitness_scores):
total_fitness = sum(fitness_scores)
probabilities = [max(score / total_fitness, 0) for score in fitness_scores]

# Ensure probabilities sum to 1


sum_probabilities = sum(probabilities)
if sum_probabilities != 0:
probabilities = [prob / sum_probabilities for prob in probabilities]

selected_indices = np.random.choice(len(population), size=len(population), p=probabilities)


return [population[i] for i in selected_indices]

# Crossover: Single-point crossover


def single_point_crossover(parent1, parent2):
crossover_point = np.random.randint(1, len(parent1))
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:]))
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:]))
return child1, child2

# Mutation: Random mutation within a small range


def mutate(chromosome, mutation_rate, mutation_range):
mutated_chromosome = chromosome.copy()
for i in range(len(mutated_chromosome)):
if np.random.rand() < mutation_rate:
mutated_chromosome[i] += np.random.uniform(-mutation_range, mutation_range)
mutated_chromosome[i] = max(-np.pi, min(mutated_chromosome[i], np.pi)) # Ensure within range
[-π, π]
return mutated_chromosome

# Genetic algorithm
def genetic_algorithm(population_size, mutation_rate, mutation_range, generations):
population = initialize_population(population_size)
for generation in range(generations):
fitness_scores = calculate_fitness(population)

# Select parents
selected_parents = roulette_wheel_selection(population, fitness_scores)

# Create offspring through crossover


offspring = []
for i in range(0, len(selected_parents), 2):
parent1 = selected_parents[i]
parent2 = selected_parents[i+1]
child1, child2 = single_point_crossover(parent1, parent2)
offspring.append(child1)
offspring.append(child2)

# Apply mutation
for i in range(len(offspring)):
offspring[i] = mutate(offspring[i], mutation_rate, mutation_range)
population = offspring

best_chromosome = max(population, key=lambda x: fitness_function(*x))


best_fitness = fitness_function(*best_chromosome)

return best_chromosome, best_fitness

# Parameters
population_size = 100
mutation_rate = 0.1
mutation_range = 0.1
generations = 100

# Run the genetic algorithm


best_chromosome, best_fitness = genetic_algorithm(population_size, mutation_rate, mutation_range,
generations)

# Print formatted output


print("Optimal solution found:")
print(f"x = {best_chromosome[0]}")
print(f"y = {best_chromosome[1]}")
print(f"z = {best_chromosome[2]}")
print(f"Fitness = {best_fitness}")

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy