Home / Past papers / MLP End Term / this paper
Consider following common data and answer the subquestions:
What will be the output of the following code snippet? Enter -1, if you think the above code snippet will generate an error.
What will be the output of the following code snippet? Enter -1, if you think the above code snippet will generate an error.
What will be the output of the following code snippet? Enter -1, if you think the above code snippet will generate an error.
What will be the output of the following code snippet? Enter -1, if you think the above code snippet will generate an error.
Consider following parameter grid for regression with RandomForest: How many unique combinations of hyperparameters are there in the above parameter grid?

















































What will be the output of the following code?
What will be the output of the following code? Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Here’s a structured summary of core topics, concepts, principles, and equations essential for the Diploma Level: Machine Learning Practice (Computer-Based Exam). The exam covers Pandas, Scikit-Learn, ML algorithms, preprocessing, model evaluation, and clustering. ---
DataFrame Operations:
df.shape → (rows, columns).df.isna().sum().sum() → Total missing values.df.column.value_counts() → Frequency of unique values.df.query("condition") → Filter rows.df.iloc[:, n] → Select column n; df.loc[index, column] → Select by label.df.column.mean() (ignores NaN by default).Handling Missing Data:
df.dropna().KNNImputer(n_neighbors=k) (for numerical data).Data Types:
float64 (default for decimals), int64, object (strings/categorical).df.dtypes.NaN):Data Preprocessing:
Scaling:
StandardScaler (standardizes to mean=0, std=1).MinMaxScaler (scales to [0, 1]).Polynomial Features:
PolynomialFeatures(degree=d, include_bias=True/False).include_bias=True, adds a column of 1s (for intercept).Encoding:
DictVectorizer (for feature extraction from dictionaries).OneHotEncoder (for categorical variables).Train-Test Split:
train_test_split(X, y, test_size=0.3, random_state=42).random_state ensures reproducibility.Pipelines:
make_pipeline(step1, step2, ...) → Sequential processing (e.g., impute → scale → model).Example:
pipe = Pipeline([
('imputer', KNNImputer(n_neighbors=3)),
('scaler', StandardScaler()),
('model', LinearRegression())
])Model Evaluation:
R² score (model.score(X_test, y_test)).Classification:
precision_score, recall_score, confusion_matrix.DummyClassifier(strategy='most_frequent') → Predicts the majority class.where = mean, = standard deviation.
degree=2 and features , output includes (if include_bias=True).| Model | Key Parameters | Use Case | Equation |
|---|---|---|---|
| LinearRegression | - | Regression | (closed-form solution via OLS) |
| RidgeRegression | alpha (regularization strength) | Regression (L2 penalty) | |
| LassoRegression | alpha | Regression (L1 penalty, sparsity) | |
| SGDRegressor | max_iter, tol, learning_rate | Large datasets | Iterative update: |
| LogisticRegression | C (inverse of alpha), class_weight | Binary classification | , where = sigmoid function. |
| Perceptron | tol, shuffle | Linear classification |
Regularization:
alpha=0 → No regularization (e.g., RidgeClassifier(alpha=0)).alpha → Stronger penalty.max_iter (not max_epoch).Logistic Regression:
class_weight='balanced' adjusts weights inversely to class frequencies.C controls regularization (smaller C → stronger regularization).| Model | Key Parameters | Use Case | Key Concepts |
|---|---|---|---|
| DecisionTree | max_depth, min_samples_split, criterion (gini/entropy for classification, mse/mae for regression) | Classification/Regression | Splits data recursively; max_depth limits tree depth to prevent overfitting. |
| RandomForest | n_estimators, bootstrap, max_features | Ensemble learning | Bagging (bootstrap aggregating) of decision trees. |
| BaggingClassifier | base_estimator, n_estimators, max_samples | Reduce variance | Trains base models on bootstrapped samples. |
| VotingClassifier | estimators, voting (hard/soft) | Ensemble learning | soft voting averages predicted probabilities. |
Decision Trees:
min_samples_split=2 (default): Minimum samples to split a node.min_samples_leaf=1 (default): Minimum samples in a leaf.Random Forest:
bootstrap=True (default): Samples with replacement.max_features='sqrt' (default for classification): Features considered for splits.Bagging vs. Boosting:
| Model | Key Parameters | Use Case | Key Concepts |
|---|---|---|---|
| KNeighborsClassifier | n_neighbors, weights (uniform/distance) | Classification | Predicts majority class of k nearest neighbors. |
| KNeighborsRegressor | n_neighbors, weights | Regression | Predicts average of k nearest neighbors. |
StandardScaler).n_neighbors:
k → Complex boundaries (overfitting).k → Smooth boundaries (underfitting).| Model | Key Parameters | Use Case | Key Concepts |
|---|---|---|---|
| SVC | C, kernel (linear, rbf), gamma | Classification | Maximizes margin; C controls misclassification penalty. |
| SVR | C, kernel, epsilon | Regression | Fits a tube around data; epsilon defines tube width. |
rbf for non-linear boundaries).StandardScaler).| Model | Key Parameters | Use Case | Key Concepts |
|---|---|---|---|
| KMeans | n_clusters, init (random/k-means++), n_init | General-purpose clustering | Minimizes within-cluster sum of squares (inertia). |
| AgglomerativeClustering | n_clusters, linkage (ward, complete, average) | Hierarchical clustering | Merges closest clusters iteratively. |
K-Means:
inertia: Sum of squared distances to centroids (lower = better).n_init: Number of times to run with different centroid seeds.Agglomerative Clustering:
Linkage Methods:
ward: Minimizes variance.complete: Maximizes distance between clusters.where = set of centroids.
| Metric | Formula | Interpretation |
|---|---|---|
| Accuracy | Overall correctness. | |
| Precision | Correctness of positive predictions. | |
| Recall (Sensitivity) | Ability to find all positive instances. | |
| F1-Score | Harmonic mean of precision and recall. | |
| Confusion Matrix | TP, TN, FP, FN for each class. |
| Metric | Formula | Interpretation |
|---|---|---|
| R² Score | Proportion of variance explained (1 = perfect fit). | |
| MSE | Average squared error. |
| Method | Description | Use Case |
|---|---|---|
| Leave-One-Out (LOOCV) | Uses samples for training, 1 for testing (repeated times). | Small datasets. |
| k-Fold CV | Splits data into folds; each fold used once for testing. | General-purpose. |
strategy='most_frequent').class_weight='balanced' or resampling.Grid Search:
ParameterGrid generates all combinations of hyperparameters.Example:
param_grid = {
'n_estimators': [10, 20, 30],
'max_features': [2, 3, 4]
}Common Parameters:
n_estimators, max_depth, min_samples_leaf.C, kernel, gamma.n_neighbors, weights.Effects:
Affected Algorithms:
Unaffected Algorithms:
| Type | Definition | Example |
|---|---|---|
| Ordinal | Categories with order. | Satisfaction (Low, Medium, High). |
| Nominal | Categories without order. | Blood type (A, B, AB, O). |
| Topic | Equation | Description |
|---|---|---|
| Linear Regression | Predicted value. | |
| Ridge Regression | L2 regularization. | |
| Lasso Regression | L1 regularization (sparsity). | |
| Logistic Regression | Sigmoid function for probabilities. | |
| Perceptron | Linear classifier. | |
| K-Means Inertia | Within-cluster sum of squares. | |
| Precision | Correct positive predictions. | |
| Recall | True positives found. | |
| R² Score | Variance explained. | |
| Standard Scaling | Normalizes features. | |
| Min-Max Scaling | Scales to [0, 1]. | |
| Polynomial Features | For , degree=2: | Generates interaction terms. |
Pandas:
df.shape, df.isna().sum(), df.value_counts().iloc, loc) and querying (df.query).Scikit-Learn:
RandomForestClassifier(n_estimators=100)).fit, predict, score methods.Algorithms:
alpha, C).max_depth, min_samples_split, bootstrap.n_neighbors.C parameter.Evaluation:
Clustering:
n_init, scaling.ward, complete).Hyperparameter Tuning:
ParameterGrid.{'a': [1,2], 'b': [3,4]} → 4 combinations.Special Cases:
DummyClassifier: Predicts majority class.DictVectorizer: For dictionary-to-feature matrix.PolynomialFeatures: include_bias adds intercept term.Common Pitfalls:
class_weight='balanced'.max_iter (SGD) with n_estimators (Random Forest).