Page 316 - Touhpad Ai
P. 316
Section B
Answer any two questions.
Each program should be written in such a way that it clearly depicts the logic of the problem.
This can be achieved by using mnemonic names and comments in the program.
(Flowcharts and Algorithms are not required.)
The programs must be written in Python
Question 6
33. Create a Python script to train a linear regression model using the NumPy library to predict a car’s fuel efficiency
(in miles per gallon) based on its engine size (in liters). You can assume your own dataset. (10)
Ans. # Linear Regression using NumPy
# Predicting Car Fuel Efficiency (mpg)
# based on Engine Size (liters)
import numpy as np
# 1. Create a simple dataset
# Engine size in liters (independent variable X)
engine_size = np.array([1.0, 1.3, 1.5, 1.8, 2.0, 2.4, 3.0, 3.5])
# Fuel efficiency in miles per gallon (dependent variable Y)
mpg = np.array([42, 38, 35, 31, 28, 24, 20, 17])
# 2. Calculate means of X and Y
x_mean = np.mean(engine_size)
y_mean = np.mean(mpg)
# 3. Compute slope (b1) and intercept (b0)
# Using the formulas:
# b1 = Σ((x - x̄)(y - ȳ)) / Σ((x - x̄)²)
# b0 = ȳ - b1 * x̄
numerator = np.sum((engine_size - x_mean) * (mpg - y_mean))
denominator = np.sum((engine_size - x_mean) ** 2)
b1 = numerator / denominator
b0 = y_mean - b1 * x_mean
print(f”Regression Equation: mpg = {b0:.2f} + {b1:.2f} × engine_size”)
# 4. Predict mpg for a new engine size
engine_new = 2.2
predicted_mpg = b0 + b1 * engine_new
print(f”Predicted fuel efficiency for {engine_new} L engine: {predicted_mp
g:.2f} mpg”)
# 5. Evaluate fit using R-squared
y_pred = b0 + b1 * engine_size
ss_total = np.sum((mpg - y_mean) ** 2)
314 Touchpad Artificial Intelligence - XI

