SC - LAB
SC - LAB
LAB MANUVAL
STUDENT NAME :
REGISTER NUMBER :
PROGRAMME : UG
PRACTICAL EXERCISES:
algorithm.
AIM :
PROGRAM :
AIM :
PROGRAM :
import numpy as np
class DiscretePerceptron:
def __init__(self, input_size):
self.weights = np.zeros(input_size)
self.bias = 0
def predict(self, inputs):
activation = np.dot(self.weights, inputs) + self.bias
return 1 if activation > 0 else 0
def train(self, inputs, target, learning_rate=0.1, epochs=100):
for _ in range(epochs):
for x, y in zip(inputs, target):
prediction = self.predict(x)
error = y - prediction
self.weights += learning_rate * error * x
self.bias += learning_rate * error
print("Training completed!")
print("Final Weights:", self.weights)
print("Final Bias:", self.bias)
def main():
class_0 = np.array([[2, 3], [3, 2], [1, 1]])
class_1 = np.array([[5, 7], [6, 8], [7, 6]])
inputs = np.vstack((class_0, class_1))
targets = np.array([0, 0, 0, 1, 1, 1])
perceptron = DiscretePerceptron(input_size=2)
perceptron.train(inputs, targets)
test_data = np.array([[4, 5], [3, 4], [6, 7]])
for data in test_data:
prediction = perceptron.predict(data)
if prediction == 0:
print(f"Data {data} belongs to class 0")
else:
print(f"Data {data} belongs to class 1")
if __name__ == "__main__":
main()
OUTPUT :
Training completed!
Final Weights: [-0.1 0.5]
Final Bias: -1.3
Data [4 5] belongs to class 1
Data [3 4] belongs to class 1
Data [6 7] belongs to class 1
RESULT :
AIM :
PROGRAM :
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
input_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
target_data = np.array([[0], [1], [1], [0]])
input_size = 2
hidden_size = 2
output_size = 1
learning_rate = 0.1
epochs = 10000
hidden_weights = np.random.uniform(size=(input_size, hidden_size))
output_weights = np.random.uniform(size=(hidden_size,
output_size))
for _ in range(epochs):
hidden_layer_activation = np.dot(input_data, hidden_weights)
hidden_layer_output = sigmoid(hidden_layer_activation)
output_layer_activation = np.dot(hidden_layer_output,
output_weights)
predicted_output = sigmoid(output_layer_activation)
error = target_data - predicted_output
output_delta = error * sigmoid_derivative(predicted_output)
hidden_layer_error = output_delta.dot(output_weights.T)
hidden_layer_delta = hidden_layer_error *
sigmoid_derivative(hidden_layer_output)
output_weights += hidden_layer_output.T.dot(output_delta) *
learning_rate
hidden_weights += input_data.T.dot(hidden_layer_delta) *
learning_rate
test_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
print("Testing Results:")
for data in test_data:
hidden_layer_activation = np.dot(data, hidden_weights)
hidden_layer_output = sigmoid(hidden_layer_activation)
output_layer_activation = np.dot(hidden_layer_output,
output_weights)
predicted_output = sigmoid(output_layer_activation)
print(f"Input: {data} Predicted Output: {predicted_output[0]}")
OUTPUT :
Testing Results:
Input: [0 0] Predicted Output: 0.1928003136839193
Input: [0 1] Predicted Output: 0.7456280321708408
Input: [1 0] Predicted Output: 0.7456333725827692
Input: [1 1] Predicted Output: 0.3316986355682776
RESULT :
AIM :
PROGRAM :
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
data = np.random.rand(100, 2)
grid_size = (10, 10)
input_dim = 2
learning_rate = 0.2
num_epochs = 1000
weight_matrix = np.random.rand(grid_size[0], grid_size[1],
input_dim)
for epoch in range(num_epochs):
for input_vector in data:
distances = np.linalg.norm(weight_matrix - input_vector, axis=-
1)
bmu_coords = np.unravel_index(np.argmin(distances),
distances.shape)
for i in range(grid_size[0]):
for j in range(grid_size[1]):
distance_to_bmu = np.linalg.norm(np.array([i, j]) -
np.array(bmu_coords))
influence = np.exp(-distance_to_bmu ** 2 / (2 * (epoch + 1)
** 2))
weight_matrix[i, j] += influence * learning_rate *
(input_vector - weight_matrix[i, j])
cluster_map = np.zeros((grid_size[0], grid_size[1]), dtype=int)
for i in range(grid_size[0]):
for j in range(grid_size[1]):
distances = np.linalg.norm(data - weight_matrix[i, j], axis=-1)
cluster_map[i, j] = np.argmin(distances)
plt.figure(figsize=(8, 8))
plt.pcolormesh(cluster_map, cmap='viridis', edgecolors='k')
plt.colorbar(label='Cluster')
plt.scatter(data[:, 0] * grid_size[0], data[:, 1] * grid_size[1],
color='red', label='Data points', alpha=0.7)
plt.legend()
plt.title('Self-Organizing Map Clustering')
plt.xlabel('Grid X')
plt.ylabel('Grid Y')
plt.show()
OUTPUT :
RESULT :
AIM :
PROGRAM :
import random
def fitness_function(x):
return -x**2 + 6*x + 9
def initialize_population(pop_size, lower_bound, upper_bound):
return [random.uniform(lower_bound, upper_bound) for _ in
range(pop_size)]
def select_parents(population):
total_fitness = sum(fitness_function(individual) for individual in
population)
roulette_wheel = [fitness_function(individual) / total_fitness for
individual in population]
parent1 = random.choices(population, weights=roulette_wheel)[0]
parent2 = random.choices(population, weights=roulette_wheel)[0]
return parent1, parent2
def crossover(parent1, parent2, crossover_prob=0.7):
if random.random() < crossover_prob:
crossover_point = random.randint(0, 1)
child1 = (parent1 + parent2) / 2
child2 = (parent1 + parent2) / 2
return child1, child2
else:
return parent1, parent2
def mutate(individual, mutation_prob=0.01):
if random.random() < mutation_prob:
individual += random.uniform(-1,1)
return individual
def genetic_algorithm(generations, pop_size, lower_bound,
upper_bound):
population = initialize_population(pop_size, lower_bound,
upper_bound)
for gen in range(generations):
new_population = []
while len(new_population) < pop_size:
parent1, parent2 = select_parents(population)
child1, child2 = crossover(parent1, parent2)
child1 = mutate(child1)
child2 = mutate(child2)
new_population.extend([child1, child2])
population = new_population
best_individual = max(population, key=fitness_function)
print(f"Generation {gen+1}: Best individual - {best_individual},
Fitness - {fitness_function(best_individual)}")
return max(population, key=fitness_function)
if __name__ == "__main__":
generations = 50
pop_size = 100
lower_bound = -10
upper_bound = 10
best_solution = genetic_algorithm(generations, pop_size,
lower_bound, upper_bound)
print(f"Best solution found: {best_solution}, Fitness:
{fitness_function(best_solution)}")
OUTPUT :
RESULT :
AIM :
PROGRAM :
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
x, y, z = ctrl.Antecedent(np.arange(-10, 10, 0.1), 'x'),
ctrl.Antecedent(np.arange(-10, 10, 0.1), 'y'),
ctrl.Consequent(np.arange(-1, 1, 0.01), 'z')
x['low'], x['high'] = fuzz.trapmf(x.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(x.universe, [0, 2.5, 5, 10])
y['low'], y['high'] = fuzz.trapmf(y.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(y.universe, [0, 2.5, 5, 10])
z['neg'], z['pos'] = fuzz.trapmf(z.universe, [-1, -0.75, -0.5, -0.25]),
fuzz.trapmf(z.universe, [0.25, 0.5, 0.75, 1])
system = ctrl.ControlSystem([ctrl.Rule(x['low'] & y['low'], z['neg']),
ctrl.Rule(x['high'] & y['high'], z['pos'])])
sim = ctrl.ControlSystemSimulation(system)
sim.input['x'], sim.input['y'] = 3, 4
sim.compute()
print(f'Fuzzy output: {sim.output["z"]}')
print(f'Actual output: {np.sin(np.sqrt(3**2 + 4**2))}')
OUTPUT :
RESULT :
AIM :
PROGRAM :
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
x, y, z, output = ctrl.Antecedent(np.arange(-10, 10, 0.1), 'x'),
ctrl.Antecedent(np.arange(-10, 10, 0.1), 'y'),
ctrl.Antecedent(np.arange(-10, 10, 0.1), 'z'),
ctrl.Consequent(np.arange(-100, 100, 0.1), 'output')
x['low'], x['high'] = fuzz.trapmf(x.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(x.universe, [0, 2.5, 5, 10])
y['low'], y['high'] = fuzz.trapmf(y.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(y.universe, [0, 2.5, 5, 10])
z['low'], z['high'] = fuzz.trapmf(z.universe, [-10, -5, -2.5, 0]),
fuzz.trapmf(z.universe, [0, 2.5, 5, 10])
output['low'], output['high'] = fuzz.trapmf(output.universe, [-100, -50,
-25, 0]), fuzz.trapmf(output.universe, [0, 25, 50, 100])
rule1, rule2 = ctrl.Rule(x['low'] & y['low'] & z['low'], output['low']),
ctrl.Rule(x['high'] & y['high'] & z['high'], output['high'])
system = ctrl.ControlSystem([rule1, rule2])
sim = ctrl.ControlSystemSimulation(system)
x_val, y_val, z_val = 3, 4, 2
sim.input['x'], sim.input['y'], sim.input['z'] = x_val, y_val, z_val
sim.compute()
fuzzy_output = sim.output["output"]
print(f'Fuzzy output: {fuzzy_output}')
actual_output = x_val**2 + 2*y_val**2 - 3*z_val**2 +
2*x_val*y_val - z_val
print(f'Actual output: {actual_output}')
OUTPUT :
RESULT :