Machine Learning Practice · Quiz 1 · Jan 2025
Machine Learning Practice · Quiz 1 · Jan 2025
← Course papers · Start practice / exam
Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.
21 / 22 published solutions
Select the correct options from the following:
Posterior distribution for p is Beta(91, 11).
Posterior distribution for p is Beta(11, 91).
Posterior distribution for p is Bernoulli(0.1).
Posterior distribution for p is Bernoulli(0.9).
We are given a Binomial sampling process where \( n = 100 \) items are sampled and \( k = 10 \) items are found to be defective, with a prior distribution for the defective proportion \( p \) given by \( \text{Beta}(\alpha_0, \beta_0) = \text{Beta}(1, 1) \).
**1. Beta-Binomial Conjugate Prior Update:**
When the prior distribution of \( p \) is \( \text{Beta}(\alpha_0, \beta_0) \) and we observe \( k \) successes (defectives) and \( n - k \) failures (non-defectives) in \( n \) independent Bernoulli trials, the posterior distribution of \( p \) is also a Beta distribution with updated parameters:
\[ \alpha_{\text{post}} = \alpha_0 + k, \quad \beta_{\text{post}} = \beta_0 + (n - k) \]
**2. Substitute the Given Values:**
- \( \alpha_{\text{post}} = 1 + 10 = 11 \)
- \( \beta_{\text{post}} = 1 + (100 - 10) = 1 + 90 = 91 \)
Therefore, the posterior distribution for \( p \) is \( \text{Beta}(11, 91) \).
**Answer: Posterior distribution for p is Beta(11, 91).**
A: **Incorrect:** Swaps the number of defectives (`10`) and non-defectives (`90`), giving `Beta(91, 11)` instead of `Beta(11, 91)`.
B: **Correct:** Adding `k = 10` defectives to `alpha_0 = 1` and `n - k = 90` non-defectives to `beta_0 = 1` yields `Beta(11, 91)`.
C: **Incorrect:** The posterior distribution of a continuous proportion `p` under a Beta prior is a Beta distribution, not a discrete Bernoulli distribution.
D: **Incorrect:** A Bernoulli distribution models a single binary outcome, not the continuous parameter `p`.
Question 145 NAT · 2.0 marks
Find the posterior mean. Enter the answer correct to two decimal places.
A published solution is not available for this question yet.
Question 147 MCQ · 2.0 marks
What is the primary risk of not performing a train-test split in a machine learning workflow?
The training time will increase.
The model might overfit the training data and perform poorly on new data.
The dataset may become unbalanced.
The model may fail to converge.
Published solution
In a machine learning workflow, a **train-test split** separates the dataset into a training set (used to fit the model) and a held-out test set (used to evaluate generalization on unseen data).
**Primary Risk of Omitting a Train-Test Split:**
If you train and evaluate a model on the exact same dataset without holding out a test set, the model can memorize noise and specific patterns in the training data (**overfitting**). You will have no reliable way to detect that the model fails to generalize and performs poorly on new, unseen data.
**Answer: The model might overfit the training data and perform poorly on new data.**
A: **Incorrect:** Not splitting the data uses 100% of samples for training, which only marginally affects training time and is not the primary methodological risk.
B: **Correct:** Without an independent test set, overfitting goes undetected and the model may perform poorly on new, unseen data.
C: **Incorrect:** Skipping a train-test split does not alter the class balance of the dataset.
D: **Incorrect:** Convergence of an optimization algorithm depends on learning rate, scaling, and loss surface, not on whether a test split was created.
Question 148 MCQ · 2.0 marks
Why is data preprocessing necessary before using it for model building?
The data may contain outliers or missing values due to errors in data
collection.
Features may have different scales, affecting model performance.
The dataset may include non-numerical features that need to be converted to
numerical representations.
All of these
Published solution
**Data preprocessing** is essential before training machine learning models for all of the following reasons:
**1. Handling Outliers and Missing Values:**
Real-world data often contains missing entries (`NaN`/null) or extreme outliers due to collection errors, which can cause algorithms to crash or skew parameter estimates.
**2. Feature Scaling:**
Features measured in different units (e.g., age vs income) have vastly different numerical scales, which can distort distance-based and gradient-based models.
**3. Encoding Non-Numerical Features:**
Categorical and text features must be converted into numerical representations (e.g., via one-hot or ordinal encoding) so mathematical models can process them.
**Answer: All of these.**
A: **Incorrect:** While true, this is only one of the reasons; Options B and C are also necessary.
B: **Incorrect:** While true, Options A and C are also valid reasons for data preprocessing.
C: **Incorrect:** While true, Options A and B are also valid reasons for data preprocessing.
D: **Correct:** Cleaning missing values/outliers, scaling features, and encoding categorical variables are all fundamental reasons why data preprocessing is necessary.
Question 149 MCQ · 2.0 marks
It specifies the tolerance level for early stopping based on the change in the
validation error.
It controls the learning rate of the stochastic regressor during training.
It determines the maximum number of iterations for the training process.
It defines the fraction of the validation set used for early stopping.
Published solution
In `sklearn.linear_model.SGDRegressor`, when `early_stopping=True` is enabled, a fraction (`validation_fraction=0.2`) of the training data is set aside as a validation set.
**Role of the `tol` Parameter:**
- The `tol` parameter specifies the **stopping criterion tolerance**.
- Specifically, when `early_stopping=True`, training stops when the validation score does not improve by at least `tol` (`0.001`) for `n_iter_no_change` (`5`) consecutive epochs.
**Answer: It specifies the tolerance level for early stopping based on the change in the validation error.**
A: **Correct:** `tol` sets the minimum improvement threshold in the validation score/loss required to continue training before triggering early stopping after `n_iter_no_change` epochs.
B: **Incorrect:** The learning rate is controlled by `eta0` and `learning_rate`, not `tol`.
C: **Incorrect:** The maximum number of epochs is controlled by `max_iter`, not `tol`.
D: **Incorrect:** The validation set fraction is controlled by `validation_fraction=0.2`, not `tol`.
Question 150 MCQ · 2.0 marks
Suppose we want to transform features in a dataset using polynomial transformation. The sklearn
API provides the functionality in which of the following modules?
sklearn.dataset
sklearn.model_selection
sklearn.preprocessing
sklearn.featureSelection
sklearn.featureExtraction
Published solution
In scikit-learn (`sklearn`), polynomial feature transformation is implemented by the `PolynomialFeatures` class.
**Module Location:**
`PolynomialFeatures` is located in the **`sklearn.preprocessing`** module:
`from sklearn.preprocessing import PolynomialFeatures`
**Answer: sklearn.preprocessing.**
A: **Incorrect:** `sklearn.datasets` (not `dataset`) is used for loading/generating datasets.
B: **Incorrect:** `sklearn.model_selection` contains splitting and cross-validation tools like `train_test_split` and `GridSearchCV`.
C: **Correct:** `PolynomialFeatures` is provided in the `sklearn.preprocessing` module.
D: **Incorrect:** Feature selection is in `sklearn.feature_selection` (snake_case), and does not contain `PolynomialFeatures`.
E: **Incorrect:** Feature extraction is in `sklearn.feature_extraction` (snake_case) for text/image extraction, not polynomial feature expansion.
Question 151 MCQ · 3.0 marks
1000
100
99
999
Published solution
Let us analyze how **Leave-One-Out Cross-Validation (`LeaveOneOut()`)** works on a dataset with \( N = 1000 \) data points and \( d = 100 \) features:
**1. How `LeaveOneOut` Splits the Data:**
- `LeaveOneOut` creates \( N \) separate train-test splits, where in each fold, **1 sample** is held out as the validation set and the remaining **\( N - 1 = 999 \) samples** are used as the training set.
- It iterates over all \( N = 1000 \) data points (not features).
**2. Number of Models Trained:**
Because `cross_val_score` fits one model per fold across all \( N = 1000 \) folds, it generates **1000 models** during execution.
**Answer: 1000.**
A: **Correct:** `LeaveOneOut` performs `N = 1000` folds (one per data point), training 1000 separate models.
B: **Incorrect:** 100 is the number of features, whereas `LeaveOneOut` splits across the 1000 samples.
C: **Incorrect:** `LeaveOneOut` splits across samples (`N = 1000`), not `d - 1 = 99` features.
D: **Incorrect:** Each fold trains on 999 samples, but there are 1000 folds in total, so 1000 models are trained.
Question 152 MCQ · 3.0 marks
Published solution
Let us compare the two linear regression models `reg1` and `reg2`:
**1. True Data-Generating Process:**
`y = np.dot(X, np.array([1, 2])) + 3`
Thus, the true relationship is \( y = 1 x_0 + 2 x_1 + 3 \), which has a **non-zero intercept of \( +3 \)**.
**2. Model 1 (`reg1` with `fit_intercept = False`):**
- `reg1` forces the regression plane to pass through the origin (\( w_0 = 0 \)).
- Because the true data has a non-zero intercept of \( 3 \) and the columns of \( X \) are not collinear with a constant vector, `reg1` cannot fit the data perfectly, so its \( R^2 \) score satisfies \( s_1 < 1.0 \).
**3. Model 2 (`reg2` with `fit_intercept = True`):**
- `reg2` estimates both the weights \( [1, 2] \) and the intercept \( 3 \), fitting the noiseless linear data **perfectly** with zero residual error.
- Thus, its \( R^2 \) score is \( s_2 = 1.0 \).
Therefore, \( s_1 < s_2 \).
**Answer: s1 < s2.**
A: **Incorrect:** Because the true target `y` includes a `+ 3` intercept, `fit_intercept=False` cannot achieve the perfect `R^2 = 1.0` score that `fit_intercept=True` achieves.
B: **Correct:** `reg2` (`fit_intercept=True`) recovers the exact linear relationship including the `+ 3` intercept (`s2 = 1.0`), whereas `reg1` (`fit_intercept=False`) has residual error (`s1 < 1.0`), so `s1 < s2`.
C: **Incorrect:** Adding a free intercept parameter to an OLS model on the training set can never decrease the training `R^2` score.
Question 153 MSQ · 2.0 marks
Published solution
Let us trace how `LabelEncoder` works on `data = ["cat", "dog", "fish", "cat", "bird", "dog", "bird"]`:
**1. Unique Classes Sorted Alphabetically:**
`LabelEncoder` finds the unique strings in `data` and sorts them in **lexicographical (alphabetical) order**:
- Index `0`: `"bird"`
- Index `1`: `"cat"`
- Index `2`: `"dog"`
- Index `3`: `"fish"`
**2. Evaluate Each Option:**
- **Option A**: Since there are 4 unique categories, `encoded_data` contains only the integer values `0, 1, 2, and 3` (specifically `[1, 2, 3, 1, 0, 2, 0]`). (**True**)
- **Option B**: `"elephant"` was not seen during `fit()`, so calling `encoder.transform(["elephant"])` raises a `ValueError: y contains previously unseen labels`. (**False**)
- **Option C**: `LabelEncoder` assigns integers based on **alphabetical order** of labels, not frequency. (**False**)
- **Option D**: Since index `2` corresponds to `"dog"` in the sorted classes `["bird", "cat", "dog", "fish"]`, calling `encoder.inverse_transform([2])` returns `array(['dog'])`. (**True**)
**Answer: Options A and D.**
A: **Correct:** With 4 unique strings (`bird`, `cat`, `dog`, `fish`), `LabelEncoder` maps them to integers `0, 1, 2, 3`.
B: **Incorrect:** Passing an unseen label (`"elephant"`) to `encoder.transform()` raises a `ValueError`.
C: **Incorrect:** `LabelEncoder` assigns integer codes in alphabetical order (`bird=0, cat=1, dog=2, fish=3`), not by frequency.
D: **Correct:** In alphabetical order, index 2 is `"dog"`, so `encoder.inverse_transform([2])` returns `"dog"`.
Question 154 MSQ · 2.0 marks
Which of the following Evaluation metrics can be used in a regression problem?
Mean Squared Error
Accuracy
F1-Score
Mean Absolute Error
credit score
CGPA
Published solution
Let us check which of the listed metrics are standard evaluation metrics for a **regression** problem (where the target is continuous):
- **Mean Squared Error (MSE)** (Option A): Measures the average squared difference between continuous predicted and actual values: \( \frac{1}{n}\sum (y_i - \hat{y}_i)^2 \). (**Regression metric**)
- **Accuracy** (Option B): Measures the fraction of exact class matches; used for **classification**, not regression.
- **F1-Score** (Option C): Harmonic mean of precision and recall; used for **classification**, not regression.
- **Mean Absolute Error (MAE)** (Option D): Measures the average absolute difference between continuous predicted and actual values: \( \frac{1}{n}\sum |y_i - \hat{y}_i| \). (**Regression metric**)
- **credit score / CGPA** (Options E, F): Domain-specific quantities, not general machine learning evaluation metrics.
**Answer: Mean Squared Error and Mean Absolute Error (Options A and D).**
A: **Correct:** Mean Squared Error (MSE) is a standard evaluation metric for regression models.
B: **Incorrect:** Accuracy is a classification metric.
C: **Incorrect:** F1-Score is a classification metric.
D: **Correct:** Mean Absolute Error (MAE) is a standard evaluation metric for regression models.
E: **Incorrect:** Credit score is a financial application output, not an ML evaluation metric.
F: **Incorrect:** CGPA is an academic grade average, not an ML evaluation metric.
Question 155 NAT · 2.0 marks
Published solution
Let us trace the `SimpleImputer` execution on the 2D array `data`:
**1. Input Matrix `data`:**
\[
\begin{array}{ccc}
\text{Col 0} & \text{Col 1} & \text{Col 2} \\
\hline
1 & 2 & 3 \\
6 & 0 & -1 \\
3 & -1 & 4
\end{array}
\]
Here `missing_values = -1` and `strategy = 'median'`.
**2. Imputing `data_imputed[1, 2]` (Row 1, Column 2):**
- The entry at `[1, 2]` is `-1`, which is marked as a missing value (`missing_values = -1`).
- `SimpleImputer` computes the **median of the non-missing values in Column 2**.
- In Column 2, the entries are `3`, `-1` (missing), and `4`. The non-missing values are `3` and `4`.
- The median of `3` and `4` is:
\[ \text{Median}(3, 4) = \frac{3 + 4}{2} = 3.5 \]
Thus, `data_imputed[1, 2]` is replaced with **3.5**.
**Answer: 3.5.**
Question 156 NAT · 3.0 marks
Published solution
Let us find the value of \( W_2 \) (`reg.coef_[1]`) step by step:
**1. Examine the Training Data:**
- `X_train = [[1, 2], [2, 4], [3, 6], [4, 8]]`
- `y_train = [1, 2, 3, 4]`
Notice that for every sample, \( X_1 = y \) and \( X_2 = 2 X_1 = 2 y \), with intercept \( W_0 = 0 \) (`fit_intercept=False`).
**2. Use the Model Equation and Given Constraint:**
- The linear equation with \( W_0 = 0 \) is:
\[ Y = W_1 X_1 + W_2 X_2 \]
- Since \( X_2 = 2 X_1 \) and \( Y = X_1 \), substituting into the equation (with zero error) gives:
\[ X_1 = W_1 X_1 + W_2 (2 X_1) \implies W_1 + 2 W_2 = 1 \]
- We are also given (and minimum-norm least squares satisfies) \( W_2 = 2 W_1 \), so \( W_1 = \frac{1}{2} W_2 \).
**3. Solve for \( W_2 \):**
\[ \frac{1}{2} W_2 + 2 W_2 = 1 \implies 2.5 W_2 = 1 \implies W_2 = \frac{1}{2.5} = 0.4 \]
(And \( W_1 = 0.2 \), so `reg.coef_` is `[0.2, 0.4]`, and `reg.coef_[1]` prints **0.4**.)
**Answer: 0.4.**
Question 157 MSQ · 2.0 marks
Consider the given Table 1: Banking data for the given subquestions stored as pandas dataframe
in variable df
Based on the above data, answer the given subquestions.
Which of the columns in the banking data are nominal features?
Job
Marital
Education
Housing
Contact
Published solution
Let us classify each categorical feature in Table 1 (`Banking Data`) as **nominal** (categories with no inherent natural order) vs **ordinal** (categories with a meaningful rank/order):
- **Job** (Option A): Categories like `unemployed`, `management`, `self-employed`, `blue-collar`, `admin`, `technician` have no natural mathematical ordering \( \rightarrow \) **Nominal**.
- **Marital** (Option B): Categories like `married`, `single` have no natural ordering \( \rightarrow \) **Nominal**.
- **Education** (Option C): Categories `primary` < `secondary` < `tertiary` have a clear natural progression/hierarchy \( \rightarrow \) **Ordinal** (not nominal).
- **Housing** (Option D): Categories `yes`, `no` have no ranking \( \rightarrow \) **Nominal**.
- **Contact** (Option E): Categories `telephone`, `cellular` have no ranking \( \rightarrow \) **Nominal**.
**Answer: Job, Marital, Housing, and Contact (Options A, B, D, and E).**
A: **Correct:** `Job` is a nominal categorical feature with no intrinsic ordering.
B: **Correct:** `Marital` status (`married`, `single`) is a nominal categorical feature.
C: **Incorrect:** `Education` (`primary`, `secondary`, `tertiary`) has a natural hierarchical order, so it is an ordinal feature.
D: **Correct:** `Housing` (`yes`, `no`) is a binary nominal feature.
E: **Correct:** `Contact` (`telephone`, `cellular`) is a nominal feature.
Question 158 MCQ · 2.0 marks
Consider the given Table 1: Banking data for the given subquestions stored as pandas dataframe
in variable df
Based on the above data, answer the given subquestions.
Choose the correct option to find the number of null values (represented as nan) present in the
Contact column
Published solution
In pandas, to count the number of missing (`NaN`/null) values in a Series `df["Contact"]`:
**1. `df["Contact"].isnull()`:**
Calling the `.isnull()` method (with parentheses) returns a boolean Series of the same length where `True` (`1`) indicates a null value and `False` (`0`) indicates a non-null value.
**2. `.sum()`:**
Chaining `.sum()` (with parentheses) sums the `True` (`1`) values, returning the total count of null values in the `Contact` column.
**Answer: df["Contact"].isnull().sum().**
A: **Correct:** `df["Contact"].isnull().sum()` creates a boolean mask of missing values and sums the `True` entries.
B: **Incorrect:** `isnull` is a method, so omitting `()` in `df["Contact"].isnull.sum()` raises an `AttributeError: 'function' object has no attribute 'sum'`.
C: **Incorrect:** Calling `.sum()` first on a string column containing `NaN` fails or concatenates strings, and `.isnull()` on a scalar is invalid.
D: **Incorrect:** Both `sum` and `isnull` are missing their method call parentheses `()`, and the order is reversed.
Question 159 MCQ · 2.0 marks
Consider the given Table 1: Banking data for the given subquestions stored as pandas dataframe
in variable df
Based on the above data, answer the given subquestions.
In **Contact** column which of the following statistical measures can be used to replace nan values?
Mean
Median
Mode
Variance
Published solution
Let us examine the data type of the **`Contact`** column in Table 1 (`Banking Data`):
**1. Feature Type:**
The `Contact` column contains non-numerical **categorical strings** (`telephone`, `cellular`, and missing values `nan`).
**2. Appropriate Imputation Statistic:**
- Numerical statistics such as **Mean**, **Median**, and **Variance** cannot be computed on nominal text categories like `'telephone'` and `'cellular'`.
- For a nominal categorical column, missing values are imputed using the **Mode** (the most frequently occurring category, which here is `'cellular'`).
**Answer: Mode.**
A: **Incorrect:** Mean can only be calculated for numerical data, not nominal strings like `'telephone'` and `'cellular'`.
B: **Incorrect:** Median requires numerical or ordered data and cannot be applied to nominal strings.
C: **Correct:** Since `Contact` is a categorical (nominal) column, the Mode (most frequent category) is the valid statistical measure to impute `nan` values.
D: **Incorrect:** Variance is a measure of numerical dispersion, not a central tendency measure or valid for categorical strings.
Question 160 MSQ · 2.0 marks
Consider the given Table 1: Banking data for the given subquestions stored as pandas dataframe
in variable df
Based on the above data, answer the given subquestions.
Which of the following options can be used to compute the median of the **Balance** column for
each category in the **Marital** feature?
Published solution
We want to compute the **median** of the `Balance` column grouped by each category in the `Marital` column:
- **Option A (`df.pivot_table(values='Balance', index='Marital', aggfunc="median")`)**:
Creates a pivot table indexed by `'Marital'`, aggregating the `'Balance'` column using the `'median'` function. (**Valid**)
- **Option B (`df.groupby('Marital').mean()`)**:
Computes the **mean** instead of the **median** (and fails on non-numeric columns if `numeric_only` is not set). (**Invalid**)
- **Option C (`df.apply('Marital').agg({'Balance': 'median'})`)**:
`df.apply('Marital')` is invalid because `.apply()` expects a function, not a column name string. (**Invalid**)
- **Option D (`df.groupby('Marital').agg({'Balance': 'median'})`)**:
Groups the DataFrame by `'Marital'` and aggregates the `'Balance'` column using `'median'`. (**Valid**)
**Answer: Options A and D.**
A: **Correct:** `df.pivot_table(values='Balance', index='Marital', aggfunc="median")` computes the median of `Balance` for each `Marital` category.
B: **Incorrect:** Uses `.mean()` instead of computing the median.
C: **Incorrect:** `df.apply('Marital')` is invalid syntax; grouping by a column requires `df.groupby('Marital')`.
D: **Correct:** `df.groupby('Marital').agg({'Balance': 'median'})` groups by `Marital` and computes the median of `Balance`.
Question 161 NAT · 1.0 marks
Consider the given Table 1: Banking data for the given subquestions stored as pandas dataframe
in variable df
Based on the above data, answer the given subquestions.
Published solution
Let us calculate `df["Age"].median()` from the 10 rows of Table 1 (`Banking Data`):
**1. Extract the 10 `Age` Values:**
The ages in the table are: \( 21, 49, 72, 31, 28, 39, 32, 59, 27, 47 \).
**2. Sort the `Age` Values in Ascending Order:**
\[ 21, \; 27, \; 28, \; 31, \; \mathbf{32}, \; \mathbf{39}, \; 47, \; 49, \; 59, \; 72 \]
**3. Compute the Median of \( n = 10 \) Values:**
Since \( n = 10 \) is even, the median is the average of the 5th and 6th sorted values (\( 32 \) and \( 39 \)):
\[ \text{Median} = \frac{32 + 39}{2} = \frac{71}{2} = 35.5 \]
**Answer: 35.5.**
Question 162 MCQ · 1.0 marks
Consider the given Table 1: Banking data for the given subquestions stored as pandas dataframe
in variable df
Based on the above data, answer the given subquestions.
secondary
329
2859
Error: Datatype not matching
Published solution
Let us trace the code `df_new = df["Age"] + df["Balance"]` and `print(df_new[4])`:
**1. Element-wise Series Addition:**
Both `df["Age"]` and `df["Balance"]` are integer Series, so `df["Age"] + df["Balance"]` adds the `Age` and `Balance` values row by row.
**2. Locate Index `4` ( the 5th Row, 0-indexed):**
- Row `0`: Age = 21, Balance = 77387
- Row `1`: Age = 49, Balance = 2037
- Row `2`: Age = 72, Balance = 132
- Row `3`: Age = 31, Balance = 298
- **Row `4`**: Age = **28**, Balance = **2831**
**3. Compute `df_new[4]`:**
\[ \text{df\_new}[4] = 28 + 2831 = 2859 \]
**Answer: 2859.**
A: **Incorrect:** `'secondary'` is the value in the `Education` column, not the sum of `Age` and `Balance`.
B: **Incorrect:** `329` (`31 + 298`) is the sum for row index `3` (the 4th row), whereas `df_new[4]` accesses 0-based index `4` (the 5th row).
C: **Correct:** At 0-based index 4 (the 5th row), `Age = 28` and `Balance = 2831`, so `28 + 2831 = 2859`.
D: **Incorrect:** Both `Age` and `Balance` are numeric (integer) columns, so they add together without any datatype error.
Question 163 MCQ · 2.0 marks
Consider the Following codeblock for the given subquestions.
Based on the above data, answer the given subquestions.
(7,5)
(3,5)
(5,3)
(5,7)
Published solution
Let us determine the shape of `transformed_df` produced by `ColumnTransformer`:
**1. Number of Rows (Samples):**
`df` has **5 rows**:
- `fruits`: `['apple', 'orange', 'banana', 'orange', 'apple']`
- `price`: `[10, 20, 5, 20, 10]`
- `color`: `['red', 'orange', 'yellow', 'orange', 'red']`
**2. Number of Columns (Features) After Transformation:**
- **`('Ohe', OneHotEncoder(), [0, 2])`** applies one-hot encoding to column `0` (`fruits`) and column `2` (`color`):
- `fruits` has **3 unique categories** (`'apple'`, `'banana'`, `'orange'`) \( \rightarrow 3 \) columns.
- `color` has **3 unique categories** (`'orange'`, `'red'`, `'yellow'`) \( \rightarrow 3 \) columns.
- **`('scaler', StandardScaler(), [1])`** applies standard scaling to column `1` (`price`) \( \rightarrow 1 \) column.
- Total columns \( = 3 + 3 + 1 = 7 \) columns.
Therefore, `transformed_df.shape` is **`(5, 7)`**.
**Answer: (5,7).**
A: **Incorrect:** Swaps the number of rows (5) and columns (7).
B: **Incorrect:** There are 5 rows and 7 transformed columns, not 3 rows and 5 columns.
C: **Incorrect:** `(5, 3)` is the shape of the original `df` before one-hot encoding expands `fruits` and `color` into 3 columns each.
D: **Correct:** There are 5 samples and `3 (fruits) + 3 (color) + 1 (price) = 7` output columns, giving shape `(5, 7)`.
Question 164 NAT · 1.0 marks
Consider the Following codeblock for the given subquestions.
Based on the above data, answer the given subquestions.
Published solution
Let us trace `ct.transformers_[1][1].mean_`:
**1. Identify `ct.transformers_[1][1]`:**
- In `transformers`, index `0` is `('Ohe', OneHotEncoder(), [0, 2])` and index `1` is `('scaler', StandardScaler(), [1])`.
- Thus, `ct.transformers_[1][1]` is the fitted `StandardScaler()` object applied to column `1` (`price`).
**2. Calculate the Mean of `price`:**
The values in `price` are `[10, 20, 5, 20, 10]`.
\[ \text{Mean} = \frac{10 + 20 + 5 + 20 + 10}{5} = \frac{65}{5} = 13 \]
**Answer: 13.**
Question 165 NAT · 2.0 marks
Consider the Following codeblock for the given subquestions.
Based on the above data, answer the given subquestions.
Published solution
Let us calculate `ct.transformers_[1][1].var_`, which is the **population variance** (`ddof=0`, used by `StandardScaler` in scikit-learn) of the `price` column `[10, 20, 5, 20, 10]`:
**1. Mean of `price`:**
From Question 164, the mean is \( \mu = 13 \).
**2. Squared Deviations from the Mean \( (x_i - 13)^2 \):**
- \( (10 - 13)^2 = (-3)^2 = 9 \)
- \( (20 - 13)^2 = (7)^2 = 49 \)
- \( (5 - 13)^2 = (-8)^2 = 64 \)
- \( (20 - 13)^2 = (7)^2 = 49 \)
- \( (10 - 13)^2 = (-3)^2 = 9 \)
**3. Compute the Variance (`var_`):**
\[ \sigma^2 = \frac{9 + 49 + 64 + 49 + 9}{5} = \frac{180}{5} = 36 \]
**Answer: 36.**
Question 166 MCQ · 2.0 marks
Consider the Following codeblock for the given subquestions.
Based on the above data, answer the given subquestions.
**Maths1**
**Section Id :** 64065379128
**Section Number :** 11
**Section type :** Online
**Mandatory or Optional :** Mandatory
**Number of Questions :** 14
**Number of Questions to be attempted :** 14
**Section Marks :** 50
**Display Number Panel :** Yes
**Section Negative Marks :** 0
**Group All Questions :** No
**Enable Mark as Answered Mark for Review and**
No
**Clear Response :**
**Section Maximum Duration :** 0
**Section Minimum Duration :** 0
**Section Time In :** Minutes
**Maximum Instruction Time :** 0
Published solution
Let us trace `ct.transform(df_new)` for the new sample `['orange', 22, 'orange']`:
**1. One-Hot Encoding of `fruits = 'orange'` (3 columns):**
- The unique categories of `fruits` sorted alphabetically are `['apple', 'banana', 'orange']`.
- Since `'orange'` is at index 2, its one-hot encoding is **`[0, 0, 1]`**.
**2. One-Hot Encoding of `color = 'orange'` (3 columns):**
- The unique categories of `color` sorted alphabetically are `['orange', 'red', 'yellow']`.
- Since `'orange'` is at index 0, its one-hot encoding is **`[1, 0, 0]`**.
**3. Standard Scaling of `price = 22` (1 column):**
- From Questions 164 and 165, the mean of `price` is \( \mu = 13 \) and the variance is \( \sigma^2 = 36 \), so the standard deviation is \( \sigma = \sqrt{36} = 6 \).
- The standardized value for `price = 22` is:
\[ z = \frac{x - \mu}{\sigma} = \frac{22 - 13}{6} = \frac{9}{6} = 1.50 \]
**4. Combined Output Row:**
Concatenating the three parts (`[0, 0, 1]`, `[1, 0, 0]`, and `[1.50]`) gives:
`[[0, 0, 1, 1, 0, 0, 1.50]]`.
**Answer: [[0, 0, 1, 1, 0, 0, 1.50]].**
A: **Incorrect:** Uses integer label encoding instead of `OneHotEncoder`, and computes an incorrect scaled value.
B: **Incorrect:** Encodes `color = 'orange'` as `[0, 0, 1]` instead of `[1, 0, 0]` (alphabetically `'orange'` comes before `'red'` and `'yellow'`).
C: **Incorrect:** Incorrect one-hot indices and divides by variance `36` (`9/36 = 0.25`) instead of standard deviation `6` (`9/6 = 1.50`).
D: **Correct:** `fruits='orange'` is `[0, 0, 1]`, `color='orange'` is `[1, 0, 0]`, and `price=22` scales to `(22 - 13) / 6 = 1.50`.
E: **Incorrect:** Divides `22 - 13 = 9` by variance `36` (`0.25`) instead of standard deviation `6` (`1.50`).