Unit 14: Machine Learning Packages in Python - Practice Quiz

ECAP792 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which pandas function is commonly used to import data from a CSV file?

Data import Easy
A. pd.read_excel()
B. pd.DataFrame()
C. pd.to_csv()
D. pd.read_csv()

2 Which Python statement imports pandas using its conventional alias?

Data import Easy
A. from pandas import sklearn
B. import pandas as plt
C. import pandas as pd
D. import pandas as sns

3 Which pandas function is designed to import a Microsoft Excel file?

Data import Easy
A. pd.read_csv() with several additional plotting parameters
B. pd.read_excel()
C. pd.read_json()
D. pd.read_table()

4 What type of pandas object is usually returned by pd.read_csv()?

Data import Easy
A. A DataFrame
B. A Series label
C. A Matplotlib figure containing the imported rows
D. A NumPy scalar

5 Which module is conventionally imported as plt for creating Matplotlib plots?

Visualization with Matplotlib Easy
A. matplotlib.pyplot
B. matplotlib.image
C. matplotlib.animation
D. matplotlib.colors

6 Which function displays a completed Matplotlib figure?

Visualization with Matplotlib Easy
A. plt.render_every_axis_and_export_the_result()
B. plt.show()
C. plt.draw_data()
D. plt.open()

7 Which function adds a title to a Matplotlib plot?

Visualization with Matplotlib Easy
A. plt.title()
B. plt.legend()
C. plt.xlabel()
D. plt.caption()

8 Which function labels the horizontal axis in Matplotlib?

Visualization with Matplotlib Easy
A. plt.legend() with an extended horizontal-axis configuration
B. plt.ylabel()
C. plt.xlabel()
D. plt.title()

9 Which Matplotlib function creates a simple line plot?

Simple line and scatter plots Easy
A. plt.hist()
B. plt.scatter()
C. plt.plot()
D. plt.bar()

10 Which Matplotlib function creates a scatter plot?

Simple line and scatter plots Easy
A. plt.scatter()
B. plt.build_a_chart_with_independent_marker_coordinates()
C. plt.pie()
D. plt.plot()

11 A line plot is especially useful for showing which kind of information?

Simple line and scatter plots Easy
A. Words in a document
B. Database table relationships
C. Parts of a whole
D. Changes over time

12 What does each marker in a basic scatter plot usually represent?

Simple line and scatter plots Easy
A. A complete data table
B. A fitted model containing every feature and parameter
C. A line of Python code
D. A pair of values

13 What is the conventional alias used when importing Seaborn?

Seaborn Easy
A. sea
B. sns
C. sbn
D. sb

14 Seaborn is primarily used for which task?

Seaborn Easy
A. Operating-system management
B. Statistical data visualization
C. Training every machine-learning algorithm without imported data
D. Database server administration

15 Seaborn is built on top of which plotting library?

Seaborn Easy
A. Requests
B. Matplotlib
C. Beautiful Soup
D. TensorFlow

16 Which Seaborn function is used to create a heatmap?

Heatmap Easy
A. sns.scatterplot()
B. sns.heatmap()
C. sns.lineplot()
D. sns.color_every_numeric_cell_and_build_a_table()

17 How are numerical values mainly represented in a heatmap?

Heatmap Easy
A. By audio signals
B. By separate machine-learning models
C. By file extensions
D. By different colors

18 What does annot=True commonly do in sns.heatmap()?

Heatmap Easy
A. Displays values in cells
B. Automatically trains a classifier using each colored cell
C. Hides the color scale
D. Deletes missing values

19 What is Scikit-learn mainly used for?

Introducing Scikit-learn package Easy
A. Machine learning
B. Audio file playback
C. Web page styling
D. Spreadsheet file compression

20 Which Scikit-learn function commonly divides data into training and testing sets?

Introducing Scikit-learn package Easy
A. fit_transform()
B. separate_every_feature_by_manually_copying_the_dataset()
C. classification_report()
D. 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?

Data import Medium
A. pd.read_csv("data.csv", dtype=["age", "income", "target"])
B. pd.read_csv("data.csv", index_col=["age", "income", "target"])
C. pd.read_csv("data.csv", usecols=["age", "income", "target"])
D. 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?

Data import Medium
A. pd.read_csv("orders.csv", dtype={"order_date": "date"})
B. pd.read_csv("orders.csv", date_format=["order_date"])
C. pd.read_csv("orders.csv", index_col=["order_date"])
D. 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?

Data import Medium
A. pd.read_csv("data.csv", fill_values=["NA", -999])
B. pd.read_csv("data.csv", na_values=["NA", -999])
C. pd.read_csv("data.csv", null_values={"NA": -999})
D. 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?

Visualization with Matplotlib Medium
A. fig, axes = plt.subplots(2, 1)
B. fig, axes = plt.axes(1, 2)
C. fig, axes = plt.figure(1, 2)
D. 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?

Visualization with Matplotlib Medium
A. plt.savefig("plot.png", bbox_inches="tight")
B. plt.savefig("plot.png", orientation="landscape")
C. plt.savefig("plot.png", frameon=False)
D. 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?

Visualization with Matplotlib Medium
A. ax.labels(title="Sales", x="Month", y="Revenue")
B. fig.axes(title="Sales", x="Month", y="Revenue")
C. fig.set(title="Sales", xlabel="Month", ylabel="Revenue")
D. 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?

Simple line and scatter plots Medium
A. Convert the values to categories
B. Shuffle the observations again
C. Sort the observations by value
D. Sort the observations by time

28 In plt.scatter(x, y, c=score, cmap="viridis"), what does the score array control?

Simple line and scatter plots Medium
A. The size assigned to each point
B. The color assigned to each point
C. The opacity assigned to each point
D. The marker assigned to each point

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?

Simple line and scatter plots Medium
A. plt.colorbar()
B. plt.grid()
C. plt.legend()
D. plt.annotate()

30 A DataFrame contains height, weight, and a categorical column species. Which call creates a scatter plot whose point colors distinguish species?

Seaborn Medium
A. sns.scatterplot(data=df, x="height", y="weight", palette="species")
B. sns.scatterplot(data=df, x="height", y="weight", hue="species")
C. sns.scatterplot(data=df, x="height", y="weight", size="species")
D. 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?

Seaborn Medium
A. Every observation as a separate line
B. The sum with a standard deviation
C. The mean with an uncertainty interval
D. The median with the complete range

32 You want all subsequent Seaborn plots to use a white-grid background and a colorblind-friendly palette. Which command applies both settings globally?

Seaborn Medium
A. sns.set_palette(style="whitegrid", palette="colorblind")
B. sns.despine(style="whitegrid", palette="colorblind")
C. sns.set_theme(style="whitegrid", palette="colorblind")
D. 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?

Heatmap Medium
A. sns.heatmap(corr, mask=np.full_like(corr, False, dtype=bool))
B. sns.heatmap(corr, mask=np.diag(np.ones(len(corr))))
C. sns.heatmap(corr, mask=np.tril(np.ones_like(corr, dtype=bool)))
D. sns.heatmap(corr, mask=np.triu(np.ones_like(corr, dtype=bool)))

34 Which heatmap arguments display cell values rounded to two decimal places?

Heatmap Medium
A. annot=".2f", fmt=True
B. labels=True, decimals=2
C. annot=True, fmt=".2f"
D. values=True, precision=".2f"

35 A correlation matrix contains values from to . Which configuration best gives zero a visually neutral midpoint?

Heatmap Medium
A. sns.heatmap(corr, cmap="viridis", center=1)
B. sns.heatmap(corr, cmap="coolwarm", center=0)
C. sns.heatmap(corr, cmap="Greens", center=None)
D. 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?

Introducing Scikit-learn package Medium
A. train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
B. train_test_split(X, y, test_size=0.2, stratify=X, random_state=42)
C. train_test_split(X, y, test_size=0.2, shuffle=False, random_state=42)
D. 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?

Introducing Scikit-learn package Medium
A. To prevent test-set information leakage
B. To remove all test-set outliers
C. To guarantee perfect model accuracy
D. To convert labels into numeric values

38 A categorical feature may contain unseen categories after deployment. Which encoder configuration avoids an error when transforming them?

Introducing Scikit-learn package Medium
A. LabelEncoder(handle_unknown="ignore")
B. OrdinalEncoder(handle_missing="ignore")
C. OneHotEncoder(handle_unknown="raise")
D. 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?

Introducing Scikit-learn package Medium
A. Mean squared error
B. R-squared score
C. Explained variance
D. F1-score

40 What is the main advantage of placing StandardScaler and a classifier in a Scikit-learn Pipeline?

Introducing Scikit-learn package Medium
A. It applies preprocessing consistently during fitting and prediction
B. It guarantees that every feature becomes normally distributed
C. It automatically selects the best possible classifier
D. It removes the need for a separate test dataset

41 A CSV column contains the literal codes NA, ?, and valid strings. Which call preserves NA as text while treating only ? as missing?

Data import Hard
A. pd.read_csv("data.csv", keep_default_na=False, na_values=["?"])
B. pd.read_csv("data.csv", keep_default_na=True, na_values=["NA"])
C. pd.read_csv("data.csv", keep_default_na=True, na_values=["?"])
D. 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?

Data import Hard
A. The converter takes precedence and determines the resulting values.
B. The nullable-integer cast runs first, followed by the converter.
C. The converter runs first, followed by the nullable-integer cast.
D. The conflicting arguments cause parsing to stop with 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?

Data import Hard
A. Set low_memory=True and concatenate chunks without conversion.
B. Set memory_map=True so every chunk shares one inferred schema.
C. Specify dtype={"x": "Int64"} when creating the chunk reader.
D. Infer each chunk independently and call 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?

Visualization with Matplotlib Hard
A. plt.gca(ax1).plot(x, y)
B. plt.figure(ax1).plot(x, y)
C. plt.plot(x, y, axes=ax1)
D. 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)?

Visualization with Matplotlib Hard
A. Only ax1 changes because sharing affects ticks but not limits.
B. Only ax2 changes because the lower axes owns shared x-limits.
C. Both axes receive the new limits because their x-axes are shared.
D. Neither axes changes until 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?

Visualization with Matplotlib Hard
A. Give both scatter plots the same alpha and zorder values.
B. Call autoscale() on each scatter plot after both are created.
C. Pass identical color arrays after independently ranking each dataset.
D. Pass one shared 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?

Simple line and scatter plots Hard
A. It rejects nonmonotonic x-values unless a marker is specified.
B. It connects points in the supplied order: 3, then 1, then 2.
C. It sorts both arrays by x before drawing the line.
D. It aggregates equal x-values and plots their mean y-values.

48 A plotted y-array is [1.0, 2.0, np.nan, 4.0]. How does a standard Matplotlib line normally represent the NaN?

Simple line and scatter plots Hard
A. It removes the point and directly joins the neighboring valid values.
B. It creates a visible break between the surrounding line segments.
C. It replaces the missing point with zero before constructing the path.
D. It interpolates through the missing point using adjacent values.

49 In ax.scatter(x, y, s=36), what does the value 36 represent?

Simple line and scatter plots Hard
A. A marker area of 36 squared typographic points.
B. A marker radius of 36 typographic points.
C. A data-space area of 36 squared axis units.
D. A marker diameter of 36 display pixels.

50 For exactly three points, why can ax.scatter(x, y, c=(1, 0, 0)) fail to express the intended uniform red color?

Simple line and scatter plots Hard
A. The tuple controls marker-edge widths rather than marker-face colors.
B. The tuple can be interpreted as three scalar values for colormap mapping.
C. Scatter converts every three-element tuple into an HSV color specification.
D. Scatter accepts RGB tuples only when their components are integer values.

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?

Seaborn Hard
A. Every observation joined in raw DataFrame row order.
B. One separate line for every observation sharing a time value.
C. The mean score at each time with an uncertainty interval.
D. The median score at each time without any uncertainty interval.

52 Why is passing an existing Matplotlib axes through ax=ax generally inappropriate for sns.displot(...)?

Seaborn Hard
A. displot is figure-level and creates its own FacetGrid.
B. displot always draws directly on pyplot's current axes.
C. displot accepts axes only when kind="kde" is selected.
D. 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?

Seaborn Hard
A. Let each plotting call infer palette positions from present categories.
B. Recompute a sequential palette from the row count of each subset.
C. Use a category-to-color palette dictionary and a fixed hue_order.
D. Sort each subset by its numeric y-values before plotting categories.

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?

Heatmap Hard
A. By matching array values against the DataFrame's cell values.
B. By sorting both objects using their row and column coordinates.
C. By aligning implicit array labels with DataFrame index labels.
D. By positional array indices, independent of DataFrame labels.

55 When vmin and vmax are omitted, what is the main effect of robust=True in sns.heatmap?

Heatmap Hard
A. It derives color limits from robust quantiles instead of extreme values.
B. It applies a logarithmic normalization to reduce outlier influence.
C. It computes colors using ranks rather than the original numeric values.
D. It replaces every outlier with the median before plotting the matrix.

56 A correlation heatmap is computed from columns with different missing-value patterns using pairwise-complete observations. Which subtle issue can arise?

Heatmap Hard
A. Every off-diagonal correlation must become exactly zero.
B. The displayed correlation matrix may fail to be positive semidefinite.
C. The matrix must become asymmetric because missingness differs by column.
D. All correlations must use the intersection of complete rows automatically.

57 A model uses imputation, standardization, and classification with cross-validation. Which structure best prevents validation-fold information from influencing preprocessing?

Introducing Scikit-learn package Hard
A. Cross-validate preprocessing separately, then transform the full dataset.
B. Fit all preprocessing once, then cross-validate only the classifier.
C. Place preprocessing and classification inside one Pipeline.
D. Transform each fold using statistics computed from all feature rows.

58 A ColumnTransformer combines sparse and dense transformer outputs with sparse_threshold=0.3. If the combined output density is , what output is expected?

Introducing Scikit-learn package Hard
A. A dense array because at least one component output was dense.
B. A sparse matrix only if every component transformer returned sparse data.
C. A sparse matrix because the combined density is below the threshold.
D. A dense array because the threshold applies only to individual columns.

59 Why does StandardScaler(with_mean=True) normally reject a SciPy sparse feature matrix?

Introducing Scikit-learn package Hard
A. Centering requires integer indices that sparse matrices do not maintain.
B. Centering would generally destroy sparsity and require dense storage.
C. Sparse matrices cannot provide feature variances without label metadata.
D. Scaling sparse values necessarily changes every zero into a missing value.

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?

Introducing Scikit-learn package Hard
A. Use GroupKFold and supply patient identifiers as the groups.
B. Use StratifiedKFold with patient identifiers as target labels.
C. Use KFold after randomly shuffling all individual records.
D. Use LeaveOneOut independently on every recorded measurement.