Unit 14: Machine Learning Packages in Python - Practice Quiz
1 Which pandas function is commonly used to import data from a CSV file?
pd.read_excel()
pd.DataFrame()
pd.to_csv()
pd.read_csv()
2 Which Python statement imports pandas using its conventional alias?
from pandas import sklearn
import pandas as plt
import pandas as pd
import pandas as sns
3 Which pandas function is designed to import a Microsoft Excel file?
pd.read_csv() with several additional plotting parameters
pd.read_excel()
pd.read_json()
pd.read_table()
4
What type of pandas object is usually returned by pd.read_csv()?
5
Which module is conventionally imported as plt for creating Matplotlib plots?
matplotlib.pyplot
matplotlib.image
matplotlib.animation
matplotlib.colors
6 Which function displays a completed Matplotlib figure?
plt.render_every_axis_and_export_the_result()
plt.show()
plt.draw_data()
plt.open()
7 Which function adds a title to a Matplotlib plot?
plt.title()
plt.legend()
plt.xlabel()
plt.caption()
8 Which function labels the horizontal axis in Matplotlib?
plt.legend() with an extended horizontal-axis configuration
plt.ylabel()
plt.xlabel()
plt.title()
9 Which Matplotlib function creates a simple line plot?
plt.hist()
plt.scatter()
plt.plot()
plt.bar()
10 Which Matplotlib function creates a scatter plot?
plt.scatter()
plt.build_a_chart_with_independent_marker_coordinates()
plt.pie()
plt.plot()
11 A line plot is especially useful for showing which kind of information?
12 What does each marker in a basic scatter plot usually represent?
13 What is the conventional alias used when importing Seaborn?
sea
sns
sbn
sb
14 Seaborn is primarily used for which task?
15 Seaborn is built on top of which plotting library?
16 Which Seaborn function is used to create a heatmap?
sns.scatterplot()
sns.heatmap()
sns.lineplot()
sns.color_every_numeric_cell_and_build_a_table()
17 How are numerical values mainly represented in a heatmap?
18
What does annot=True commonly do in sns.heatmap()?
19 What is Scikit-learn mainly used for?
20 Which Scikit-learn function commonly divides data into training and testing sets?
fit_transform()
separate_every_feature_by_manually_copying_the_dataset()
classification_report()
train_test_split()
21
A CSV file contains 30 columns, but an analysis requires only age, income, and target. Which approach imports only these columns with pandas?
pd.read_csv("data.csv", dtype=["age", "income", "target"])
pd.read_csv("data.csv", index_col=["age", "income", "target"])
pd.read_csv("data.csv", usecols=["age", "income", "target"])
pd.read_csv("data.csv", names=["age", "income", "target"])
22
A column named order_date contains values such as 2026-08-15. Which command converts it to a datetime type while importing the CSV?
pd.read_csv("orders.csv", dtype={"order_date": "date"})
pd.read_csv("orders.csv", date_format=["order_date"])
pd.read_csv("orders.csv", index_col=["order_date"])
pd.read_csv("orders.csv", parse_dates=["order_date"])
23
A dataset uses both NA and -999 to represent missing values. Which import option correctly recognizes both markers?
pd.read_csv("data.csv", fill_values=["NA", -999])
pd.read_csv("data.csv", na_values=["NA", -999])
pd.read_csv("data.csv", null_values={"NA": -999})
pd.read_csv("data.csv", dropna=["NA", -999])
24 You need two plots arranged side by side and want to modify each plot independently. Which statement creates the appropriate objects?
fig, axes = plt.subplots(2, 1)
fig, axes = plt.axes(1, 2)
fig, axes = plt.figure(1, 2)
fig, axes = plt.subplots(1, 2)
25 A saved Matplotlib image cuts off part of its axis labels. Which command is most appropriate for saving it without clipping the labels?
plt.savefig("plot.png", bbox_inches="tight")
plt.savefig("plot.png", orientation="landscape")
plt.savefig("plot.png", frameon=False)
plt.savefig("plot.png", transparent=True)
26
Given fig, ax = plt.subplots(), which code correctly adds a title and labels to that specific axes object?
ax.labels(title="Sales", x="Month", y="Revenue")
fig.axes(title="Sales", x="Month", y="Revenue")
fig.set(title="Sales", xlabel="Month", ylabel="Revenue")
ax.set(title="Sales", xlabel="Month", ylabel="Revenue")
27 A table contains measurements recorded at irregular times and stored in random row order. What should be done before drawing a line plot that represents temporal progression?
28
In plt.scatter(x, y, c=score, cmap="viridis"), what does the score array control?
29
Two lines are plotted with label="Actual" and label="Predicted", but their labels do not appear on the chart. Which additional call is required?
plt.colorbar()
plt.grid()
plt.legend()
plt.annotate()
30
A DataFrame contains height, weight, and a categorical column species. Which call creates a scatter plot whose point colors distinguish species?
sns.scatterplot(data=df, x="height", y="weight", palette="species")
sns.scatterplot(data=df, x="height", y="weight", hue="species")
sns.scatterplot(data=df, x="height", y="weight", size="species")
sns.scatterplot(data=df, x="height", y="weight", style=None)
31
A Seaborn line plot has repeated observations for each x-value. What does sns.lineplot display by default at each x-value?
32 You want all subsequent Seaborn plots to use a white-grid background and a colorblind-friendly palette. Which command applies both settings globally?
sns.set_palette(style="whitegrid", palette="colorblind")
sns.despine(style="whitegrid", palette="colorblind")
sns.set_theme(style="whitegrid", palette="colorblind")
sns.set_style(style="whitegrid", color="colorblind")
33
You have computed corr = df.corr(numeric_only=True) and want to hide its upper triangle, including the diagonal. Which call applies a suitable mask?
sns.heatmap(corr, mask=np.full_like(corr, False, dtype=bool))
sns.heatmap(corr, mask=np.diag(np.ones(len(corr))))
sns.heatmap(corr, mask=np.tril(np.ones_like(corr, dtype=bool)))
sns.heatmap(corr, mask=np.triu(np.ones_like(corr, dtype=bool)))
34 Which heatmap arguments display cell values rounded to two decimal places?
annot=".2f", fmt=True
labels=True, decimals=2
annot=True, fmt=".2f"
values=True, precision=".2f"
35 A correlation matrix contains values from to . Which configuration best gives zero a visually neutral midpoint?
sns.heatmap(corr, cmap="viridis", center=1)
sns.heatmap(corr, cmap="coolwarm", center=0)
sns.heatmap(corr, cmap="Greens", center=None)
sns.heatmap(corr, cmap="Blues", center=-1)
36 A classification dataset has only 10% positive examples. Which split best preserves this class proportion in both subsets?
train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
train_test_split(X, y, test_size=0.2, stratify=X, random_state=42)
train_test_split(X, y, test_size=0.2, shuffle=False, random_state=42)
train_test_split(X, y, test_size=0.2, random_state=None, shuffle=False)
37
Why should StandardScaler be fitted only on training data rather than on the complete dataset?
38 A categorical feature may contain unseen categories after deployment. Which encoder configuration avoids an error when transforming them?
LabelEncoder(handle_unknown="ignore")
OrdinalEncoder(handle_missing="ignore")
OneHotEncoder(handle_unknown="raise")
OneHotEncoder(handle_unknown="ignore")
39 A classifier achieves 95% accuracy, but the positive class is rare. Which metric is most useful when both missed positives and false alarms matter?
40
What is the main advantage of placing StandardScaler and a classifier in a Scikit-learn Pipeline?
41
A CSV column contains the literal codes NA, ?, and valid strings. Which call preserves NA as text while treating only ? as missing?
pd.read_csv("data.csv", keep_default_na=False, na_values=["?"])
pd.read_csv("data.csv", keep_default_na=True, na_values=["NA"])
pd.read_csv("data.csv", keep_default_na=True, na_values=["?"])
pd.read_csv("data.csv", keep_default_na=False, na_values=[])
42
What happens when pd.read_csv receives both dtype={"id": "Int64"} and a converters function for the id column?
ValueError.
43
A large CSV is read with chunksize=10000. Early chunks contain only integers in column x, while later chunks include missing values. Which approach best guarantees a consistent nullable-integer schema after concatenation?
low_memory=True and concatenate chunks without conversion.
memory_map=True so every chunk shares one inferred schema.
dtype={"x": "Int64"} when creating the chunk reader.
convert_dtypes() on each.
44
After creating several figures, code must add a line specifically to an earlier axes object ax1, regardless of pyplot's current figure. Which call is reliable?
plt.gca(ax1).plot(x, y)
plt.figure(ax1).plot(x, y)
plt.plot(x, y, axes=ax1)
ax1.plot(x, y)
45
Two subplots are created with fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True). What is the expected effect of ax1.set_xlim(0, 10)?
ax1 changes because sharing affects ticks but not limits.
ax2 changes because the lower axes owns shared x-limits.
fig.canvas.draw() is called explicitly.
46 Two scatter plots use the same colormap, but their numeric ranges differ. Which design makes a given numeric value map to the same color in both plots?
alpha and zorder values.
autoscale() on each scatter plot after both are created.
Normalize(vmin, vmax) instance to both plots.
47
Given x = [3, 1, 2] and y = [30, 10, 20], what does ax.plot(x, y) do by default?
x before drawing the line.
48
A plotted y-array is [1.0, 2.0, np.nan, 4.0]. How does a standard Matplotlib line normally represent the NaN?
49
In ax.scatter(x, y, s=36), what does the value 36 represent?
50
For exactly three points, why can ax.scatter(x, y, c=(1, 0, 0)) fail to express the intended uniform red color?
51
A DataFrame has multiple score observations for each time. With no additional arguments, what does sns.lineplot(data=df, x="time", y="score") generally display?
52
Why is passing an existing Matplotlib axes through ax=ax generally inappropriate for sns.displot(...)?
displot is figure-level and creates its own FacetGrid.
displot always draws directly on pyplot's current axes.
displot accepts axes only when kind="kde" is selected.
displot requires an axes array matching the DataFrame columns.
53
Separate filtered plots contain different subsets of category levels. Which approach most reliably keeps each hue category mapped to the same color across all plots?
hue_order.
54
A labeled DataFrame is plotted with sns.heatmap(data, annot=annotations), where annotations is a same-shaped NumPy array. How are annotation entries matched to cells?
55
When vmin and vmax are omitted, what is the main effect of robust=True in sns.heatmap?
56 A correlation heatmap is computed from columns with different missing-value patterns using pairwise-complete observations. Which subtle issue can arise?
57 A model uses imputation, standardization, and classification with cross-validation. Which structure best prevents validation-fold information from influencing preprocessing?
Pipeline.
58
A ColumnTransformer combines sparse and dense transformer outputs with sparse_threshold=0.3. If the combined output density is , what output is expected?
59
Why does StandardScaler(with_mean=True) normally reject a SciPy sparse feature matrix?
60 A medical dataset has several rows per patient. Which cross-validation strategy prevents records from the same patient appearing in both training and validation sets?
GroupKFold and supply patient identifiers as the groups.
StratifiedKFold with patient identifiers as target labels.
KFold after randomly shuffling all individual records.
LeaveOneOut independently on every recorded measurement.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →