Home / Past papers / MLP End Term / this paper
Consider the following Python code using Pandas: What does the groupby operation in the code achieve?































Consider a dataset representing various attributes of red wine, loaded into a Pandas DataFrame named data using the following code: Suppose we are interested in extracting the value of the chlorides attribute for the third sample in the dataset (2nd by index). Which of the following expressions correctly achieves this? chlorides is at the 4th index of columns.



















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 summary is organized by themes (e.g., preprocessing, model evaluation, algorithms) with key equations, Python snippets, and conceptual notes. --- ---
Standardization/Normalization:
Handling Missing Data:
SimpleImputer: Replaces missing values with mean/median/mode.
from sklearn.impute import SimpleImputer
si = SimpleImputer(strategy="mean")
si.fit_transform(data)si.statistics_ gives the computed means/medians.Categorical Encoding:
OneHotEncoder: Converts categorical features to binary columns.
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(sparse_output=False)
encoded = ohe.fit_transform(data[['category']])LabelEncoder: Converts categories to integers (not recommended for features).
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y_encoded = le.fit_transform(y)Feature Selection:
SelectKBest: Selects top-k features based on statistical tests (e.g., chi-squared, ANOVA).
from sklearn.feature_selection import SelectKBest, chi2
skb = SelectKBest(chi2, k=3)
X_selected = skb.fit_transform(X, y)
skb.scores_: Scores for each feature.skb.pvalues_: p-values for hypothesis testing.Regression Metrics:
Classification Metrics:
Cross-Validation:
GridSearchCV: Exhaustive search over hyperparameters.
from sklearn.model_selection import GridSearchCV
param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf']}
grid_search = GridSearchCV(SVC(), param_grid, cv=5)
grid_search.fit(X, y)RandomizedSearchCV: Random sampling of hyperparameters.
from sklearn.model_selection import RandomizedSearchCV
param_dist = {'C': loguniform(1e-4, 1e0), 'kernel': ['linear', 'rbf']}
random_search = RandomizedSearchCV(SVC(), param_dist, n_iter=10, cv=3)LeaveOneOut (LOO): Uses n-1 samples for training, 1 for testing.
from sklearn.model_selection import LeaveOneOut, cross_val_score
loo = LeaveOneOut()
scores = cross_val_score(model, X, y, cv=loo)Linear Regression:
Higher → more regularization (prevents overfitting).
Logistic Regression:
SGDClassifier/Regressor:
Key Parameters:
loss: 'hinge', 'log', 'squared_error'.penalty: 'l1', 'l2', 'elasticnet'.alpha: Regularization strength.warm_start: Reuses previous solution for faster training.Example:
from sklearn.linear_model import SGDClassifier
clf = SGDClassifier(loss="hinge", penalty="l2", alpha=0.001)SVC/SVR:
Kernel Trick: Maps data to higher dimensions for linear separation.
'linear', 'poly', 'rbf', 'sigmoid'.Regularization (C):
Example:
from sklearn.svm import SVC
clf = SVC(kernel='rbf', C=1.0)Hyperparameters:
max_depth: Maximum tree depth.min_samples_split: Minimum samples to split a node.min_samples_leaf: Minimum samples in a leaf.Example:
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(max_depth=3, min_samples_leaf=5)MLPClassifier/Regressor:
Key Parameters:
hidden_layer_sizes: Tuple specifying neurons per layer (e.g., (10, 5)).activation: 'logistic', 'tanh', 'relu'.alpha: L2 regularization strength.solver: 'adam', 'sgd', 'lbfgs'.Example:
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(10,), alpha=0.01)Bagging (e.g., Random Forest):
RandomForestClassifier:
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=100, max_depth=5)BaggingClassifier:
from sklearn.ensemble import BaggingClassifier
bag_clf = BaggingClassifier(KNeighborsClassifier(), n_estimators=30)Boosting (e.g., AdaBoost, Gradient Boosting):
Voting Classifier:
Example:
from sklearn.ensemble import VotingClassifier
eclf = VotingClassifier(
estimators=[('lr', LogisticRegression()), ('svm', SVC())],
voting='soft'
)K-Means:
Elbow Method: Plot inertia vs. k to find optimal k.
from sklearn.cluster import KMeans
inertias = []
for k in range(1, 11):
kmeans = KMeans(n_clusters=k)
kmeans.fit(X)
inertias.append(kmeans.inertia_)
plt.plot(range(1, 11), inertias)Types of Clustering:
PCA (Principal Component Analysis):
t-SNE:
Hyperparameters:
n_neighbors: Number of neighbors to consider.weights: 'uniform' or 'distance' (closer neighbors have more influence).CountVectorizer:
max_features: Limits vocabulary size.Example:
from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(max_features=1000)
X = vectorizer.fit_transform(texts)Overfitting/Underfitting:
Overfitting: High training score, low test score.
Underfitting: Low training/test scores.
Hyperparameter Tuning:
GridSearchCV or RandomizedSearchCV.loguniform(1e-4, 1e0)) for parameters like alpha.Neural Networks:
Activation Functions:
'identity' (regression), 'logistic' (binary classification).Imbalanced Data:
class_weight='balanced') or resampling (SMOTE).| Task | Code Snippet |
|---|---|
| Standardize data | StandardScaler().fit_transform(X) |
| Impute missing values | SimpleImputer(strategy='mean').fit_transform(X) |
| Train-test split | train_test_split(X, y, test_size=0.2, random_state=42) |
| Grid search | GridSearchCV(estimator, param_grid, cv=5).fit(X, y) |
| K-Means clustering | KMeans(n_clusters=3).fit(X) |
| Feature selection | SelectKBest(chi2, k=5).fit_transform(X, y) |
| Neural network | MLPClassifier(hidden_layer_sizes=(10,), solver='adam').fit(X, y) |
| Cross-validation | cross_val_score(model, X, y, cv=LeaveOneOut()) |
| One-hot encoding | OneHotEncoder().fit_transform(X[['category']]) |
| Voting classifier | VotingClassifier([('lr', LogisticRegression()), ('svm', SVC())]).fit(X, y) |
LabelEncoder for features (use OneHotEncoder instead).random_state for reproducibility.Misinterpreting predict vs. predict_proba:
predict: Returns class labels.predict_proba: Returns class probabilities.| Concept | Equation |
|---|---|
| Standardization | |
| MinMax Scaling | |
| R² Score | |
| RMSE | |
| Ridge Loss | |
| Lasso Loss | |
| Logistic Regression | , where |
| Neural Network Parameters | |
| K-Means Inertia | |
| Decision Tree Entropy |