task7GradedLab2 Mahul Sethi
task7GradedLab2 Mahul Sethi
def target_function(x):
return 2 * x**2 + 3 * x + 4
def generate_data(num_points):
X = np.linspace(0, 10, num_points)
y = np.array([target_function(x) + random.uniform(-1, 1) for x in X])
return X, y
def create_individual():
return [random.uniform(-5, 5), random.uniform(-5, 5), random.uniform(-5, 5)]
population_size = 100
num_generations = 50
Mahul Sethi 1000014223 A(P2)
mutation_rate = 0.1
data = generate_data(50)
children = []
while len(children) < population_size - num_parents:
parent1, parent2 = random.choices(parents, k=2)
crossover_point = random.randint(1, len(parent1) - 1)
child = parent1[:crossover_point] + parent2[crossover_point:]
if random.random() < mutation_rate:
mutation_gene = random.randint(0, len(child) - 1)
child[mutation_gene] = random.uniform(-5, 5)
children.append(child)
a, b, c = best_predictor
print(f"Best Predictor: {a:.2f}x^2 + {b:.2f}x + {c:.2f}")
test_data = generate_data(10)
predictions = [a * x**2 + b * x + c for x in test_data[0]]