Unit 14 subjective questions Machine Learning Packages in Python
ECAP792 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Define data import in Python. Explain how a CSV file can be imported using Pandas.
Model answer
Data import is the process of loading data from an external source into a Python environment for inspection, cleaning, analysis, or modeling.
A CSV file can be imported with Pandas as follows:
import pandas as pd data = pd.read_csv("data.csv")pd.read_csv()reads comma-separated data.- The result is stored as a Pandas DataFrame.
data.head()displays the first five rows.data.info()shows column names, data types, and non-null counts.- Options such as
sep,header,names,index_col, andna_valuescan control how the file is interpreted.
-
Question 2 of 20
Describe how data can be imported from CSV, Excel, and JSON files in Python. Compare the functions used for these formats.
Model answer
Pandas provides separate functions for importing common file formats:
- CSV:
pd.read_csv("file.csv") - Excel:
pd.read_excel("file.xlsx", sheet_name="Sheet1") - JSON:
pd.read_json("file.json")
All three functions normally return a DataFrame, but they interpret different storage structures:
- CSV stores tabular data as delimited text.
- Excel stores data in workbooks containing one or more sheets.
- JSON represents data through objects, arrays, and key-value pairs.
After import, useful validation commands include
head(),shape,info(), andisnull().sum(). Correct parameters must be supplied when a source has unusual delimiters, headers, encodings, or missing-value symbols. - CSV:
-
Question 3 of 20
Explain the importance of inspecting and validating a dataset immediately after importing it.
Model answer
Inspection confirms that the data has been loaded correctly and is suitable for analysis.
Important checks include:
- Preview records:
df.head()anddf.tail()reveal whether headers and values were parsed correctly. - Check dimensions:
df.shapereturns the numbers of rows and columns. - Review structure:
df.info()displays column names, data types, and non-null counts. - Generate summaries:
df.describe()reports descriptive statistics for numerical columns. - Find missing values:
df.isnull().sum()counts null values in each column. - Detect duplication:
df.duplicated().sum()identifies repeated rows.
These checks prevent misleading visualizations and machine-learning results caused by malformed columns, missing values, duplicates, or incorrect data types.
- Preview records:
-
Question 4 of 20
What is Matplotlib? Describe its role in data visualization and explain the purpose of
pyplot.Model answer
Matplotlib is a Python library used to create static, animated, and interactive visualizations. It supports line plots, scatter plots, bar charts, histograms, pie charts, and many other graph types.
matplotlib.pyplotis a convenient plotting interface that is commonly imported as:import matplotlib.pyplot as pltIts functions manage figures, axes, plotting commands, labels, legends, and display operations. For example,
plt.plot()creates a line plot, whileplt.show()displays the completed figure.Matplotlib is valuable because it:
- Reveals trends, patterns, distributions, and outliers.
- Offers detailed control over plot appearance.
- Integrates with NumPy, Pandas, Seaborn, and Jupyter notebooks.
-
Question 5 of 20
Describe the main components of a Matplotlib figure and distinguish between a figure and an axes object.
Model answer
A Matplotlib visualization is organized hierarchically:
- A figure is the complete drawing canvas or output window.
- An axes object is an individual plotting area inside the figure.
- An axis controls a coordinate direction, such as the x-axis or y-axis.
- Artists are visible elements such as lines, text, legends, and markers.
A figure can contain multiple axes objects. They can be created with:
fig, ax = plt.subplots() ax.plot(x, y)Here,
figrefers to the entire canvas andaxrefers to the plotting region. The object-oriented approach is particularly useful when creating multiple subplots or precisely customizing a visualization. -
-
Question 6 of 20
Explain how to create and customize a simple line plot in Matplotlib. Include a suitable example.
Model answer
A line plot displays ordered observations connected by straight lines and is commonly used to show change over time.
import matplotlib.pyplot as plt days = [1, 2, 3, 4, 5] sales = [20, 28, 25, 35, 42] plt.plot(days, sales, color="blue", marker="o", linestyle="--", label="Sales") plt.title("Daily Sales") plt.xlabel("Day") plt.ylabel("Units Sold") plt.grid(True) plt.legend() plt.show()Important customization options are:
colorchanges the line color.markermarks individual observations.linestylechanges the line pattern.title(),xlabel(), andylabel()provide context.legend()identifies plotted series.grid()makes values easier to compare.
-
Question 7 of 20
What is a scatter plot? Explain how it helps identify relationships between two numerical variables.
Model answer
A scatter plot represents each observation as a point with coordinates . It is created in Matplotlib using
plt.scatter(x, y).A scatter plot can reveal:
- Positive association: generally increases as increases.
- Negative association: generally decreases as increases.
- No clear association: points show no systematic pattern.
- Nonlinear relationships: points follow a curve rather than a straight line.
- Clusters: observations form distinct groups.
- Outliers: individual points lie far from the main pattern.
A visible association does not by itself establish causation. Statistical analysis and domain knowledge are needed before making causal conclusions.
-
Question 8 of 20
Distinguish between a line plot and a scatter plot. State an appropriate use case for each.
Model answer
Line plot:
- Connects observations in a specified order.
- Emphasizes continuity, progression, or trends.
- Is appropriate for time-series data, such as monthly revenue.
- Is created with
plt.plot(x, y).
Scatter plot:
- Displays observations as separate points.
- Emphasizes the relationship between two numerical variables.
- Is appropriate for examining variables such as height and weight.
- Is created with
plt.scatter(x, y).
Connecting unordered observations with lines can falsely imply continuity. Conversely, a scatter plot may not emphasize sequential change as clearly as a line plot.
-
Question 9 of 20
Explain how multiple data series can be displayed in one Matplotlib plot and how they should be made distinguishable.
Model answer
Multiple series can be plotted on the same axes by calling a plotting function once for each series:
plt.plot(x, y1, color="blue", marker="o", label="Product A") plt.plot(x, y2, color="red", marker="s", label="Product B") plt.xlabel("Month") plt.ylabel("Sales") plt.title("Product Sales Comparison") plt.legend() plt.grid(True) plt.show()The series should be distinguished through:
- Contrasting colors.
- Different markers or line styles.
- Clear labels and a legend.
- Appropriate axis labels and units.
Design should not rely only on color because some readers may have color-vision deficiencies. Markers and line patterns improve accessibility.
-
Question 10 of 20
Describe the purpose of subplots in Matplotlib and explain how a subplot arrangement can be created.
Model answer
Subplots place multiple axes within a single figure. They are useful for comparing different variables or plot types while keeping the visualizations organized.
A arrangement can be created as follows:
import matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2, figsize=(10, 8)) axes[0, 0].plot(x, y1) axes[0, 1].scatter(x, y2) axes[1, 0].hist(y1) axes[1, 1].bar(x, y2) fig.tight_layout() plt.show()plt.subplots(2, 2)creates four axes.axes[row, column]selects a specific subplot.figsizecontrols the overall dimensions.tight_layout()reduces overlap among titles and labels.
-
Question 11 of 20
What is Seaborn? Explain how it extends Matplotlib for statistical data visualization.
Model answer
Seaborn is a high-level statistical visualization library built on Matplotlib. It is commonly imported with:
import seaborn as snsSeaborn extends Matplotlib by providing:
- Attractive default themes and color palettes.
- Simple syntax for complex statistical graphics.
- Direct integration with Pandas DataFrames.
- Automatic grouping through parameters such as
hue,style, andsize. - Functions for distributions, categorical comparisons, regression relationships, and heatmaps.
For example,
sns.scatterplot(data=df, x="age", y="income", hue="group")maps DataFrame columns directly to visual properties. Matplotlib functions can still be used to customize Seaborn plots. -
Question 12 of 20
Compare Matplotlib and Seaborn with respect to abstraction, customization, default appearance, and typical use.
Model answer
Matplotlib is a general-purpose, lower-level visualization library. It provides detailed control over almost every graphical element and is suitable for highly customized plots.
Seaborn is a higher-level library built on Matplotlib. It provides concise functions for statistical graphics and attractive defaults.
Key differences are:
- Abstraction: Seaborn requires less code for many statistical plots.
- Customization: Matplotlib offers more direct, fine-grained control.
- Appearance: Seaborn provides polished themes and coordinated palettes by default.
- Data handling: Seaborn works naturally with named DataFrame columns.
- Typical use: Matplotlib is ideal for custom general plotting, while Seaborn is ideal for exploratory statistical visualization.
They are complementary rather than competing tools because Seaborn plots can be refined using Matplotlib.
-
Question 13 of 20
Explain the use of the
hue,style, andsizeparameters in a Seaborn scatter plot.Model answer
Seaborn can map additional variables to visual properties:
huemaps a variable to color.stylemaps a variable to marker shape.sizemaps a variable to marker size.
Example:
sns.scatterplot( data=df, x="experience", y="salary", hue="department", style="employment_type", size="performance_score" )This plot shows more than two dimensions of information at once. However, too many categories or encodings can make a graph difficult to read. Clear legends, suitable palettes, and a limited number of categories should therefore be used.
-
Question 14 of 20
Define a heatmap and describe the types of information that can be represented using it.
Model answer
A heatmap represents values in a two-dimensional matrix by mapping numerical magnitude to color.
Heatmaps can represent:
- Correlation matrices.
- Confusion matrices.
- Missing-value patterns.
- Frequency tables.
- Measurements observed across categories and time periods.
A basic Seaborn heatmap is created using:
sns.heatmap(matrix, cmap="viridis", annot=True)Here,
cmapselects the color map andannot=Truewrites values inside the cells. A color bar explains the relationship between colors and numerical values. Meaningful row labels, column labels, and a suitable color scale are essential for correct interpretation. -
Question 15 of 20
Explain how to construct and interpret a correlation heatmap using Pandas and Seaborn.
Model answer
A correlation heatmap summarizes pairwise linear relationships among numerical variables.
import seaborn as sns import matplotlib.pyplot as plt corr = df.corr(numeric_only=True) sns.heatmap(corr, annot=True, cmap="coolwarm", vmin=-1, vmax=1) plt.title("Correlation Matrix") plt.show()For variables and , Pearson correlation is:
Interpretation:
- close to indicates strong positive linear association.
- close to indicates strong negative linear association.
- close to indicates weak linear association.
- The diagonal equals because each variable is perfectly correlated with itself.
Correlation does not imply causation and may fail to capture nonlinear relationships.
-
Question 16 of 20
What is Scikit-learn? Describe the major machine-learning tasks and utilities supported by the package.
Model answer
Scikit-learn, imported as
sklearn, is an open-source Python package for machine learning. It offers a consistent estimator interface and integrates with NumPy, SciPy, Pandas, and Matplotlib.It supports:
- Classification: predicting categories.
- Regression: predicting continuous values.
- Clustering: finding groups in unlabeled data.
- Dimensionality reduction: reducing the number of features.
- Preprocessing: scaling, encoding, and transforming data.
- Model selection: train-test splitting, cross-validation, and hyperparameter tuning.
- Evaluation: metrics such as accuracy, precision, recall, mean squared error, and .
- Pipelines: combining preprocessing and estimation into a repeatable workflow.
-
Question 17 of 20
Describe the standard workflow for building a supervised machine-learning model using Scikit-learn.
Model answer
A standard supervised-learning workflow contains the following stages:
- Import and inspect data: Load the dataset and identify quality issues.
- Separate features and target: Store predictors in and the output in .
- Split the data: Use
train_test_split()to create training and testing subsets. - Preprocess features: Impute missing values, encode categories, or scale numerical columns.
- Select an estimator: Choose a classifier or regressor appropriate for the problem.
- Train: Call
model.fit(X_train, y_train). - Predict: Call
model.predict(X_test). - Evaluate: Compare predictions with
y_testusing suitable metrics. - Improve: Tune hyperparameters or compare alternative models.
The test data must remain separate during training and tuning to provide an unbiased estimate of final generalization performance.
-
Question 18 of 20
Explain the purpose of training and testing datasets. Show how
train_test_splitis used in Scikit-learn.Model answer
The training set is used to estimate a model's parameters. The testing set contains unseen observations used to evaluate how well the trained model generalizes.
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 )test_size=0.2assigns of observations to testing.random_state=42makes the split reproducible.- For classification,
stratify=ycan preserve class proportions.
Evaluating a model on the same data used for training can produce an overly optimistic score. A separate test set gives a more realistic estimate of performance on new data.
-
Question 19 of 20
Explain the
fit,predict, andscoremethods in the Scikit-learn estimator interface.Model answer
Scikit-learn estimators follow a consistent application programming interface:
fit(X_train, y_train)learns model parameters from training data.predict(X_test)generates predicted outputs for new feature values.score(X_test, y_test)returns an estimator-specific default performance measure.
Example:
from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) predictions = model.predict(X_test) result = model.score(X_test, y_test)For
LinearRegression,score()normally returns the coefficient of determination:Because the meaning of
score()varies by estimator, explicit metric functions should be used when a particular evaluation criterion is required. -
Question 20 of 20
Design an end-to-end Python workflow that imports a dataset, explores it visually, trains a Scikit-learn model, and evaluates the result.
Model answer
An end-to-end workflow can be organized as follows:
-
Import libraries and data:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_scoredf = pd.read_csv("data.csv")
-
Inspect the dataset: Use
df.head(),df.info(),df.describe(), anddf.isnull().sum(). -
Visualize relationships:
sns.scatterplot(data=df, x="feature", y="target")
sns.heatmap(df.corr(numeric_only=True), annot=True)
plt.show() -
Prepare and split data:
X = df[["feature"]]
y = df["target"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
) -
Train and predict:
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test) -
Evaluate:
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
Mean squared error is calculated as:
A lower MSE indicates smaller prediction errors, while a higher generally indicates that the model explains more target variance. The workflow should also address missing values, categorical variables, data leakage, and model assumptions where applicable.
-
That's unit 14
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 14 of ECAP792 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 14 of ECAP792 save you a night before the exam?
Then you can help keep it free for the next batch. 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.