rguLAB

DS Lab: all codes + viva

29 record programs. Copy any code; the output, graphs and viva answers are right below it.

Download PDF

Pandas basics

Program 01

Import & export files

Import and export datasets in CSV, Excel and JSON using Pandas.

Run it

Algorithm

1. Start
2. Build a small DataFrame from a dict
3. Write it with to_csv / to_json / to_excel (index=False)
4. Read each file back with read_csv / read_json / read_excel and print
5. Stop

Program

import pandas as pd

df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})
df.to_csv('01.csv', index=False)
df.to_json('01.json', orient='records')
df.to_excel('01.xlsx', index=False)

print("CSV Data:\n", pd.read_csv('01.csv'))
print("\nJSON Data:\n", pd.read_json('01.json'))
print("\nExcel Data:\n", pd.read_excel('01.xlsx'))

Output

CSV Data:
       Name  Age
0    Alice   25
1      Bob   30
2  Charlie   35

JSON Data:
       Name  Age
0    Alice   25
1      Bob   30
2  Charlie   35

Excel Data:
       Name  Age
0    Alice   25
1      Bob   30
2  Charlie   35

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Viva: what does each line do?

  1. df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. df.to_csv('01.csv', index=False)

    to_csv() writes the DataFrame to a .csv file. index=False stops pandas saving the row numbers as an extra column.

  3. df.to_json('01.json', orient='records')

    to_json() writes the DataFrame to a .json file. orient='records' writes JSON as one object per row.

  4. df.to_excel('01.xlsx', index=False)

    to_excel() writes the DataFrame to an .xlsx file. index=False stops pandas saving the row numbers as an extra column.

  5. print("CSV Data:\n", pd.read_csv('01.csv'))

    Prints "CSV Data:" with the result. pd.read_csv() loads a .csv file into a DataFrame.

  6. print("\nJSON Data:\n", pd.read_json('01.json'))

    Prints "JSON Data:" with the result. pd.read_json() loads a .json file into a DataFrame.

  7. print("\nExcel Data:\n", pd.read_excel('01.xlsx'))

    Prints "Excel Data:" with the result. pd.read_excel() loads an .xlsx sheet into a DataFrame (needs openpyxl).

Viva: concepts

Q. Why pass index=False to to_csv()?

A. So the row numbers are not saved as an extra column. Without it, reading the file back gives you an extra 'Unnamed: 0' column.

Q. Which package does pandas use to write .xlsx files?

A. openpyxl. openpyxl reads and writes .xlsx. xlrd only reads the old .xls format.

Q. to_json(orient='records') writes…

A. A list of row objects: [{...}, {...}]. 'records' gives one JSON object per row, which is the most readable layout.

Viva: "change it to…"

→ Add a City column

df['City'] = ['Delhi', 'Pune', 'Goa']

→ Show only the first 2 rows of the CSV

print(pd.read_csv('01.csv').head(2))

→ Save JSON one object per column instead

df.to_json('01.json')

Program 02

Data preprocessing

Data preprocessing: missing values, duplicates and inconsistent data.

Run it

Algorithm

1. Start
2. Fill missing Age with the median: fillna(df['Age'].median())
3. Remove repeated rows with drop_duplicates()
4. Fix messy text: str.strip().str.title()
5. Turn invalid values (salary ≤ 0) into NaN with where(), then fill with the median
6. Stop

Program

import pandas as pd
import numpy as np

df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Bob', 'David', 'eve '],
                   'Age': [25, np.nan, np.nan, 40, 22],
                   'Salary': [50000, 60000, 60000, -10000, 45000]})

df['Age'] = df['Age'].fillna(df['Age'].median())
df = df.drop_duplicates()
df['Name'] = df['Name'].str.strip().str.title()
s = df['Salary'].where(df['Salary'] > 0)
df['Salary'] = s.fillna(s.median())
print(df)

Output

    Name   Age   Salary
0  Alice  25.0  50000.0
1    Bob  25.0  60000.0
3  David  40.0  50000.0
4    Eve  22.0  45000.0

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Q. Why import numpy as np?

A. numpy: fast arrays and maths. np is just a short name so we can type np.something.

Viva: what does each line do?

  1. df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Bob', 'David', 'eve '],
                       'Age': [25, np.nan, np.nan, 40, 22],
                       'Salary': [50000, 60000, 60000, -10000, 45000]})

    pd.DataFrame builds a table from the dict: each key becomes a column. np.nan is the 'missing value' marker.

  2. df['Age'] = df['Age'].fillna(df['Age'].median())

    fillna() replaces missing values (NaN) with the value you give it. median() is the middle value when sorted; outliers barely move it. Creates (or replaces) df['Age'] with this value.

  3. df = df.drop_duplicates()

    drop_duplicates() removes repeated rows. The result is stored in df.

  4. df['Name'] = df['Name'].str.strip().str.title()

    .str gives string methods (strip, lower, title…) for a whole column. str.strip() removes spaces at both ends of each string. title() capitalises the first letter of each word (or sets a plot title). Creates (or replaces) df['Name'] with this value.

  5. s = df['Salary'].where(df['Salary'] > 0)

    where() keeps values where the condition is True and puts NaN elsewhere. The result is stored in s.

  6. df['Salary'] = s.fillna(s.median())

    fillna() replaces missing values (NaN) with the value you give it. median() is the middle value when sorted; outliers barely move it. Creates (or replaces) df['Salary'] with this value.

  7. print(df)

    Prints the result.

Viva: concepts

Q. What is data preprocessing?

A. Cleaning raw data before analysis: handling missing values, duplicates, wrong types and inconsistent text, so the results are correct.

Q. What does df['Salary'].where(df['Salary'] > 0) return?

A. The same column with non-positive values turned into NaN. where() keeps values where the condition is True and puts NaN everywhere else.

Q. Why fill missing values with the median rather than the mean?

A. The median isn't pulled by outliers like -10000. One bad value drags the mean a lot but barely moves the median.

Q. 'eve ' becomes 'Eve' because of…

A. str.strip().str.title(). strip() removes the spaces at both ends, title() capitalises the first letter.

Viva: "change it to…"

→ Fill Age with the mean instead of the median

df['Age'] = df['Age'].fillna(df['Age'].mean())

→ Just delete rows with missing values

df = df.dropna()

→ Make names UPPERCASE

df['Name'] = df['Name'].str.strip().str.upper()

→ Count missing values first

print(df.isnull().sum())

Program 03

Descriptive statistics

Descriptive statistics: mean, median, mode, variance, std dev, covariance.

Run it

Algorithm

1. Start
2. Make a DataFrame with two numeric columns
3. Call df.mean(), median(), mode(), var(), std()
4. Call df.cov() for the covariance matrix
5. Stop

Program

import pandas as pd

df = pd.DataFrame({'A': [10, 20, 20, 30, 40, 50], 'B': [15, 25, 25, 35, 45, 55]})

print("Mean:\n", df.mean())
print("\nMedian:\n", df.median())
print("\nMode:\n", df.mode())
print("\nVariance:\n", df.var())
print("\nStandard Deviation:\n", df.std())
print("\nCovariance:\n", df.cov())

Output

Mean:
 A    28.333333
B    33.333333
dtype: float64

Median:
 A    25.0
B    30.0
dtype: float64

Mode:
     A   B
0  20  25

Variance:
 A    216.666667
B    216.666667
dtype: float64

Standard Deviation:
 A    14.719601
B    14.719601
dtype: float64

Covariance:
             A           B
A  216.666667  216.666667
B  216.666667  216.666667

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Viva: what does each line do?

  1. df = pd.DataFrame({'A': [10, 20, 20, 30, 40, 50], 'B': [15, 25, 25, 35, 45, 55]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. print("Mean:\n", df.mean())

    Prints "Mean:" with the result. mean() is the average.

  3. print("\nMedian:\n", df.median())

    Prints "Median:" with the result. median() is the middle value when sorted; outliers barely move it.

  4. print("\nMode:\n", df.mode())

    Prints "Mode:" with the result. mode() is the most frequent value; [0] takes the first one.

  5. print("\nVariance:\n", df.var())

    Prints "Variance:" with the result. var() is the variance: the average squared distance from the mean.

  6. print("\nStandard Deviation:\n", df.std())

    Prints "Standard Deviation:" with the result. std() is the standard deviation, the square root of the variance.

  7. print("\nCovariance:\n", df.cov())

    Prints "Covariance:" with the result. cov() gives the covariance matrix: how pairs of columns vary together.

Viva: concepts

Q. Mean vs median?

A. Mean is the average; median is the middle value. The median is better when there are outliers.

Q. pandas df.var() divides by…

A. n − 1 (sample variance). pandas uses ddof=1 by default. NumPy's np.var uses n, so the two give different answers.

Q. Why does df.mode() return a DataFrame, not one number?

A. A column can have more than one mode. If two values tie for most frequent, both are modes, so pandas returns rows.

Q. Standard deviation is…

A. The square root of the variance. std = √var, which puts it back in the same units as the data.

Viva: "change it to…"

→ Only for column A

print(df['A'].mean(), df['A'].median(), df['A'].std())

→ All summary stats at once

print(df.describe())

→ Correlation instead of covariance

print(df.corr())

Program 08

Pandas manipulation

Manipulate and transform datasets using Pandas.

Run it

Algorithm

1. Start
2. Add a column: df['Bonus'] = df['Salary'] * 0.10
3. Filter: df[df['Age'] > 30]
4. Sort: df.sort_values('Salary', ascending=False)
5. Stop

Program

import pandas as pd

df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie', 'David'],
                   'Age': [25, 30, 35, 40],
                   'Salary': [50000, 60000, 70000, 80000]})
df['Bonus'] = df['Salary'] * 0.10
print("After Adding Bonus:\n", df)
print("\nFiltered (Age > 30):\n", df[df['Age'] > 30])
print("\nSorted by Salary:\n", df.sort_values('Salary', ascending=False))

Output

After Adding Bonus:
       Name  Age  Salary   Bonus
0    Alice   25   50000  5000.0
1      Bob   30   60000  6000.0
2  Charlie   35   70000  7000.0
3    David   40   80000  8000.0

Filtered (Age > 30):
       Name  Age  Salary   Bonus
2  Charlie   35   70000  7000.0
3    David   40   80000  8000.0

Sorted by Salary:
       Name  Age  Salary   Bonus
3    David   40   80000  8000.0
2  Charlie   35   70000  7000.0
1      Bob   30   60000  6000.0
0    Alice   25   50000  5000.0

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Viva: what does each line do?

  1. df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie', 'David'],
                       'Age': [25, 30, 35, 40],
                       'Salary': [50000, 60000, 70000, 80000]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. df['Bonus'] = df['Salary'] * 0.10

    Creates (or replaces) df['Bonus'] with this value.

  3. print("After Adding Bonus:\n", df)

    Prints "After Adding Bonus:" with the result.

  4. print("\nFiltered (Age > 30):\n", df[df['Age'] > 30])

    Prints "Filtered (Age > 30):" with the result.

  5. print("\nSorted by Salary:\n", df.sort_values('Salary', ascending=False))

    Prints "Sorted by Salary:" with the result. sort_values() orders rows by a column; ascending=False for largest first. ascending=False sorts from largest to smallest.

Viva: concepts

Q. df[df['Age'] > 30] is called…

A. Boolean indexing (filtering). The inner part makes a True/False Series, and the outer brackets keep the True rows.

Q. How do you sort from highest to lowest?

A. sort_values(..., ascending=False). pandas uses ascending=; Python's sorted() uses reverse=.

Q. Average salary per department is…

A. df.groupby('Dept')['Salary'].mean(). groupby → pick the column → aggregate. A common extension in the exam.

Viva: "change it to…"

→ Bonus of 20%

df['Bonus'] = df['Salary'] * 0.20

→ Salary above 60000

print(df[df['Salary'] > 60000])

→ Sort by age, youngest first

print(df.sort_values('Age'))

→ Average salary

print(df['Salary'].mean())

Statistics

Program 04

Covariance & correlation

Compute and visualize covariance and correlation matrices.

Run it

Algorithm

1. Start
2. Compute df.cov() and df.corr()
3. Make two side-by-side axes: plt.subplots(1, 2, figsize=(12, 5))
4. Draw each matrix with sns.heatmap(..., annot=True, cmap='coolwarm', ax=ax[i])
5. Stop

Program

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': [10, 20, 20, 30, 40, 50],
                   'B': [15, 25, 25, 35, 45, 55],
                   'C': [5, 10, 15, 20, 25, 30]})
print("Covariance Matrix:\n", df.cov())
print("\nCorrelation Matrix:\n", df.corr())

fig, ax = plt.subplots(1, 2, figsize=(12, 5))
sns.heatmap(df.cov(), annot=True, cmap='coolwarm', ax=ax[0]).set_title("Covariance Matrix")
sns.heatmap(df.corr(), annot=True, cmap='coolwarm', ax=ax[1]).set_title("Correlation Matrix")
plt.show()

Output

Covariance Matrix:
             A           B      C
A  216.666667  216.666667  135.0
B  216.666667  216.666667  135.0
C  135.000000  135.000000   87.5

Correlation Matrix:
           A         B         C
A  1.000000  1.000000  0.980469
B  1.000000  1.000000  0.980469
C  0.980469  0.980469  1.000000
Graph 1 produced by DS program 04: Covariance & correlation
Graph · Program 04

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Q. Why import seaborn as sns?

A. seaborn: statistical plots built on matplotlib. sns is just a short name so we can type sns.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Viva: what does each line do?

  1. df = pd.DataFrame({'A': [10, 20, 20, 30, 40, 50],
                       'B': [15, 25, 25, 35, 45, 55],
                       'C': [5, 10, 15, 20, 25, 30]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. print("Covariance Matrix:\n", df.cov())

    Prints "Covariance Matrix:" with the result. cov() gives the covariance matrix: how pairs of columns vary together.

  3. print("\nCorrelation Matrix:\n", df.corr())

    Prints "Correlation Matrix:" with the result. corr() gives the correlation matrix, with values from −1 to 1.

  4. fig, ax = plt.subplots(1, 2, figsize=(12, 5))

    plt.subplots(rows, cols) makes a figure with a grid of boxes (axes) to draw in. figsize=(w, h) sets the figure size in inches. The result is stored in fig, ax.

  5. sns.heatmap(df.cov(), annot=True, cmap='coolwarm', ax=ax[0]).set_title("Covariance Matrix")

    sns.heatmap() colours a matrix; used for correlation or confusion matrices. cov() gives the covariance matrix: how pairs of columns vary together. annot=True writes the number inside each heatmap cell.

  6. sns.heatmap(df.corr(), annot=True, cmap='coolwarm', ax=ax[1]).set_title("Correlation Matrix")

    sns.heatmap() colours a matrix; used for correlation or confusion matrices. corr() gives the correlation matrix, with values from −1 to 1. annot=True writes the number inside each heatmap cell.

  7. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. Covariance vs correlation?

A. Both show how two variables move together. Correlation is scaled to −1…1 and has no units, so it is easier to compare.

Q. Correlation always lies between…

A. −1 and 1. Correlation is covariance scaled by both standard deviations, so it is bounded.

Q. annot=True in sns.heatmap…

A. Writes the number inside each cell. Without annot you only see colours.

Q. Why is corr(A, B) exactly 1.0 here?

A. B is always A + 5, a perfect straight-line relation. Any exact linear relation y = ax + b with a > 0 gives correlation 1.

Viva: "change it to…"

→ Only the correlation heatmap

sns.heatmap(df.corr(), annot=True, cmap='coolwarm')
plt.show()

→ Different colours

cmap='viridis'   # or 'Blues', 'YlGnBu'

Program 05

Normal distributions

Analyze univariate and multivariate normal distributions.

Run it

Algorithm

1. Start
2. Univariate: np.random.normal(mean, std, size)
3. Multivariate: np.random.multivariate_normal(mean_vector, cov_matrix, size)
4. Print sample mean / std / np.cov(..., rowvar=False)
5. Plot a histogram and a scatter side by side
6. Stop

Program

import numpy as np
import matplotlib.pyplot as plt

data = np.random.normal(50, 10, 1000)
multi = np.random.multivariate_normal([50, 30], [[100, 50], [50, 64]], 1000)
print("Univariate Mean:", data.mean(), " Std:", data.std())
print("Multivariate Mean:", multi.mean(axis=0))
print("Multivariate Covariance:\n", np.cov(multi, rowvar=False))

fig, ax = plt.subplots(1, 2, figsize=(12, 5))
ax[0].hist(data, bins=30)
ax[0].set_title("Univariate Normal Distribution")
ax[1].scatter(multi[:, 0], multi[:, 1], alpha=0.5)
ax[1].set_title("Multivariate Normal Distribution")
plt.show()

Output

Univariate Mean: 49.67332303089289  Std: 9.824210693574127
Multivariate Mean: [49.88341838 29.75859401]
Multivariate Covariance:
 [[103.73097274  55.03180105]
 [ 55.03180105  72.89431088]]
Graph 1 produced by DS program 05: Normal distributions
Graph · Program 05

Viva: which module is used and why

Q. Why import numpy as np?

A. numpy: fast arrays and maths. np is just a short name so we can type np.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Viva: what does each line do?

  1. data = np.random.normal(50, 10, 1000)

    np.random generates random numbers for synthetic data. random.normal(mean, std, size) samples from a bell curve. The result is stored in data.

  2. multi = np.random.multivariate_normal([50, 30], [[100, 50], [50, 64]], 1000)

    np.random generates random numbers for synthetic data. multivariate_normal() samples correlated 2-D points from a mean vector and covariance matrix. The result is stored in multi.

  3. print("Univariate Mean:", data.mean(), " Std:", data.std())

    Prints "Univariate Mean:" with the result. mean() is the average. std() is the standard deviation, the square root of the variance.

  4. print("Multivariate Mean:", multi.mean(axis=0))

    Prints "Multivariate Mean:" with the result. mean() is the average. axis=0 works down the rows, axis=1 across the columns.

  5. print("Multivariate Covariance:\n", np.cov(multi, rowvar=False))

    Prints "Multivariate Covariance:" with the result. cov() gives the covariance matrix: how pairs of columns vary together. rowvar=False tells np.cov that columns are variables.

  6. fig, ax = plt.subplots(1, 2, figsize=(12, 5))

    plt.subplots(rows, cols) makes a figure with a grid of boxes (axes) to draw in. figsize=(w, h) sets the figure size in inches. The result is stored in fig, ax.

  7. ax[0].hist(data, bins=30)

    hist() draws a histogram, which shows the distribution of one numeric column. bins sets how many bars a histogram is split into.

  8. ax[0].set_title("Univariate Normal Distribution")

    ax.set_title() names one subplot.

  9. ax[1].scatter(multi[:, 0], multi[:, 1], alpha=0.5)

    scatter() plots x against y as dots, which shows the relationship. alpha=0.5 sets transparency (0 = invisible, 1 = solid).

  10. ax[1].set_title("Multivariate Normal Distribution")

    ax.set_title() names one subplot.

  11. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. What is a normal distribution?

A. A symmetric bell-shaped curve where mean = median = mode. About 68% of values lie within 1 std, 95% within 2 std.

Q. In np.random.normal(50, 10, 1000), what is 10?

A. The standard deviation. The arguments are loc (mean), scale (std) and size.

Q. Why do the numbers change on every run?

A. There is no random seed; add np.random.seed(0). With a fixed seed you get the same samples every time.

Q. With cov [[100, 50], [50, 64]], the std of the 2nd variable is…

A. 8. The diagonal holds the variances, and √64 = 8.

Viva: "change it to…"

→ Mean 100, std 15

data = np.random.normal(100, 15, 1000)

→ Same numbers every run

np.random.seed(0)   # put before generating

→ More bars in the histogram

ax[0].hist(data, bins=50)

Program 06

Hypothesis testing

Hypothesis testing using SciPy.

Run it

Algorithm

1. Start
2. State H₀: the population mean is 50
3. T, p = stats.ttest_1samp(sample, 50)
4. If p < 0.05, reject H₀; otherwise fail to reject
5. Stop

Program

from scipy import stats

t, p = stats.ttest_1samp([48, 52, 51, 49, 50, 53, 47, 52, 51, 50], 50)
print("T-statistic:", t)
print("P-value:", p)
print("Reject the null hypothesis" if p < 0.05 else "Fail to reject the null hypothesis")

Output

T-statistic: 0.5023310149673481
P-value: 0.6274948659508928
Fail to reject the null hypothesis

Viva: which module is used and why

Q. Why stats from scipy?

A. scipy: scientific maths, including stats. scipy.stats holds the statistical tests and distributions.

Viva: what does each line do?

  1. t, p = stats.ttest_1samp([48, 52, 51, 49, 50, 53, 47, 52, 51, 50], 50)

    ttest_1samp() tests whether a sample's mean differs from a given value. The result is stored in t, p.

  2. print("T-statistic:", t)

    Prints "T-statistic:" with the result.

  3. print("P-value:", p)

    Prints "P-value:" with the result.

  4. print("Reject the null hypothesis" if p < 0.05 else "Fail to reject the null hypothesis")

    Prints "Reject the null hypothesis" with the result.

Viva: concepts

Q. What is the null hypothesis here?

A. H₀: the population mean is 50. The test checks if the data gives enough evidence against it.

Q. What does the p-value mean?

A. The chance of getting data this extreme if H₀ is true. Small p (< 0.05) means H₀ is unlikely.

Q. p = 0.627 at α = 0.05 means…

A. Fail to reject the null hypothesis. A large p-value means the data is consistent with H₀.

Q. Which test compares the means of two independent groups?

A. stats.ttest_ind. ttest_rel is for paired (before/after) data; ttest_1samp compares one group with a fixed value.

Q. The p-value is…

A. The probability of a result this extreme if H₀ were true. A small p means the data would be surprising under H₀.

Viva: "change it to…"

→ Test against 52 instead of 50

t, p = stats.ttest_1samp(data, 52)

→ Compare two groups

t, p = stats.ttest_ind(group1, group2)

→ Use α = 0.01

print("Reject" if p < 0.01 else "Fail to reject")

Program 07

Confidence intervals

Confidence intervals for population parameters.

Run it

Algorithm

1. Start
2. Mean = np.mean(data)
3. Standard error: stats.sem(data)
4. Stats.t.interval(0.95, len(data) - 1, loc=mean, scale=sem)
5. Stop

Program

import numpy as np
from scipy import stats

data = [48, 52, 51, 49, 50, 53, 47, 52, 51, 50]
mean = np.mean(data)
print("Mean:", mean)
print("95% Confidence Interval:", stats.t.interval(0.95, len(data) - 1, loc=mean, scale=stats.sem(data)))

Output

Mean: 50.3
95% Confidence Interval: (np.float64(48.94900408571514), np.float64(51.650995914284856))

Viva: which module is used and why

Q. Why import numpy as np?

A. numpy: fast arrays and maths. np is just a short name so we can type np.something.

Q. Why stats from scipy?

A. scipy: scientific maths, including stats. scipy.stats holds the statistical tests and distributions.

Viva: what does each line do?

  1. data = [48, 52, 51, 49, 50, 53, 47, 52, 51, 50]

    Stores the value in data for the next lines.

  2. mean = np.mean(data)

    mean() is the average. The result is stored in mean.

  3. print("Mean:", mean)

    Prints "Mean:" with the result.

  4. print("95% Confidence Interval:", stats.t.interval(0.95, len(data) - 1, loc=mean, scale=stats.sem(data)))

    Prints "95% Confidence Interval:" with the result. t.interval() gives a confidence interval for the mean. loc=mean centres the interval on the sample mean. scale=stats.sem(data) uses the standard error as the spread.

Viva: concepts

Q. What does a 95% confidence interval mean?

A. If we repeated the sampling many times, about 95% of such intervals would contain the true population mean.

Q. The degrees of freedom passed to t.interval are…

A. n − 1. One degree of freedom is used up estimating the mean.

Q. stats.sem(data) computes…

A. std ÷ √n (standard error of the mean). SEM shows how much the sample mean would vary between samples.

Q. Why use the t-distribution here, not the normal?

A. Small sample and the population std is unknown. For large n the t-distribution approaches the normal anyway.

Viva: "change it to…"

→ 99% confidence interval

stats.t.interval(0.99, len(data) - 1, loc=mean, scale=stats.sem(data))

→ Also print the standard deviation

print("Std:", np.std(data, ddof=1))

Graphs

Program 09

Matplotlib & Seaborn

Visualize data using Matplotlib and Seaborn.

Run it

Algorithm

1. Start
2. Fig, ax = plt.subplots(1, 2, figsize=(12, 5))
3. Matplotlib: ax[0].plot(x, y, marker='o')
4. Seaborn: sns.scatterplot(data=df, x=..., y=..., ax=ax[1])
5. Plt.show()
6. Stop

Program

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'Age': [25, 30, 35, 40, 45], 'Salary': [50000, 60000, 70000, 80000, 90000]})

fig, ax = plt.subplots(1, 2, figsize=(12, 5))
ax[0].plot(df['Age'], df['Salary'], marker='o')
ax[0].set_title("Matplotlib Line Plot")
sns.scatterplot(data=df, x='Age', y='Salary', ax=ax[1]).set_title("Seaborn Scatter Plot")
plt.show()

Output

(graph only - no printed output)
Graph 1 produced by DS program 09: Matplotlib & Seaborn
Graph · Program 09

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why import seaborn as sns?

A. seaborn: statistical plots built on matplotlib. sns is just a short name so we can type sns.something.

Viva: what does each line do?

  1. df = pd.DataFrame({'Age': [25, 30, 35, 40, 45], 'Salary': [50000, 60000, 70000, 80000, 90000]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. fig, ax = plt.subplots(1, 2, figsize=(12, 5))

    plt.subplots(rows, cols) makes a figure with a grid of boxes (axes) to draw in. figsize=(w, h) sets the figure size in inches. The result is stored in fig, ax.

  3. ax[0].plot(df['Age'], df['Salary'], marker='o')

    plot() draws a line or bar chart (kind='bar' for bars). marker sets the dot shape on a line or scatter plot.

  4. ax[0].set_title("Matplotlib Line Plot")

    ax.set_title() names one subplot.

  5. sns.scatterplot(data=df, x='Age', y='Salary', ax=ax[1]).set_title("Seaborn Scatter Plot")

    sns.scatterplot() is a scatter plot; hue colours points by a category. data=df tells seaborn which table to take the columns from. ax.set_title() names one subplot.

  6. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. figsize=(12, 5) is measured in…

A. Inches (width, height). Pixels = inches × dpi.

Q. How do you draw a Seaborn plot inside a specific subplot?

A. Pass ax=ax[1]. Every axes-level Seaborn function accepts ax=.

Q. marker='o' in plot()…

A. Draws a dot at every data point. Line style is linestyle='--'; marker is the point symbol.

Viva: "change it to…"

→ Red dashed line

ax[0].plot(df['Age'], df['Salary'], marker='o', color='red', linestyle='--')

→ Axis labels

ax[0].set_xlabel('Age')
ax[0].set_ylabel('Salary')

Program 10

Six chart types

Bar chart, histogram, pie chart, box plot, scatter plot and heatmap.

Run it

Algorithm

1. Start
2. Plt.subplots(2, 3) gives a 2×3 grid → ax[row, col]
3. Bar, hist, pie(autopct), boxplot, scatter
4. Sns.heatmap(df.corr(), annot=True, ax=ax[1, 2])
5. Plt.tight_layout() then plt.show()
6. Stop

Program

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
                   'Age': [25, 30, 35, 40, 45],
                   'Salary': [50000, 60000, 70000, 80000, 90000]})

fig, ax = plt.subplots(2, 3, figsize=(15, 9))
ax[0, 0].bar(df['Name'], df['Salary'])
ax[0, 0].set_title("Bar Chart")
ax[0, 1].hist(df['Age'], bins=5)
ax[0, 1].set_title("Histogram")
ax[0, 2].pie(df['Salary'], labels=df['Name'], autopct='%1.1f%%')
ax[0, 2].set_title("Pie Chart")
ax[1, 0].boxplot(df['Salary'])
ax[1, 0].set_title("Box Plot")
ax[1, 1].scatter(df['Age'], df['Salary'])
ax[1, 1].set_title("Scatter Plot")
sns.heatmap(df[['Age', 'Salary']].corr(), annot=True, ax=ax[1, 2]).set_title("Heatmap")
plt.tight_layout()
plt.show()

Output

(graph only - no printed output)
Graph 1 produced by DS program 10: Six chart types
Graph · Program 10

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why import seaborn as sns?

A. seaborn: statistical plots built on matplotlib. sns is just a short name so we can type sns.something.

Viva: what does each line do?

  1. df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
                       'Age': [25, 30, 35, 40, 45],
                       'Salary': [50000, 60000, 70000, 80000, 90000]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. fig, ax = plt.subplots(2, 3, figsize=(15, 9))

    plt.subplots(rows, cols) makes a figure with a grid of boxes (axes) to draw in. figsize=(w, h) sets the figure size in inches. The result is stored in fig, ax.

  3. ax[0, 0].bar(df['Name'], df['Salary'])

    bar() draws a bar chart, for comparing categories.

  4. ax[0, 0].set_title("Bar Chart")

    ax.set_title() names one subplot.

  5. ax[0, 1].hist(df['Age'], bins=5)

    hist() draws a histogram, which shows the distribution of one numeric column. bins sets how many bars a histogram is split into.

  6. ax[0, 1].set_title("Histogram")

    ax.set_title() names one subplot.

  7. ax[0, 2].pie(df['Salary'], labels=df['Name'], autopct='%1.1f%%')

    pie() draws a pie chart, which shows the share of each part in the whole. labels= names each slice. autopct='%1.1f%%' prints the percentage on each pie slice.

  8. ax[0, 2].set_title("Pie Chart")

    ax.set_title() names one subplot.

  9. ax[1, 0].boxplot(df['Salary'])

    boxplot() shows the median, quartiles and outliers.

  10. ax[1, 0].set_title("Box Plot")

    ax.set_title() names one subplot.

  11. ax[1, 1].scatter(df['Age'], df['Salary'])

    scatter() plots x against y as dots, which shows the relationship.

  12. ax[1, 1].set_title("Scatter Plot")

    ax.set_title() names one subplot.

  13. sns.heatmap(df[['Age', 'Salary']].corr(), annot=True, ax=ax[1, 2]).set_title("Heatmap")

    sns.heatmap() colours a matrix; used for correlation or confusion matrices. corr() gives the correlation matrix, with values from −1 to 1. annot=True writes the number inside each heatmap cell.

  14. plt.tight_layout()

    tight_layout() stops labels overlapping between subplots.

  15. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. Which chart for what?

A. Bar = compare categories, histogram = distribution, pie = parts of a whole, box = spread and outliers, scatter = relationship, heatmap = correlation matrix.

Q. autopct='%1.1f%%' on a pie chart…

A. Shows each slice's percentage with 1 decimal. %% prints a literal % sign.

Q. plt.tight_layout() is used to…

A. Stop titles and labels of subplots overlapping. It adjusts the spacing between subplots automatically.

Q. A box plot shows…

A. Median, quartiles (IQR) and outliers. The box is Q1–Q3, the line is the median, and the whiskers go to 1.5×IQR.

Viva: "change it to…"

→ Only a bar chart

plt.bar(df['Name'], df['Salary'])
plt.title('Salary')
plt.show()

→ Horizontal bars

plt.barh(df['Name'], df['Salary'])

→ Save the figure

plt.savefig('charts.png')   # before plt.show()

Program 37

Interactive Plotly

Interactive data visualization using Plotly.

Run it

Algorithm

1. Start
2. Df = px.data.iris() (bundled, works offline)
3. Px.scatter(df, x=..., y=..., color='species', size=..., hover_data=[...])
4. Fig.show() opens in the browser
5. Stop

Program

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x='sepal_length', y='sepal_width', color='species',
                 size='petal_length', hover_data=['petal_width'], title="Interactive Iris Scatter Plot")
fig.show()

Output

(opens an interactive Plotly dashboard in the web browser - no printed output)
Graph 1 produced by DS program 37: Interactive Plotly
Graph · Program 37

Viva: which module is used and why

Q. Why import plotly.express as px?

A. plotly.express: interactive charts. px is just a short name so we can type px.something.

Viva: what does each line do?

  1. df = px.data.iris()

    .data is the feature matrix of a sklearn dataset. The result is stored in df.

  2. fig = px.scatter(df, x='sepal_length', y='sepal_width', color='species',
                     size='petal_length', hover_data=['petal_width'], title="Interactive Iris Scatter Plot")

    scatter() plots x against y as dots, which shows the relationship. color sets the colour of the plotted marks. size='petal_length' draws bigger bubbles for bigger values. The result is stored in fig.

  3. fig.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. Does px.data.iris() need internet?

A. No, the sample data ships inside plotly. Other bundled ones: px.data.tips(), gapminder(), stocks(). sns.load_dataset() does need internet.

Q. size='petal_length' in px.scatter…

A. Sets each marker's size from petal length. color= sets the colour, hover_data= adds tooltip fields.

Viva: "change it to…"

→ Plot petal sizes instead

px.scatter(df, x='petal_length', y='petal_width', color='species')

→ Interactive histogram

px.histogram(df, x='sepal_length', color='species').show()

→ Interactive bar chart

px.bar(df, x='species', y='sepal_length').show()

Program 38

Pair plots & PCA

Visualize multidimensional data: pair plots and dimensionality reduction.

Run it

Algorithm

1. Start
2. Iris = load_iris(as_frame=True); df = iris.data
3. Df['species'] = iris.target_names[iris.target]
4. Sns.pairplot(df, hue='species'); plt.show()
5. PCA(2) → sns.scatterplot(x=PC1, y=PC2, hue=species)
6. Stop

Program

import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA

iris = load_iris(as_frame=True)
df = iris.data
df['species'] = iris.target_names[iris.target]

sns.pairplot(df, hue='species')
plt.show()

X_pca = PCA(n_components=2).fit_transform(df.drop(columns='species'))
sns.scatterplot(x=X_pca[:, 0], y=X_pca[:, 1], hue=df['species'])
plt.title("2D PCA Visualization")
plt.show()

Output

(graph only - no printed output)
Graph 1 produced by DS program 38: Pair plots & PCA
Graph 1 · Program 38
Graph 2 produced by DS program 38: Pair plots & PCA
Graph 2 · Program 38

Viva: which module is used and why

Q. Why import seaborn as sns?

A. seaborn: statistical plots built on matplotlib. sns is just a short name so we can type sns.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why load_iris from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed.

Q. Why PCA from sklearn.decomposition?

A. sklearn.decomposition: PCA and TruncatedSVD. PCA projects the data onto the directions of most variance.

Viva: what does each line do?

  1. iris = load_iris(as_frame=True)

    load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed. as_frame=True returns the dataset as a pandas DataFrame. The result is stored in iris.

  2. df = iris.data

    .data is the feature matrix of a sklearn dataset. The result is stored in df.

  3. df['species'] = iris.target_names[iris.target]

    target_names holds the class names behind the numeric labels. .target holds the labels (the y values). Creates (or replaces) df['species'] with this value.

  4. sns.pairplot(df, hue='species')

    sns.pairplot() draws a scatter plot for every pair of columns. hue colours the points or bars by a category column.

  5. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

  6. X_pca = PCA(n_components=2).fit_transform(df.drop(columns='species'))

    PCA projects the data onto the directions of most variance. n_components is how many components (or dimensions) to keep. fit_transform() learns the transformation and applies it in one step. The result is stored in X_pca.

  7. sns.scatterplot(x=X_pca[:, 0], y=X_pca[:, 1], hue=df['species'])

    sns.scatterplot() is a scatter plot; hue colours points by a category. hue colours the points or bars by a category column.

  8. plt.title("2D PCA Visualization")

    title() puts a heading on the graph.

  9. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. Why PCA?

A. To reduce many features to a few (here 4 → 2) while keeping the most variance, so we can visualise the data.

Q. A pair plot shows…

A. A scatter plot for every pair of columns, with distributions on the diagonal. hue= colours the points by class.

Q. iris.target_names[iris.target] works because…

A. NumPy fancy indexing maps each 0/1/2 to its name. An array indexed by an array of integers.

Viva: "change it to…"

→ 3 components

PCA(n_components=3)

→ How much variance PCA keeps

pca = PCA(n_components=2)
X_pca = pca.fit_transform(df.drop(columns='species'))
print(pca.explained_variance_ratio_)

Regression (predict a number)

Program 11

Simple linear regression

Simple Linear Regression using Scikit-learn.

Run it

Algorithm

1. Start
2. X = df[['Experience']] (2-D), y = df['Salary']
3. Model = LinearRegression().fit(X, y)
4. Print coef_[0] (slope), intercept_, score(X, y) (R²)
5. Predict a new value, then plot the points with the regression line
6. Stop

Program

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

df = pd.DataFrame({'Experience': range(1, 11),
                   'Salary': [30000, 35000, 41000, 44000, 52000, 55000, 62000, 66000, 71000, 78000]})
X, y = df[['Experience']], df['Salary']

model = LinearRegression().fit(X, y)
print("Slope:", model.coef_[0], " Intercept:", model.intercept_)
print("R2 Score:", model.score(X, y))
print("Predicted Salary for 11 years:", model.predict(pd.DataFrame({'Experience': [11]}))[0])

plt.scatter(X, y, label="Data")
plt.plot(X, model.predict(X), color='red', label="Regression Line")
plt.title("Simple Linear Regression")
plt.legend()
plt.show()

Output

Slope: 5248.48484848485  Intercept: 24533.333333333325
R2 Score: 0.9965768897535254
Predicted Salary for 11 years: 82266.66666666667
Graph 1 produced by DS program 11: Simple linear regression
Graph · Program 11

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why LinearRegression from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. LinearRegression fits a straight line: y = mx + c.

Viva: what does each line do?

  1. df = pd.DataFrame({'Experience': range(1, 11),
                       'Salary': [30000, 35000, 41000, 44000, 52000, 55000, 62000, 66000, 71000, 78000]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. X, y = df[['Experience']], df['Salary']

    X = the input columns (features), y = the answer column the model must predict (target). The result is stored in X, y.

  3. model = LinearRegression().fit(X, y)

    LinearRegression fits a straight line: y = mx + c. fit() learns from the training data.

  4. print("Slope:", model.coef_[0], " Intercept:", model.intercept_)

    Prints "Slope:" with the result. coef_ holds the learned slopes (one per feature). intercept_ is the learned constant term c.

  5. print("R2 Score:", model.score(X, y))

    Prints "R2 Score:" with the result. score() returns accuracy (classifiers) or R² (regressors).

  6. print("Predicted Salary for 11 years:", model.predict(pd.DataFrame({'Experience': [11]}))[0])

    Prints "Predicted Salary for 11 years:" with the result. predict() gives the model's predicted labels or values. pd.DataFrame builds a table from the dict: each key becomes a column.

  7. plt.scatter(X, y, label="Data")

    scatter() plots x against y as dots, which shows the relationship. label is the text that appears in the legend.

  8. plt.plot(X, model.predict(X), color='red', label="Regression Line")

    plot() draws a line or bar chart (kind='bar' for bars). predict() gives the model's predicted labels or values. color sets the colour of the plotted marks.

  9. plt.title("Simple Linear Regression")

    title() puts a heading on the graph.

  10. plt.legend()

    legend() shows which colour is which series.

  11. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. What is linear regression?

A. A model that fits the best straight line y = mx + c through the data to predict a continuous value.

Q. Why df[['Experience']] with double brackets?

A. scikit-learn needs X to be 2-D (rows × features). Single brackets give a 1-D Series; double brackets give a one-column DataFrame.

Q. For a regressor, model.score(X, y) returns…

A. R² (coefficient of determination). For classifiers, score() returns accuracy instead.

Q. A prediction from simple linear regression is…

A. intercept + slope × x. This is ŷ = b₀ + b₁x.

Viva: "change it to…"

→ Predict for 15 years

print(model.predict(pd.DataFrame({'Experience': [15]}))[0])

→ Also print MSE

from sklearn.metrics import mean_squared_error
print("MSE:", mean_squared_error(y, model.predict(X)))

Program 12

Multiple linear regression

Multiple Linear Regression with model evaluation.

Run it

Algorithm

1. Start
2. X = df.drop(columns='Salary'), y = df['Salary']
3. Train_test_split(X, y, test_size=0.3, random_state=1)
4. Fit on train, predict on test
5. Evaluate with mean_squared_error and r2_score
6. Stop

Program

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

df = pd.DataFrame({
    'Experience': range(1, 16),
    'Education': [12, 14, 16, 16, 14, 18, 16, 18, 20, 16, 18, 20, 18, 20, 22],
    'Projects': [2, 3, 5, 4, 6, 7, 6, 8, 9, 8, 10, 11, 10, 12, 13],
    'Salary': [39000, 44500, 49500, 50500, 53000, 59500, 61000, 68500,
               71000, 69000, 76500, 81500, 81000, 85000, 91500]})
X, y = df.drop(columns='Salary'), df['Salary']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)

model = LinearRegression().fit(X_train, y_train)
y_pred = model.predict(X_test)
print("Coefficients:", model.coef_)
print("Intercept:", model.intercept_)
print("MSE:", mean_squared_error(y_test, y_pred))
print("R2 Score:", r2_score(y_test, y_pred))

Output

Coefficients: [2866.65373507 1107.60162076   96.64209664]
Intercept: 22505.043320832818
MSE: 2101589.657324817
R2 Score: 0.9804974976120563
Graph 1 produced by DS program 12: Multiple linear regression
Graph · Program 12

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why LinearRegression from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. LinearRegression fits a straight line: y = mx + c.

Q. Why mean_squared_error and r2_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… mean_squared_error() is the average squared prediction error; take √ for RMSE. r2_score() is the share of the variance in y the model explains.

Viva: what does each line do?

  1. df = pd.DataFrame({
        'Experience': range(1, 16),
        'Education': [12, 14, 16, 16, 14, 18, 16, 18, 20, 16, 18, 20, 18, 20, 22],
        'Projects': [2, 3, 5, 4, 6, 7, 6, 8, 9, 8, 10, 11, 10, 12, 13],
        'Salary': [39000, 44500, 49500, 50500, 53000, 59500, 61000, 68500,
                   71000, 69000, 76500, 81500, 81000, 85000, 91500]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. X, y = df.drop(columns='Salary'), df['Salary']

    X = the input columns (features), y = the answer column the model must predict (target). drop() removes the named rows or columns (axis=1 for columns). columns='Salary' names the column to remove.

  3. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)

    train_test_split() splits the data into training and test sets. test_size=0.3 keeps 30% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  4. model = LinearRegression().fit(X_train, y_train)

    LinearRegression fits a straight line: y = mx + c. fit() learns from the training data.

  5. y_pred = model.predict(X_test)

    predict() gives the model's predicted labels or values. The result is stored in y_pred.

  6. print("Coefficients:", model.coef_)

    Prints "Coefficients:" with the result. coef_ holds the learned slopes (one per feature).

  7. print("Intercept:", model.intercept_)

    Prints "Intercept:" with the result. intercept_ is the learned constant term c.

  8. print("MSE:", mean_squared_error(y_test, y_pred))

    Prints "MSE:" with the result. mean_squared_error() is the average squared prediction error; take √ for RMSE.

  9. print("R2 Score:", r2_score(y_test, y_pred))

    Prints "R2 Score:" with the result. r2_score() is the share of the variance in y the model explains.

Viva: concepts

Q. MSE vs R²?

A. MSE is the average squared error (lower is better, in squared units). R² is the fraction of variance explained (closer to 1 is better).

Q. With 15 rows and test_size=0.3, the test set has how many rows?

A. 5. scikit-learn rounds the test size up: ceil(4.5) = 5.

Q. random_state=1 in train_test_split…

A. Gives the same split every run. Any fixed integer works; it seeds the shuffle.

Q. MSE is measured in…

A. The target's units squared. Take √MSE (RMSE) to get back to the target's units.

Viva: "change it to…"

→ 80/20 split

test_size=0.2

→ Show actual vs predicted

print(pd.DataFrame({'Actual': y_test, 'Predicted': y_pred}))

Program 13

Ridge & Lasso

Ridge and Lasso Regression.

Run it

Algorithm

1. Start
2. Split the data into train and test
3. Make_pipeline(StandardScaler(), Ridge(alpha=1.0))
4. Make_pipeline(StandardScaler(), Lasso(alpha=100.0))
5. Compare test R² and the coefficients
6. Stop

Program

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge, Lasso

df = pd.DataFrame({
    'Experience': range(1, 16),
    'Education': [12, 14, 16, 16, 14, 18, 16, 18, 20, 16, 18, 20, 18, 20, 22],
    'Projects': [2, 3, 5, 4, 6, 7, 6, 8, 9, 8, 10, 11, 10, 12, 13],
    'Distance': [12, 30, 8, 25, 40, 15, 33, 6, 22, 18, 35, 10, 28, 20, 14],
    'Salary': [39000, 44500, 49500, 50500, 53000, 59500, 61000, 68500,
               71000, 69000, 76500, 81500, 81000, 85000, 91500]})
X_train, X_test, y_train, y_test = train_test_split(df.drop(columns='Salary'), df['Salary'], test_size=0.3, random_state=1)

for name, m in [('Ridge', Ridge(alpha=1.0)), ('Lasso', Lasso(alpha=100.0, max_iter=10000))]:
    model = make_pipeline(StandardScaler(), m).fit(X_train, y_train)
    print(f"{name} R2 Score:", model.score(X_test, y_test))
    print(f"{name} Coefs:", m.coef_.round(2))

Output

Ridge R2 Score: 0.9735442276317761
Ridge Coefs: [7769.75 3114.27 5702.76 -193.01]
Lasso R2 Score: 0.9800886182117426
Lasso Coefs: [13465.47  3363.96   408.81    -0.  ]
Graph 1 produced by DS program 13: Ridge & Lasso
Graph · Program 13

Viva: which module is used and why

Q. Why import pandas as pd?

A. pandas: tables (DataFrame) and file I/O. pd is just a short name so we can type pd.something.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why make_pipeline from sklearn.pipeline?

A. sklearn.pipeline: chaining preprocessing and model steps. make_pipeline() chains steps (e.g. scaler → model) into one estimator.

Q. Why StandardScaler from sklearn.preprocessing?

A. sklearn.preprocessing: scalers and encoders. StandardScaler rescales each feature to mean 0 and std 1.

Q. Why Ridge and Lasso from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. Ridge is linear regression with an L2 penalty that shrinks the coefficients. Lasso is linear regression with an L1 penalty that can make coefficients exactly 0.

Viva: what does each line do?

  1. df = pd.DataFrame({
        'Experience': range(1, 16),
        'Education': [12, 14, 16, 16, 14, 18, 16, 18, 20, 16, 18, 20, 18, 20, 22],
        'Projects': [2, 3, 5, 4, 6, 7, 6, 8, 9, 8, 10, 11, 10, 12, 13],
        'Distance': [12, 30, 8, 25, 40, 15, 33, 6, 22, 18, 35, 10, 28, 20, 14],
        'Salary': [39000, 44500, 49500, 50500, 53000, 59500, 61000, 68500,
                   71000, 69000, 76500, 81500, 81000, 85000, 91500]})

    pd.DataFrame builds a table from the dict: each key becomes a column. The result is stored in df.

  2. X_train, X_test, y_train, y_test = train_test_split(df.drop(columns='Salary'), df['Salary'], test_size=0.3, random_state=1)

    train_test_split() splits the data into training and test sets. drop() removes the named rows or columns (axis=1 for columns). columns='Salary' names the column to remove. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. for name, m in [('Ridge', Ridge(alpha=1.0)), ('Lasso', Lasso(alpha=100.0, max_iter=10000))]:

    Loop: repeats the indented lines for every name, m in [('Ridge', Ridge(alpha=1.0)), ('Lasso', Lasso(alpha=100.0, max_iter=10000))]. Ridge is linear regression with an L2 penalty that shrinks the coefficients. alpha is the regularisation strength: bigger means more shrinkage. Lasso is linear regression with an L1 penalty that can make coefficients exactly 0.

  4.     model = make_pipeline(StandardScaler(), m).fit(X_train, y_train)

    make_pipeline() chains steps (e.g. scaler → model) into one estimator. StandardScaler rescales each feature to mean 0 and std 1. fit() learns from the training data.

  5.     print(f"{name} R2 Score:", model.score(X_test, y_test))

    Prints "… R2 Score:" with the result. score() returns accuracy (classifiers) or R² (regressors).

  6.     print(f"{name} Coefs:", m.coef_.round(2))

    Prints "… Coefs:" with the result. coef_ holds the learned slopes (one per feature). round() limits the number of decimal places.

Viva: concepts

Q. Why regularisation?

A. To stop overfitting by penalising big coefficients. Ridge shrinks them; Lasso can remove features completely.

Q. Which one can shrink a coefficient to exactly 0?

A. Lasso (L1 penalty). That is why Lasso also does feature selection: a coefficient printed as 0 (or -0.) means that feature was dropped.

Q. Ridge adds which penalty to the loss?

A. Sum of squared coefficients (L2). L2 shrinks all coefficients smoothly but rarely to zero.

Q. Why scale the features before Ridge/Lasso?

A. The penalty treats all coefficients equally, so features must share a scale. Otherwise a feature measured in big units gets penalised differently.

Viva: "change it to…"

→ Stronger Ridge penalty

Ridge(alpha=10.0)

→ Plain linear regression to compare

from sklearn.linear_model import LinearRegression
('Linear', LinearRegression())

Classification (predict a class)

Program 14

Train-test split & CV

Model selection using train-test split and cross-validation.

Run it

Algorithm

1. Start
2. Make data with make_classification(...)
3. Split 75/25 and score each model on the test set
4. Cross_val_score(model, X, y, cv=5).mean()
5. Pick the best: max(cv, key=cv.get)
6. Stop

Program

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=500, n_features=8, n_informative=5, n_redundant=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

models = {'Logistic Regression': LogisticRegression(), 'kNN': KNeighborsClassifier(),
          'Decision Tree': DecisionTreeClassifier(random_state=42)}
cv = {}
for name, m in models.items():
    test = m.fit(X_train, y_train).score(X_test, y_test)
    cv[name] = cross_val_score(m, X, y, cv=5).mean()
    print(f"{name:20s} Test Accuracy: {test:.4f}  5-Fold CV: {cv[name]:.4f}")
print("Best model:", max(cv, key=cv.get))

Output

Logistic Regression  Test Accuracy: 0.8480  5-Fold CV: 0.8440
kNN                  Test Accuracy: 0.9120  5-Fold CV: 0.9180
Decision Tree        Test Accuracy: 0.8720  5-Fold CV: 0.9000
Best model: kNN
Graph 1 produced by DS program 14: Train-test split & CV
Graph · Program 14

Viva: which module is used and why

Q. Why make_classification from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). make_classification() creates a synthetic labelled dataset.

Q. Why train_test_split and cross_val_score from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets. cross_val_score() trains and tests on k folds and returns one score per fold.

Q. Why LogisticRegression from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. LogisticRegression is a classifier: it passes a linear score through the sigmoid.

Q. Why KNeighborsClassifier from sklearn.neighbors?

A. sklearn.neighbors: k-nearest neighbours. KNeighborsClassifier labels a point by majority vote of its k nearest neighbours.

Q. Why DecisionTreeClassifier from sklearn.tree?

A. sklearn.tree: decision trees. DecisionTreeClassifier splits the data with if/else rules on the features.

Viva: what does each line do?

  1. X, y = make_classification(n_samples=500, n_features=8, n_informative=5, n_redundant=2, random_state=42)

    X = the input columns (features), y = the answer column the model must predict (target). make_classification() creates a synthetic labelled dataset. n_samples is how many rows to generate. n_features is how many columns (features) to generate.

  2. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.25 keeps 25% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. models = {'Logistic Regression': LogisticRegression(), 'kNN': KNeighborsClassifier(),
              'Decision Tree': DecisionTreeClassifier(random_state=42)}

    LogisticRegression is a classifier: it passes a linear score through the sigmoid. KNeighborsClassifier labels a point by majority vote of its k nearest neighbours. DecisionTreeClassifier splits the data with if/else rules on the features. The result is stored in models.

  4. cv = {}

    Stores the value in cv for the next lines.

  5. for name, m in models.items():

    Loop: repeats the indented lines for every name, m in models.items(). items() gives (name, model) pairs so the loop can use both.

  6.     test = m.fit(X_train, y_train).score(X_test, y_test)

    fit() learns from the training data. score() returns accuracy (classifiers) or R² (regressors). The result is stored in test.

  7.     cv[name] = cross_val_score(m, X, y, cv=5).mean()

    cross_val_score() trains and tests on k folds and returns one score per fold. mean() is the average. Creates (or replaces) cv[name] with this value.

  8.     print(f"{name:20s} Test Accuracy: {test:.4f}  5-Fold CV: {cv[name]:.4f}")

    Prints "… Test Accuracy: … 5-Fold CV: …" with the result.

  9. print("Best model:", max(cv, key=cv.get))

    Prints "Best model:" with the result. key= tells sort/max which value to compare by. key=cv.get makes max() compare the dict's values (the scores) and return the best name.

Viva: concepts

Q. What is cross-validation?

A. Split data into k folds; train on k−1 and test on the remaining one, k times. Average score is more reliable than one split.

Q. cross_val_score(m, X, y, cv=5)…

A. Trains and tests 5 times, each fold taking a turn as the test set. It returns 5 scores; their mean is a steadier estimate.

Q. max(cv, key=cv.get) returns…

A. The model name with the highest CV score. key= tells max to compare by the dict values.

Q. Why use cross-validation over a single split?

A. The score depends less on one lucky or unlucky split. Every sample is used for testing exactly once.

Viva: "change it to…"

→ 10-fold cross-validation

cross_val_score(m, X, y, cv=10).mean()

→ Add an SVM to the comparison

from sklearn.svm import SVC
models['SVM'] = SVC()

Program 15

Evaluation metrics

Model evaluation: confusion matrix, accuracy, precision, recall, F1, ROC-AUC.

Run it

Algorithm

1. Start
2. Train a scaled LogisticRegression on breast cancer data
3. Y_pred = predict(X_test), y_prob = predict_proba(X_test)[:, 1]
4. Confusion_matrix, accuracy, precision, recall, F1 from y_pred
5. Roc_auc_score from y_prob
6. Stop

Program

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, roc_auc_score

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
y_pred = model.predict(X_test)
y_prob = model.predict_proba(X_test)[:, 1]

print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Accuracy:", accuracy_score(y_test, y_pred))
print("Precision:", precision_score(y_test, y_pred))
print("Recall:", recall_score(y_test, y_pred))
print("F1-Score:", f1_score(y_test, y_pred))
print("ROC-AUC:", roc_auc_score(y_test, y_prob))

Output

Confusion Matrix:
 [[53  1]
 [ 2 87]]
Accuracy: 0.9790209790209791
Precision: 0.9886363636363636
Recall: 0.9775280898876404
F1-Score: 0.9830508474576272
ROC-AUC: 0.9977111943404079
Graph 1 produced by DS program 15: Evaluation metrics
Graph · Program 15

Viva: which module is used and why

Q. Why load_breast_cancer from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_breast_cancer() loads a built-in binary classification dataset.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why make_pipeline from sklearn.pipeline?

A. sklearn.pipeline: chaining preprocessing and model steps. make_pipeline() chains steps (e.g. scaler → model) into one estimator.

Q. Why StandardScaler from sklearn.preprocessing?

A. sklearn.preprocessing: scalers and encoders. StandardScaler rescales each feature to mean 0 and std 1.

Q. Why LogisticRegression from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. LogisticRegression is a classifier: it passes a linear score through the sigmoid.

Q. Why confusion_matrix, accuracy_score, precision_score, recall_score, f1_score and roc_auc_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… confusion_matrix() counts TP, FP, FN and TN for each class. accuracy_score() is correct predictions ÷ total. precision_score() is TP ÷ (TP + FP): how many predicted positives were right.

Viva: what does each line do?

  1. X, y = load_breast_cancer(return_X_y=True)

    X = the input columns (features), y = the answer column the model must predict (target). load_breast_cancer() loads a built-in binary classification dataset. return_X_y=True returns (X, y) directly instead of a Bunch object.

  2. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.25 keeps 25% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)

    make_pipeline() chains steps (e.g. scaler → model) into one estimator. StandardScaler rescales each feature to mean 0 and std 1. LogisticRegression is a classifier: it passes a linear score through the sigmoid.

  4. y_pred = model.predict(X_test)

    predict() gives the model's predicted labels or values. The result is stored in y_pred.

  5. y_prob = model.predict_proba(X_test)[:, 1]

    predict_proba() gives the probability for each class. The result is stored in y_prob.

  6. print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))

    Prints "Confusion Matrix:" with the result. confusion_matrix() counts TP, FP, FN and TN for each class.

  7. print("Accuracy:", accuracy_score(y_test, y_pred))

    Prints "Accuracy:" with the result. accuracy_score() is correct predictions ÷ total.

  8. print("Precision:", precision_score(y_test, y_pred))

    Prints "Precision:" with the result. precision_score() is TP ÷ (TP + FP): how many predicted positives were right.

  9. print("Recall:", recall_score(y_test, y_pred))

    Prints "Recall:" with the result. recall_score() is TP ÷ (TP + FN): how many real positives were found.

  10. print("F1-Score:", f1_score(y_test, y_pred))

    Prints "F1-Score:" with the result. f1_score() is the harmonic mean of precision and recall.

  11. print("ROC-AUC:", roc_auc_score(y_test, y_prob))

    Prints "ROC-AUC:" with the result. roc_auc_score() is the area under the ROC curve; 1.0 is perfect, 0.5 is guessing.

Viva: concepts

Q. Precision vs recall?

A. Precision = TP/(TP+FP): of predicted positives, how many were right. Recall = TP/(TP+FN): of real positives, how many we found.

Q. What is F1?

A. The harmonic mean of precision and recall; useful when classes are imbalanced.

Q. Precision =

A. TP / (TP + FP). Of everything predicted positive, how much really was positive.

Q. Recall =

A. TP / (TP + FN). Of all actual positives, how many we caught.

Q. roc_auc_score needs…

A. Probabilities for the positive class (predict_proba[:, 1]). AUC measures ranking across every threshold, so it needs scores, not labels.

Q. In sklearn's confusion_matrix, the rows are…

A. Actual classes (columns are predicted). So [[TN, FP], [FN, TP]] for binary labels 0/1.

Viva: "change it to…"

→ Full per-class report

from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))

→ Use a different split

test_size=0.3

Program 16

k-Nearest Neighbors

k-Nearest Neighbors (kNN) classification.

Run it

Algorithm

1. Start
2. Iris = load_iris(); split 70/30 with random_state=42
3. KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
4. Accuracy + confusion matrix on the test set
5. Predict a new flower and map it with iris.target_names
6. Stop

Program

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)

knn = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)
y_pred = knn.predict(X_test)
print("kNN Accuracy:", accuracy_score(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("Prediction for [5.1, 3.5, 1.4, 0.2]:", iris.target_names[knn.predict([[5.1, 3.5, 1.4, 0.2]])[0]])

Output

kNN Accuracy: 1.0
Confusion Matrix:
 [[19  0  0]
 [ 0 13  0]
 [ 0  0 13]]
Prediction for [5.1, 3.5, 1.4, 0.2]: setosa
Graph 1 produced by DS program 16: k-Nearest Neighbors
Graph · Program 16

Viva: which module is used and why

Q. Why load_iris from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why KNeighborsClassifier from sklearn.neighbors?

A. sklearn.neighbors: k-nearest neighbours. KNeighborsClassifier labels a point by majority vote of its k nearest neighbours.

Q. Why accuracy_score and confusion_matrix from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… accuracy_score() is correct predictions ÷ total. confusion_matrix() counts TP, FP, FN and TN for each class.

Viva: what does each line do?

  1. iris = load_iris()

    load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed. The result is stored in iris.

  2. X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)

    train_test_split() splits the data into training and test sets. .data is the feature matrix of a sklearn dataset. .target holds the labels (the y values). You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. knn = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)

    KNeighborsClassifier labels a point by majority vote of its k nearest neighbours. n_neighbors is k, the number of neighbours that vote. fit() learns from the training data. The result is stored in knn.

  4. y_pred = knn.predict(X_test)

    predict() gives the model's predicted labels or values. The result is stored in y_pred.

  5. print("kNN Accuracy:", accuracy_score(y_test, y_pred))

    Prints "kNN Accuracy:" with the result. accuracy_score() is correct predictions ÷ total.

  6. print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))

    Prints "Confusion Matrix:" with the result. confusion_matrix() counts TP, FP, FN and TN for each class.

  7. print("Prediction for [5.1, 3.5, 1.4, 0.2]:", iris.target_names[knn.predict([[5.1, 3.5, 1.4, 0.2]])[0]])

    Prints "Prediction for [5.1, 3.5, 1.4, 0.2]:" with the result. target_names holds the class names behind the numeric labels. predict() gives the model's predicted labels or values.

Viva: concepts

Q. How does kNN work?

A. It stores the training data. For a new point it finds the k closest points (by distance) and takes the majority vote.

Q. What is k in kNN?

A. The number of nearest neighbours that vote. The new point takes the majority label of its k closest training points.

Q. What does kNN do during fit()?

A. It just stores the training data (lazy learner). All the work happens at predict time.

Q. The Iris dataset has…

A. 150 samples, 4 features, 3 classes. Iris, Wine and Breast Cancer all ship with scikit-learn, so they load without internet.

Viva: "change it to…"

→ k = 3

KNeighborsClassifier(n_neighbors=3)

→ Try k = 1 to 10

for k in range(1, 11):
    acc = KNeighborsClassifier(n_neighbors=k).fit(X_train, y_train).score(X_test, y_test)
    print(k, acc)

Program 17

Decision Tree

Decision Tree classification.

Run it

Algorithm

1. Start
2. DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=42)
3. Fit on train, print the test accuracy
4. Export_text(dt, feature_names=iris.feature_names) prints the rules
5. Stop

Program

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.metrics import accuracy_score

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)

dt = DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=42).fit(X_train, y_train)
print("Decision Tree Accuracy:", accuracy_score(y_test, dt.predict(X_test)))
print("\nDecision Rules:\n" + export_text(dt, feature_names=iris.feature_names))

Output

Decision Tree Accuracy: 1.0

Decision Rules:
|--- petal length (cm) <= 2.45
|   |--- class: 0
|--- petal length (cm) >  2.45
|   |--- petal length (cm) <= 4.75
|   |   |--- petal width (cm) <= 1.60
|   |   |   |--- class: 1
|   |   |--- petal width (cm) >  1.60
|   |   |   |--- class: 2
|   |--- petal length (cm) >  4.75
|   |   |--- petal width (cm) <= 1.75
|   |   |   |--- class: 1
|   |   |--- petal width (cm) >  1.75
|   |   |   |--- class: 2
Graph 1 produced by DS program 17: Decision Tree
Graph · Program 17

Viva: which module is used and why

Q. Why load_iris from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why DecisionTreeClassifier and export_text from sklearn.tree?

A. sklearn.tree: decision trees. DecisionTreeClassifier splits the data with if/else rules on the features. export_text() prints the decision tree's rules as text.

Q. Why accuracy_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… accuracy_score() is correct predictions ÷ total.

Viva: what does each line do?

  1. iris = load_iris()

    load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed. The result is stored in iris.

  2. X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)

    train_test_split() splits the data into training and test sets. .data is the feature matrix of a sklearn dataset. .target holds the labels (the y values). You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. dt = DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=42).fit(X_train, y_train)

    DecisionTreeClassifier splits the data with if/else rules on the features. criterion picks the split measure: 'gini' or 'entropy'. max_depth limits how deep a tree grows, which helps against overfitting. The result is stored in dt.

  4. print("Decision Tree Accuracy:", accuracy_score(y_test, dt.predict(X_test)))

    Prints "Decision Tree Accuracy:" with the result. accuracy_score() is correct predictions ÷ total. predict() gives the model's predicted labels or values.

  5. print("\nDecision Rules:\n" + export_text(dt, feature_names=iris.feature_names))

    Prints "Decision Rules:" with the result. export_text() prints the decision tree's rules as text. feature_names holds the column names of the features.

Viva: concepts

Q. What is Gini?

A. A measure of impurity: 0 means a node has only one class. The tree picks the split that lowers impurity the most.

Q. max_depth=3…

A. Limits the tree to 3 levels so it doesn't overfit. Deeper trees memorise noise.

Q. Besides 'gini', which criterion can a tree split on?

A. 'entropy' (information gain). Both measure impurity; they usually give similar trees.

Q. export_text() prints…

A. The tree's if/else rules as text. For a picture, use sklearn.tree.plot_tree(dt) + plt.show().

Viva: "change it to…"

→ Use entropy

DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=42)

→ Draw the tree

from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
plot_tree(dt, filled=True, feature_names=iris.feature_names)
plt.show()

Program 18

Support Vector Machine

Support Vector Machine (SVM) classification.

Run it

Algorithm

1. Start
2. Load iris and split 70/30
3. Loop over kernels ['linear', 'poly', 'rbf']
4. SVC(kernel=k).fit(...) and print each accuracy
5. Stop

Program

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

for kernel in ['linear', 'poly', 'rbf']:
    svm = SVC(kernel=kernel).fit(X_train, y_train)
    print(f"SVM ({kernel}) Accuracy:", accuracy_score(y_test, svm.predict(X_test)))

Output

SVM (linear) Accuracy: 1.0
SVM (poly) Accuracy: 0.9777777777777777
SVM (rbf) Accuracy: 1.0
Graph 1 produced by DS program 18: Support Vector Machine
Graph · Program 18

Viva: which module is used and why

Q. Why load_iris from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why SVC from sklearn.svm?

A. sklearn.svm: support vector machines. SVC is a support vector classifier: it finds the widest-margin boundary.

Q. Why accuracy_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… accuracy_score() is correct predictions ÷ total.

Viva: what does each line do?

  1. X, y = load_iris(return_X_y=True)

    X = the input columns (features), y = the answer column the model must predict (target). load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed. return_X_y=True returns (X, y) directly instead of a Bunch object.

  2. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.3 keeps 30% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. for kernel in ['linear', 'poly', 'rbf']:

    Loop: repeats the indented lines for every kernel in ['linear', 'poly', 'rbf'].

  4.     svm = SVC(kernel=kernel).fit(X_train, y_train)

    SVC is a support vector classifier: it finds the widest-margin boundary. kernel chooses the SVM's boundary shape: 'linear', 'rbf', 'poly'. fit() learns from the training data. The result is stored in svm.

  5.     print(f"SVM ({kernel}) Accuracy:", accuracy_score(y_test, svm.predict(X_test)))

    Prints "SVM (…) Accuracy:" with the result. accuracy_score() is correct predictions ÷ total. predict() gives the model's predicted labels or values.

Viva: concepts

Q. What does SVM do?

A. Finds the boundary with the widest margin between classes. Kernels let it draw curved boundaries.

Q. SVC's default kernel is…

A. 'rbf'. RBF (Gaussian) handles curved boundaries well.

Q. The kernel trick…

A. Lets the SVM separate data in a higher dimension without computing it. It is why SVMs can draw non-linear boundaries.

Q. Support vectors are…

A. The training points closest to the decision boundary. Only they decide where the margin sits.

Viva: "change it to…"

→ Only RBF with C = 10

svm = SVC(kernel='rbf', C=10).fit(X_train, y_train)

→ Confusion matrix

from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, svm.predict(X_test)))

Program 19

Random Forest

Random Forest classification.

Run it

Algorithm

1. Start
2. Load_wine(return_X_y=True), split 70/30
3. RandomForestClassifier(n_estimators=100, random_state=42)
4. Fit and print the test accuracy
5. Stop

Program

from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

rf = RandomForestClassifier(n_estimators=100, random_state=42).fit(X_train, y_train)
print("Random Forest Accuracy:", accuracy_score(y_test, rf.predict(X_test)))

Output

Random Forest Accuracy: 1.0
Graph 1 produced by DS program 19: Random Forest
Graph · Program 19

Viva: which module is used and why

Q. Why load_wine from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_wine() loads the built-in Wine dataset (178 samples, 3 classes).

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why RandomForestClassifier from sklearn.ensemble?

A. sklearn.ensemble: random forests and boosting. RandomForestClassifier averages many decision trees (bagging).

Q. Why accuracy_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… accuracy_score() is correct predictions ÷ total.

Viva: what does each line do?

  1. X, y = load_wine(return_X_y=True)

    X = the input columns (features), y = the answer column the model must predict (target). load_wine() loads the built-in Wine dataset (178 samples, 3 classes). return_X_y=True returns (X, y) directly instead of a Bunch object.

  2. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.3 keeps 30% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. rf = RandomForestClassifier(n_estimators=100, random_state=42).fit(X_train, y_train)

    RandomForestClassifier averages many decision trees (bagging). n_estimators is the number of trees in the forest. random_state fixes the randomness so you get the same result every run. The result is stored in rf.

  4. print("Random Forest Accuracy:", accuracy_score(y_test, rf.predict(X_test)))

    Prints "Random Forest Accuracy:" with the result. accuracy_score() is correct predictions ÷ total. predict() gives the model's predicted labels or values.

Viva: concepts

Q. Why is a random forest better than one tree?

A. Many trees on random samples vote together, which reduces overfitting (variance).

Q. n_estimators=100 means…

A. The forest has 100 decision trees. More trees means more stable predictions, but slower.

Q. A random forest classifies by…

A. A majority vote of its trees. Each tree sees a bootstrap sample and random feature subsets (bagging).

Q. The Wine dataset has…

A. 178 samples, 13 features, 3 classes. Useful when they ask you to describe the dataset.

Viva: "change it to…"

→ 50 trees

RandomForestClassifier(n_estimators=50, random_state=42)

→ Which features matter most

print(rf.feature_importances_)

Program 20

Naive Bayes

Naive Bayes classification.

Run it

Algorithm

1. Start
2. Load iris and split 70/30
3. GaussianNB().fit(X_train, y_train)
4. Print the test accuracy
5. Stop

Program

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

nb = GaussianNB().fit(X_train, y_train)
print("Naive Bayes Accuracy:", accuracy_score(y_test, nb.predict(X_test)))

Output

Naive Bayes Accuracy: 0.9777777777777777
Graph 1 produced by DS program 20: Naive Bayes
Graph · Program 20

Viva: which module is used and why

Q. Why load_iris from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why GaussianNB from sklearn.naive_bayes?

A. sklearn.naive_bayes: Naive Bayes classifiers. GaussianNB is Naive Bayes for numeric features, assuming each follows a normal distribution.

Q. Why accuracy_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… accuracy_score() is correct predictions ÷ total.

Viva: what does each line do?

  1. X, y = load_iris(return_X_y=True)

    X = the input columns (features), y = the answer column the model must predict (target). load_iris() loads the built-in Iris dataset (150 flowers, 3 species). No download needed. return_X_y=True returns (X, y) directly instead of a Bunch object.

  2. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.3 keeps 30% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. nb = GaussianNB().fit(X_train, y_train)

    GaussianNB is Naive Bayes for numeric features, assuming each follows a normal distribution. fit() learns from the training data. The result is stored in nb.

  4. print("Naive Bayes Accuracy:", accuracy_score(y_test, nb.predict(X_test)))

    Prints "Naive Bayes Accuracy:" with the result. accuracy_score() is correct predictions ÷ total. predict() gives the model's predicted labels or values.

Viva: concepts

Q. Why 'naive'?

A. It assumes all features are independent of each other given the class, which is rarely true but works well.

Q. What is 'naive' about Naive Bayes?

A. It assumes features are independent given the class. That assumption is rarely true, but it still works well.

Q. GaussianNB assumes that, within each class, each feature…

A. Is normally distributed. It learns a mean and variance per feature per class.

Q. For text word counts you would use…

A. MultinomialNB. BernoulliNB is for yes/no word presence.

Viva: "change it to…"

→ Use the wine data

from sklearn.datasets import load_wine
X, y = load_wine(return_X_y=True)

→ Confusion matrix

from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, nb.predict(X_test)))

Program 21

Logistic regression

Logistic Regression for binary classification.

Run it

Algorithm

1. Start
2. Load_breast_cancer(return_X_y=True), split 75/25
3. Make_pipeline(StandardScaler(), LogisticRegression())
4. Print the accuracy and predict_proba for one sample
5. Stop

Program

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
print("Logistic Regression Accuracy:", accuracy_score(y_test, model.predict(X_test)))
print("P(benign) for first test sample:", model.predict_proba(X_test[:1])[0, 1])

Output

Logistic Regression Accuracy: 0.9790209790209791
P(benign) for first test sample: 0.8766704261947693
Graph 1 produced by DS program 21: Logistic regression
Graph · Program 21

Viva: which module is used and why

Q. Why load_breast_cancer from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_breast_cancer() loads a built-in binary classification dataset.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why make_pipeline from sklearn.pipeline?

A. sklearn.pipeline: chaining preprocessing and model steps. make_pipeline() chains steps (e.g. scaler → model) into one estimator.

Q. Why StandardScaler from sklearn.preprocessing?

A. sklearn.preprocessing: scalers and encoders. StandardScaler rescales each feature to mean 0 and std 1.

Q. Why LogisticRegression from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. LogisticRegression is a classifier: it passes a linear score through the sigmoid.

Q. Why accuracy_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… accuracy_score() is correct predictions ÷ total.

Viva: what does each line do?

  1. X, y = load_breast_cancer(return_X_y=True)

    X = the input columns (features), y = the answer column the model must predict (target). load_breast_cancer() loads a built-in binary classification dataset. return_X_y=True returns (X, y) directly instead of a Bunch object.

  2. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.25 keeps 25% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  3. model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)

    make_pipeline() chains steps (e.g. scaler → model) into one estimator. StandardScaler rescales each feature to mean 0 and std 1. LogisticRegression is a classifier: it passes a linear score through the sigmoid.

  4. print("Logistic Regression Accuracy:", accuracy_score(y_test, model.predict(X_test)))

    Prints "Logistic Regression Accuracy:" with the result. accuracy_score() is correct predictions ÷ total. predict() gives the model's predicted labels or values.

  5. print("P(benign) for first test sample:", model.predict_proba(X_test[:1])[0, 1])

    Prints "P(benign) for first test sample:" with the result. predict_proba() gives the probability for each class.

Viva: concepts

Q. Is logistic regression regression?

A. No, it is a classifier. It uses the sigmoid to turn a score into a probability between 0 and 1.

Q. Logistic regression outputs…

A. A probability, through the sigmoid function. The class is 1 if the probability is ≥ 0.5.

Q. In load_breast_cancer, target 1 means…

A. Benign (0 = malignant). Check data.target_names: ['malignant', 'benign'].

Q. Why put StandardScaler in the pipeline?

A. The features have very different ranges; scaling helps the solver converge. Without it you often get a ConvergenceWarning.

Viva: "change it to…"

→ Predicted class for the first sample

print(model.predict(X_test[:1]))

→ Confusion matrix

from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, model.predict(X_test)))

Program 22

Compare classifiers

Compare classification algorithms on the same dataset.

Run it

Algorithm

1. Start
2. Load wine and scale X with StandardScaler
3. Put 6 models in a dict
4. Loop: fit, predict, print accuracy aligned with f'{name:20s}'
5. Stop

Program

from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB

X, y = load_wine(return_X_y=True)
X = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

models = {"Logistic Regression": LogisticRegression(), "kNN": KNeighborsClassifier(),
          "Decision Tree": DecisionTreeClassifier(random_state=42), "SVM": SVC(),
          "Random Forest": RandomForestClassifier(random_state=42), "Naive Bayes": GaussianNB()}
for name, model in models.items():
    model.fit(X_train, y_train)
    print(f"{name:20s} Accuracy: {accuracy_score(y_test, model.predict(X_test)):.4f}")

Output

Logistic Regression  Accuracy: 0.9815
kNN                  Accuracy: 0.9630
Decision Tree        Accuracy: 0.9630
SVM                  Accuracy: 0.9815
Random Forest        Accuracy: 1.0000
Naive Bayes          Accuracy: 1.0000
Graph 1 produced by DS program 22: Compare classifiers
Graph · Program 22

Viva: which module is used and why

Q. Why load_wine from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_wine() loads the built-in Wine dataset (178 samples, 3 classes).

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why StandardScaler from sklearn.preprocessing?

A. sklearn.preprocessing: scalers and encoders. StandardScaler rescales each feature to mean 0 and std 1.

Q. Why accuracy_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… accuracy_score() is correct predictions ÷ total.

Q. Why LogisticRegression from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. LogisticRegression is a classifier: it passes a linear score through the sigmoid.

Q. Why KNeighborsClassifier from sklearn.neighbors?

A. sklearn.neighbors: k-nearest neighbours. KNeighborsClassifier labels a point by majority vote of its k nearest neighbours.

Q. Why DecisionTreeClassifier from sklearn.tree?

A. sklearn.tree: decision trees. DecisionTreeClassifier splits the data with if/else rules on the features.

Q. Why SVC from sklearn.svm?

A. sklearn.svm: support vector machines. SVC is a support vector classifier: it finds the widest-margin boundary.

Q. Why RandomForestClassifier from sklearn.ensemble?

A. sklearn.ensemble: random forests and boosting. RandomForestClassifier averages many decision trees (bagging).

Q. Why GaussianNB from sklearn.naive_bayes?

A. sklearn.naive_bayes: Naive Bayes classifiers. GaussianNB is Naive Bayes for numeric features, assuming each follows a normal distribution.

Viva: what does each line do?

  1. X, y = load_wine(return_X_y=True)

    X = the input columns (features), y = the answer column the model must predict (target). load_wine() loads the built-in Wine dataset (178 samples, 3 classes). return_X_y=True returns (X, y) directly instead of a Bunch object.

  2. X = StandardScaler().fit_transform(X)

    StandardScaler rescales each feature to mean 0 and std 1. fit_transform() learns the transformation and applies it in one step.

  3. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.3 keeps 30% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  4. models = {"Logistic Regression": LogisticRegression(), "kNN": KNeighborsClassifier(),
              "Decision Tree": DecisionTreeClassifier(random_state=42), "SVM": SVC(),
              "Random Forest": RandomForestClassifier(random_state=42), "Naive Bayes": GaussianNB()}

    LogisticRegression is a classifier: it passes a linear score through the sigmoid. KNeighborsClassifier labels a point by majority vote of its k nearest neighbours. DecisionTreeClassifier splits the data with if/else rules on the features. The result is stored in models.

  5. for name, model in models.items():

    Loop: repeats the indented lines for every name, model in models.items(). items() gives (name, model) pairs so the loop can use both.

  6.     model.fit(X_train, y_train)

    fit() learns from the training data.

  7.     print(f"{name:20s} Accuracy: {accuracy_score(y_test, model.predict(X_test)):.4f}")

    Prints "… Accuracy: …" with the result.

Viva: concepts

Q. f'{name:20s}' does what?

A. Pads the name to 20 characters so the columns line up. :.4f in the same line formats a number to 4 decimals.

Q. What is slightly off about scaling before train_test_split?

A. Test data leaks into the scaler's mean/std. Strictly, fit the scaler on train only (see program 40). Fine for a lab, worth mentioning in a viva.

Q. Which models benefit most from scaling?

A. kNN and SVM (distance-based). Trees split one feature at a time, so scale doesn't matter to them.

Viva: "change it to…"

→ Print the best model

scores = {}
# inside the loop: scores[name] = accuracy_score(y_test, model.predict(X_test))
print("Best:", max(scores, key=scores.get))

→ Use iris instead of wine

from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)

Clustering (find groups, no labels)

Program 23

K-Means clustering

K-Means clustering.

Run it

Algorithm

1. Start
2. X, _ = make_blobs(n_samples=300, centers=4, ...)
3. KMeans(n_clusters=4, n_init=10, random_state=42).fit_predict(X)
4. Print cluster_centers_
5. Scatter coloured by label, with centres as red X
6. Stop

Program

import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.8, random_state=42)
kmeans = KMeans(n_clusters=4, n_init=10, random_state=42)
labels = kmeans.fit_predict(X)
print("Cluster Centres:\n", kmeans.cluster_centers_)

plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.scatter(*kmeans.cluster_centers_.T, c='red', marker='X', s=200)
plt.title("K-Means Clustering")
plt.show()

Output

Cluster Centres:
 [[-2.63715917  8.98563949]
 [-6.84180708 -6.84038791]
 [ 4.70253968  2.02807134]
 [-8.83330596  7.21790214]]
Graph 1 produced by DS program 23: K-Means clustering
Graph · Program 23

Viva: which module is used and why

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why make_blobs from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). make_blobs() creates synthetic clusters, which is ideal for clustering demos.

Q. Why KMeans from sklearn.cluster?

A. sklearn.cluster: K-Means, agglomerative and other clustering. KMeans groups points around k centroids.

Viva: what does each line do?

  1. X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.8, random_state=42)

    make_blobs() creates synthetic clusters, which is ideal for clustering demos. n_samples is how many rows to generate. centers is how many clusters make_blobs creates.

  2. kmeans = KMeans(n_clusters=4, n_init=10, random_state=42)

    KMeans groups points around k centroids. n_clusters=4: the number of groups to find. n_init is how many times K-Means restarts with new centroids (the best run is kept). The result is stored in kmeans.

  3. labels = kmeans.fit_predict(X)

    fit_predict() fits a clustering model and returns each point's cluster. The result is stored in labels.

  4. print("Cluster Centres:\n", kmeans.cluster_centers_)

    Prints "Cluster Centres:" with the result. cluster_centers_ holds the final centroid coordinates.

  5. plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')

    scatter() plots x against y as dots, which shows the relationship. c= colours each point (here by its cluster label). cmap picks the colour map (e.g. 'coolwarm', 'Blues').

  6. plt.scatter(*kmeans.cluster_centers_.T, c='red', marker='X', s=200)

    scatter() plots x against y as dots, which shows the relationship. cluster_centers_ holds the final centroid coordinates. .T transposes the array (rows ↔ columns).

  7. plt.title("K-Means Clustering")

    title() puts a heading on the graph.

  8. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. How does K-Means work?

A. Pick k centres, assign each point to the nearest centre, move each centre to the mean of its points, repeat until nothing changes.

Q. n_init=10 means…

A. Run 10 times from different starting centroids and keep the best. K-Means can get stuck in bad local optima.

Q. A common way to choose k is…

A. The elbow method on inertia_ (or the silhouette score). Plot inertia for k = 1..10 and look for the bend.

Q. plt.scatter(*kmeans.cluster_centers_.T, ...) works because…

A. The transpose gives [all x, all y], and * unpacks them as two arguments. Same as scatter(centers[:, 0], centers[:, 1]).

Viva: "change it to…"

→ 3 clusters

make_blobs(n_samples=300, centers=3, ...)
KMeans(n_clusters=3, n_init=10, random_state=42)

→ Elbow method to choose k

for k in range(1, 11):
    print(k, KMeans(n_clusters=k, n_init=10).fit(X).inertia_)

Program 24

Hierarchical clustering

Hierarchical clustering with dendrogram.

Run it

Algorithm

1. Start
2. Z = linkage(X, method='ward')
3. Fcluster(Z, t=3, criterion='maxclust') gives the labels
4. Dendrogram(Z) then plt.show()
5. Stop

Program

import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
from sklearn.datasets import make_blobs

X, _ = make_blobs(n_samples=50, centers=3, cluster_std=2.5, random_state=7)
Z = linkage(X, method='ward')
print("Cluster labels:", fcluster(Z, t=3, criterion='maxclust'))

dendrogram(Z)
plt.title("Hierarchical Clustering Dendrogram")
plt.xlabel("Sample index")
plt.ylabel("Distance")
plt.show()

Output

Cluster labels: [3 1 3 2 3 3 3 1 2 1 3 1 2 2 3 2 3 3 2 1 3 3 1 2 3 3 3 3 1 3 1 2 1 2 3 3 1
 3 2 3 1 3 2 1 3 1 3 1 1 1]
Graph 1 produced by DS program 24: Hierarchical clustering
Graph · Program 24

Viva: which module is used and why

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why linkage, dendrogram and fcluster from scipy.cluster.hierarchy?

A. scipy.cluster.hierarchy: linkage, dendrogram and fcluster for hierarchical clustering. linkage() builds the hierarchical merge tree that the dendrogram draws. dendrogram() draws the hierarchical clustering tree. fcluster() cuts the dendrogram into flat cluster labels.

Q. Why make_blobs from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). make_blobs() creates synthetic clusters, which is ideal for clustering demos.

Viva: what does each line do?

  1. X, _ = make_blobs(n_samples=50, centers=3, cluster_std=2.5, random_state=7)

    make_blobs() creates synthetic clusters, which is ideal for clustering demos. n_samples is how many rows to generate. centers is how many clusters make_blobs creates.

  2. Z = linkage(X, method='ward')

    linkage() builds the hierarchical merge tree that the dendrogram draws. method picks how cluster distance is measured ('ward', 'single', 'complete'). The result is stored in Z.

  3. print("Cluster labels:", fcluster(Z, t=3, criterion='maxclust'))

    Prints "Cluster labels:" with the result. fcluster() cuts the dendrogram into flat cluster labels. criterion='maxclust' means: cut the tree into exactly t clusters.

  4. dendrogram(Z)

    dendrogram() draws the hierarchical clustering tree.

  5. plt.title("Hierarchical Clustering Dendrogram")

    title() puts a heading on the graph.

  6. plt.xlabel("Sample index")

    xlabel() names the x-axis.

  7. plt.ylabel("Distance")

    ylabel() names the y-axis.

  8. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. Agglomerative (bottom-up) clustering starts with…

A. Every point as its own cluster. It keeps merging the closest pair until one cluster is left.

Q. Ward linkage merges the pair that…

A. Least increases the within-cluster variance. Other options: 'single', 'complete', 'average'.

Q. fcluster(Z, t=3, criterion='maxclust')…

A. Cuts the tree into 3 flat clusters. Visually: a horizontal cut through the dendrogram.

Viva: "change it to…"

→ Single linkage

Z = linkage(X, method='single')

→ 4 clusters

fcluster(Z, t=4, criterion='maxclust')

Program 25

Compare clustering

Compare clustering algorithms using performance metrics.

Run it

Algorithm

1. Start
2. Make_blobs with 4 centres of different spreads
3. KMeans, AgglomerativeClustering, GaussianMixture
4. Silhouette_score (higher is better) and davies_bouldin_score (lower is better)
5. Stop

Program

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans, AgglomerativeClustering
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score, davies_bouldin_score

X, _ = make_blobs(n_samples=400, centers=4, cluster_std=[0.6, 1.2, 0.8, 1.6], random_state=42)

models = {'K-Means': KMeans(n_clusters=4, n_init=10, random_state=42),
          'Agglomerative': AgglomerativeClustering(n_clusters=4),
          'Gaussian Mixture': GaussianMixture(n_components=4, random_state=42)}
for name, m in models.items():
    labels = m.fit_predict(X)
    print(f"{name:16s} Silhouette: {silhouette_score(X, labels):.4f}  Davies-Bouldin: {davies_bouldin_score(X, labels):.4f}")

Output

K-Means          Silhouette: 0.7821  Davies-Bouldin: 0.3085
Agglomerative    Silhouette: 0.7820  Davies-Bouldin: 0.3093
Gaussian Mixture Silhouette: 0.7751  Davies-Bouldin: 0.3142
Graph 1 produced by DS program 25: Compare clustering
Graph · Program 25

Viva: which module is used and why

Q. Why make_blobs from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). make_blobs() creates synthetic clusters, which is ideal for clustering demos.

Q. Why KMeans and AgglomerativeClustering from sklearn.cluster?

A. sklearn.cluster: K-Means, agglomerative and other clustering. KMeans groups points around k centroids. AgglomerativeClustering merges the closest clusters bottom-up (hierarchical clustering).

Q. Why GaussianMixture from sklearn.mixture?

A. sklearn.mixture: Gaussian mixture models. GaussianMixture models the data as a mix of Gaussian blobs (soft clustering).

Q. Why silhouette_score and davies_bouldin_score from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… silhouette_score() runs from −1 to 1; higher means tighter, better-separated clusters. davies_bouldin_score(): lower is better; it compares cluster spread with the distance between clusters.

Viva: what does each line do?

  1. X, _ = make_blobs(n_samples=400, centers=4, cluster_std=[0.6, 1.2, 0.8, 1.6], random_state=42)

    make_blobs() creates synthetic clusters, which is ideal for clustering demos. n_samples is how many rows to generate. centers is how many clusters make_blobs creates.

  2. models = {'K-Means': KMeans(n_clusters=4, n_init=10, random_state=42),
              'Agglomerative': AgglomerativeClustering(n_clusters=4),
              'Gaussian Mixture': GaussianMixture(n_components=4, random_state=42)}

    KMeans groups points around k centroids. n_clusters=4: the number of groups to find. n_init is how many times K-Means restarts with new centroids (the best run is kept). The result is stored in models.

  3. for name, m in models.items():

    Loop: repeats the indented lines for every name, m in models.items(). items() gives (name, model) pairs so the loop can use both.

  4.     labels = m.fit_predict(X)

    fit_predict() fits a clustering model and returns each point's cluster. The result is stored in labels.

  5.     print(f"{name:16s} Silhouette: {silhouette_score(X, labels):.4f}  Davies-Bouldin: {davies_bouldin_score(X, labels):.4f}")

    Prints "… Silhouette: … Davies-Bouldin: …" with the result.

Viva: concepts

Q. Silhouette score ranges from…

A. −1 to 1, higher is better. Close to 1 means tight, well-separated clusters.

Q. Davies–Bouldin index: better clusters give…

A. A lower value. It averages how similar each cluster is to its closest neighbour.

Q. Gaussian Mixture differs from K-Means because it…

A. Gives soft (probabilistic) memberships with elliptical clusters. Use gmm.predict_proba(X) to see the probabilities.

Viva: "change it to…"

→ Only K-Means silhouette

labels = KMeans(n_clusters=4, n_init=10).fit_predict(X)
print(silhouette_score(X, labels))

→ Try 3 clusters

n_clusters=3   # and n_components=3 for GaussianMixture

EDA and the full project

Program 39

Exploratory data analysis

Exploratory Data Analysis (EDA) on a real-world dataset.

Run it

Algorithm

1. Start
2. Df = load_wine(as_frame=True).frame
3. Df.info(), df.describe(), df.isnull().sum()
4. Sns.boxplot(data=df, x='target', y='alcohol')
5. Stop

Program

import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine

df = load_wine(as_frame=True).frame

df.info()
print("\nSummary Statistics:\n", df.describe())
print("\nMissing Values:\n", df.isnull().sum())

sns.boxplot(data=df, x='target', y='alcohol')
plt.title("Alcohol by Wine Class")
plt.show()

Output

<class 'pandas.DataFrame'>
RangeIndex: 178 entries, 0 to 177
Data columns (total 14 columns):
 #   Column                        Non-Null Count  Dtype
---  ------                        --------------  -----
 0   alcohol                       178 non-null    float64
 1   malic_acid                    178 non-null    float64
 2   ash                           178 non-null    float64
 3   alcalinity_of_ash             178 non-null    float64
 4   magnesium                     178 non-null    float64
 5   total_phenols                 178 non-null    float64
 6   flavanoids                    178 non-null    float64
 7   nonflavanoid_phenols          178 non-null    float64
 8   proanthocyanins               178 non-null    float64
 9   color_intensity               178 non-null    float64
 10  hue                           178 non-null    float64
 11  od280/od315_of_diluted_wines  178 non-null    float64
 12  proline                       178 non-null    float64
 13  target                        178 non-null    int64
dtypes: float64(13), int64(1)
memory usage: 19.6 KB

Summary Statistics:
           alcohol  malic_acid  ...      proline      target
count  178.000000  178.000000  ...   178.000000  178.000000
mean    13.000618    2.336348  ...   746.893258    0.938202
std      0.811827    1.117146  ...   314.907474    0.775035
min     11.030000    0.740000  ...   278.000000    0.000000
25%     12.362500    1.602500  ...   500.500000    0.000000
50%     13.050000    1.865000  ...   673.500000    1.000000
75%     13.677500    3.082500  ...   985.000000    2.000000
max     14.830000    5.800000  ...  1680.000000    2.000000

[8 rows x 14 columns]

Missing Values:
 alcohol                         0
malic_acid                      0
ash                             0
alcalinity_of_ash               0
magnesium                       0
total_phenols                   0
flavanoids                      0
nonflavanoid_phenols            0
proanthocyanins                 0
color_intensity                 0
hue                             0
od280/od315_of_diluted_wines    0
proline                         0
target                          0
dtype: int64
Graph 1 produced by DS program 39: Exploratory data analysis
Graph · Program 39

Viva: which module is used and why

Q. Why import seaborn as sns?

A. seaborn: statistical plots built on matplotlib. sns is just a short name so we can type sns.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why load_wine from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_wine() loads the built-in Wine dataset (178 samples, 3 classes).

Viva: what does each line do?

  1. df = load_wine(as_frame=True).frame

    load_wine() loads the built-in Wine dataset (178 samples, 3 classes). as_frame=True returns the dataset as a pandas DataFrame. .frame is the dataset as one DataFrame (with as_frame=True).

  2. df.info()

    info() prints the column names, non-null counts and data types (it prints by itself).

  3. print("\nSummary Statistics:\n", df.describe())

    Prints "Summary Statistics:" with the result. describe() gives count, mean, std, min, quartiles and max per numeric column.

  4. print("\nMissing Values:\n", df.isnull().sum())

    Prints "Missing Values:" with the result. isnull() marks missing values as True; add .sum() to count them per column. sum() adds values (per column for a DataFrame).

  5. sns.boxplot(data=df, x='target', y='alcohol')

    boxplot() shows the median, quartiles and outliers. data=df tells seaborn which table to take the columns from.

  6. plt.title("Alcohol by Wine Class")

    title() puts a heading on the graph.

  7. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

Viva: concepts

Q. What is EDA?

A. Exploratory Data Analysis: understanding data with summaries and graphs (shape, types, missing values, distributions, outliers) before modelling.

Q. df.info() shows…

A. Columns, non-null counts, dtypes and memory use. It's the quickest check for missing values and wrong dtypes.

Q. In df.describe(), the 50% row is…

A. The median. 25% and 75% are the 1st and 3rd quartiles.

Q. df.isnull().sum() returns…

A. The count of missing values in each column. True counts as 1 when you sum.

Viva: "change it to…"

→ First 5 rows

print(df.head())

→ Correlation heatmap

sns.heatmap(df.corr(), cmap='coolwarm')
plt.show()

→ Histogram of alcohol

df['alcohol'].hist(bins=20)
plt.show()

Program 40

End-to-end application

End-to-end data science app: preprocess, visualize, model, evaluate, predict.

Run it

Algorithm

1. Start
2. Load → drop_duplicates().dropna()
3. Split 80/20, then scaler.fit_transform(X_train) and scaler.transform(X_test)
4. Visualise the class balance with sns.countplot
5. Fit LogisticRegression, print confusion_matrix + classification_report
6. Predict one sample and map it with target_names
7. Stop

Program

import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix

# 1. Load data
data = load_breast_cancer(as_frame=True)
df = data.frame

# 2. Preprocessing
df = df.drop_duplicates().dropna()
X, y = df.drop(columns='target'), df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train, X_test = scaler.fit_transform(X_train), scaler.transform(X_test)

# 3. Visualization
sns.countplot(x=y)
plt.title("Class Balance (0 = malignant, 1 = benign)")
plt.show()

# 4. Model
model = LogisticRegression().fit(X_train, y_train)

# 5. Evaluation
y_pred = model.predict(X_test)
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test, y_pred))

# 6. Prediction
print("Prediction for first test patient:", data.target_names[model.predict(X_test[:1])[0]])

Output

Confusion Matrix:
 [[41  2]
 [ 1 70]]

Classification Report:
               precision    recall  f1-score   support

           0       0.98      0.95      0.96        43
           1       0.97      0.99      0.98        71

    accuracy                           0.97       114
   macro avg       0.97      0.97      0.97       114
weighted avg       0.97      0.97      0.97       114

Prediction for first test patient: benign
Graph 1 produced by DS program 40: End-to-end application
Graph · Program 40

Viva: which module is used and why

Q. Why import seaborn as sns?

A. seaborn: statistical plots built on matplotlib. sns is just a short name so we can type sns.something.

Q. Why import matplotlib.pyplot as plt?

A. matplotlib.pyplot: the plotting interface, imported as plt. plt is just a short name so we can type plt.something.

Q. Why load_breast_cancer from sklearn.datasets?

A. sklearn.datasets: built-in datasets (load_*) and generators (make_*). load_breast_cancer() loads a built-in binary classification dataset.

Q. Why train_test_split from sklearn.model_selection?

A. sklearn.model_selection: splitting and cross-validation tools. train_test_split() splits the data into training and test sets.

Q. Why StandardScaler from sklearn.preprocessing?

A. sklearn.preprocessing: scalers and encoders. StandardScaler rescales each feature to mean 0 and std 1.

Q. Why LogisticRegression from sklearn.linear_model?

A. sklearn.linear_model: linear and logistic regression, Ridge, Lasso. LogisticRegression is a classifier: it passes a linear score through the sigmoid.

Q. Why classification_report and confusion_matrix from sklearn.metrics?

A. sklearn.metrics: accuracy, precision, recall, F1, R², silhouette… classification_report() prints precision, recall and F1 for every class. confusion_matrix() counts TP, FP, FN and TN for each class.

Viva: what does each line do?

  1. data = load_breast_cancer(as_frame=True)

    load_breast_cancer() loads a built-in binary classification dataset. as_frame=True returns the dataset as a pandas DataFrame. The result is stored in data.

  2. df = data.frame

    .frame is the dataset as one DataFrame (with as_frame=True). The result is stored in df.

  3. df = df.drop_duplicates().dropna()

    drop_duplicates() removes repeated rows. dropna() removes rows (or columns) that contain missing values.

  4. X, y = df.drop(columns='target'), df['target']

    X = the input columns (features), y = the answer column the model must predict (target). drop() removes the named rows or columns (axis=1 for columns). columns='target' names the column to remove.

  5. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    train_test_split() splits the data into training and test sets. test_size=0.2 keeps 20% of the rows for testing; the rest train the model. random_state fixes the randomness so you get the same result every run. You get 4 parts: features and answers for training, and features and answers for testing. The result is stored in X_train, X_test, y_train, y_test.

  6. scaler = StandardScaler()

    StandardScaler rescales each feature to mean 0 and std 1. The result is stored in scaler.

  7. X_train, X_test = scaler.fit_transform(X_train), scaler.transform(X_test)

    fit_transform() learns the transformation and applies it in one step. transform() applies a fitted transformation to new data. The result is stored in X_train, X_test.

  8. sns.countplot(x=y)

    sns.countplot() shows how many rows fall in each category.

  9. plt.title("Class Balance (0 = malignant, 1 = benign)")

    title() puts a heading on the graph.

  10. plt.show()

    plt.show() displays the figure (in Spyder it appears in the Plots pane).

  11. model = LogisticRegression().fit(X_train, y_train)

    LogisticRegression is a classifier: it passes a linear score through the sigmoid. fit() learns from the training data.

  12. y_pred = model.predict(X_test)

    predict() gives the model's predicted labels or values. The result is stored in y_pred.

  13. print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))

    Prints "Confusion Matrix:" with the result. confusion_matrix() counts TP, FP, FN and TN for each class.

  14. print("\nClassification Report:\n", classification_report(y_test, y_pred))

    Prints "Classification Report:" with the result. classification_report() prints precision, recall and F1 for every class.

  15. print("Prediction for first test patient:", data.target_names[model.predict(X_test[:1])[0]])

    Prints "Prediction for first test patient:" with the result. target_names holds the class names behind the numeric labels. predict() gives the model's predicted labels or values.

Viva: concepts

Q. Why fit the scaler only on train?

A. So no information from the test set leaks into training. The test set must stay unseen.

Q. Why fit_transform on X_train but only transform on X_test?

A. So no information from the test set leaks into the scaler. The test set must stay unseen data.

Q. In classification_report, 'support' is…

A. The number of true samples of each class in the test set. 43 malignant + 71 benign = 114 test rows.

Q. 'macro avg' in classification_report is…

A. The plain average over classes. 'weighted avg' weights each class by its support.

Viva: "change it to…"

→ Use Random Forest instead

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state=42).fit(X_train, y_train)

→ Print accuracy

from sklearn.metrics import accuracy_score
print("Accuracy:", accuracy_score(y_test, y_pred))

Subject viva

Basics

Q. What is data science?

A. An interdisciplinary field that uses statistics, programming and domain knowledge to extract insight from data. The usual pipeline is collect → clean → explore → model → evaluate → communicate.

Q. Difference between data science, machine learning and AI?

A. AI is the broad goal of machines acting intelligently. ML is the subset of AI that learns patterns from data. Data science uses ML along with statistics, visualisation and data engineering to answer questions with data.

Q. Structured vs unstructured data?

A. Structured data fits rows and columns (CSV, SQL tables). Unstructured data has no fixed schema: text, images, audio. Semi-structured data (JSON, XML) has tags but no rigid table.

Pandas

Q. Series vs DataFrame?

A. A Series is a 1-D labelled array (one column). A DataFrame is a 2-D labelled table made of Series that share an index.

Q. loc vs iloc?

A. loc selects by labels (row/column names), iloc by integer positions. df.loc[0:2] includes label 2, df.iloc[0:2] stops before position 2.

Preprocessing

Q. Ways to handle missing values?

A. Drop rows or columns (dropna), impute with the mean, median or mode (fillna), forward/backward fill for time series, or model-based imputation. Use the median when there are outliers.

Q. Normalisation vs standardisation?

A. Normalisation (MinMaxScaler) rescales to [0, 1]. Standardisation (StandardScaler) gives mean 0 and std 1. Distance-based models like kNN, SVM and K-Means need one of them.

Q. How do you encode categorical variables?

A. Label encoding maps categories to integers, fine for ordinal data or trees. One-hot encoding (pd.get_dummies) makes one 0/1 column per category, which suits nominal data and linear models.

Q. What is an outlier and how do you detect one?

A. A value far from the rest. Detect it with box plots or the IQR rule (below Q1 − 1.5·IQR or above Q3 + 1.5·IQR), or with z-scores (|z| > 3).

Statistics

Q. Mean vs median vs mode?

A. The mean is the average, the median is the middle value, the mode is the most frequent value. With skewed data or outliers, the median describes the centre better.

Q. Covariance vs correlation?

A. Both measure how two variables move together. Covariance depends on the units; correlation divides by both standard deviations, so it lies between −1 and 1 and has no units.

Q. What is a p-value and what does α = 0.05 mean?

A. The p-value is the probability of seeing results this extreme if H₀ is true. If p < α = 0.05 we reject H₀, accepting a 5% chance of a Type I error (a false positive).

Q. Type I vs Type II error?

A. Type I: rejecting a true H₀ (false positive, probability α). Type II: failing to reject a false H₀ (false negative, probability β). Power = 1 − β.

Q. What is the Central Limit Theorem?

A. The distribution of sample means approaches a normal distribution as the sample size grows (n ≥ 30 is the usual rule), whatever the population's shape. That is what justifies t-tests and confidence intervals.

ML

Q. Supervised vs unsupervised learning?

A. Supervised learning has labelled targets: regression for numbers, classification for classes. Unsupervised learning finds structure without labels: clustering, dimensionality reduction.

Q. What is overfitting and how do you prevent it?

A. The model memorises the training noise: high training accuracy, poor test accuracy. Prevent it with more data, cross-validation, regularisation (Ridge/Lasso), pruning or max_depth, dropout, or simpler models.

Q. Explain the bias–variance trade-off.

A. Bias is error from a model that is too simple (underfitting). Variance is error from sensitivity to the training data (overfitting). Increasing complexity lowers bias and raises variance; the best model balances the two.

Q. Why split into train and test sets?

A. To estimate performance on unseen data. Fit only on train, evaluate on test. Cross-validation repeats this over k folds for a steadier estimate.

Evaluation

Q. When is accuracy misleading?

A. On imbalanced data: 95% 'not fraud' gives 95% accuracy while catching no fraud. Use precision, recall, F1, ROC-AUC or the confusion matrix instead.

Q. Precision vs recall: when does each matter?

A. Precision = TP/(TP+FP), which matters when false alarms are costly (spam filters). Recall = TP/(TP+FN), which matters when misses are costly (cancer screening). F1 is their harmonic mean.

Q. What do R² and RMSE tell you in regression?

A. R² is the fraction of variance in y the model explains (1 is perfect). RMSE is the typical prediction error in the target's own units.

Models

Q. Linear vs logistic regression?

A. Linear regression predicts a continuous value with a straight line. Logistic regression predicts a class probability by passing a linear score through the sigmoid; it is a classifier despite the name.

Q. Bagging vs boosting?

A. Bagging (Random Forest) trains models in parallel on bootstrap samples and averages them, which reduces variance. Boosting (AdaBoost, XGBoost) trains models one after another, each fixing the previous one's errors, which reduces bias.

Q. How does K-Means work?

A. Pick k centroids, assign each point to its nearest centroid, move each centroid to the mean of its points, and repeat until nothing changes. Choose k with the elbow method or the silhouette score.

Q. What is PCA used for?

A. Dimensionality reduction: it projects the data onto orthogonal directions (principal components) of maximum variance. It is used for visualisation, noise removal and speeding up models. Scale the data first.

Visualisation

Q. Which chart for which question?

A. Distribution → histogram or box plot. Relationship → scatter plot. Comparison across categories → bar chart. Composition → pie or stacked bar. Correlation matrix → heatmap. Trend over time → line chart.