Descriptive Statistics Practice Questions
Descriptive Statistics Practice Questions
• Range
• Variance
• Standard Deviation
• Interquartile Range (IQR)
Ans. • Mean
• Median
• Mode
• Pandas
• NumPy
• SciPy
• statistics (built-in)
• Population: The entire group of individuals or items that you're interested in studying.
Example: All students in a university.
• Sample: A smaller group selected from the population, used to draw conclusions about
the whole. Example: 100 students randomly chosen from the university.
Key difference:
Population = whole group
Sample = part of the group used for analysis
Sampling helps when studying the entire population is impractical or too costly.
Ans. The Central Limit Theorem (CLT) states that the sampling distribution of the sample mean
approaches a normal distribution as the sample size increases, regardless of the population's
original distribution (given that the sample size is sufficiently large).
The p-value is the probability of obtaining test results at least as extreme as the observed results,
assuming the null hypothesis is true. A small p-value (typically < 0.05) indicates strong
evidence against the null hypothesis, suggesting it should be rejected.
13. Name one type of test used for comparing two independent samples.
The Independent Samples t-test (or Two-Sample t-test) is commonly used to compare the
means of two independent groups.
1. Line plot
2. Bar chart
3. Scatter plot
19. What type of plot is used to visualize the relationship between two continuous
variables?
A scatter plot is typically used to visualize the relationship between two continuous variables.
• Answer:
A box plot (also called a whisker plot) is used to visualize the distribution, central
tendency, and variability of a dataset. It shows the median, upper and lower quartiles, and
potential outliers, helping identify skewness and spread in the data.
• Answer:
A bar plot displays data using rectangular bars where the length of each bar is
proportional to the value it represents. It's used to compare quantities across different
categories, such as comparing sales across different regions or performance of different
models.
• Answer:
Several libraries are available for creating visualizations in Python. The most commonly
used ones include:
o Matplotlib: A basic plotting library for creating static, interactive, and animated
visualizations.
o Seaborn: Built on top of Matplotlib, it provides a high-level interface for drawing
attractive and informative statistical graphics.
Other options include Plotly, Bokeh, and Altair.
• Answer:
Handling missing values is crucial because missing data can lead to inaccurate analyses
or biased model results. Techniques like imputation (filling missing values with
mean/median/mode) or removing rows/columns help ensure data quality and reliability of
machine learning models.
• Answer:
Label encoding is a preprocessing technique where categorical labels (text) are converted
into numeric form by assigning a unique integer to each category. For example,
{'Male': 0, 'Female': 1}. It's commonly used when preparing data for machine
learning algorithms that require numerical input.
• Answer:
One common method is Min-Max Scaling, which scales features to a fixed range,
usually [0, 1]. This ensures all features contribute equally to the model's performance,
especially in distance-based algorithms like k-NN or SVM.
• Answer:
Feature selection is the process of choosing only the most important and relevant features
from a dataset for model building. It helps in reducing overfitting, improving model
performance, and decreasing computation time. Methods include filter, wrapper, and
embedded techniques.
• Answer:
Feature engineering involves creating new features or modifying existing ones to
improve model accuracy. This may include combining multiple features, creating
interaction terms, encoding categorical variables, or transforming data using
mathematical functions. It's a key step in enhancing model performance.
python
CopyEdit
import pandas as pd
df = [Link]({'Color': ['Red', 'Green', 'Blue']})
encoded_df = pd.get_dummies(df)
32. What are the common techniques for handling missing values in Python?
Answer:
35. Define K-Means clustering and its application in academic performance analysis.
Answer: K-Means clustering partitions data into K groups based on feature similarity. In
academic analysis, it helps group students by performance levels (e.g., high, medium, low
achievers).
36. Describe the use of artificial neural networks (ANN) in image analysis.
Answer: ANNs learn patterns from pixel data to perform tasks like image classification, object
detection, and facial recognition by mimicking the human brain’s neuron connections.
37. Explain the concept of convolutional neural networks (CNN) in audio analysis.
Answer: CNNs can be applied to audio spectrograms (visual representations of sound) to extract
temporal and frequency features for tasks like speech recognition and audio classification.
38. Name one metric commonly used for evaluating the performance of machine learning
models.
Answer: Accuracy – measures the proportion of correctly predicted instances out of total
predictions, especially in classification problems.
40. What is the main difference between supervised and unsupervised learning?
Answer:
• Supervised Learning uses labeled data to train models (e.g., classification, regression).
• Unsupervised Learning uses unlabeled data to find patterns or structure (e.g., clustering,
dimensionality reduction).
41. Explain the difference between mean, median, and mode. Provide an example
illustrating when each measure of central tendency is most appropriate.
• Mean is the average of all values, calculated by summing all data points and dividing by
the number of values. It is sensitive to outliers.
• Median is the middle value when the data is arranged in ascending or descending order.
If there is an even number of observations, the median is the average of the two middle
values. It is not affected by outliers.
• Mode is the value that appears most frequently. A dataset can have more than one mode
(bimodal, multimodal), or no mode at all.
In this case, the mean is distorted by the outlier (₹1,00,000), so the median gives a better sense
of the typical income.
42. Describe the concept of variance and its significance in descriptive statistics.
How does it relate to the spread of data points?
• Variance is a measure of how much the data values deviate from the mean. It is
calculated as the average of the squared differences from the mean.
• Formula (Sample):
•
Significance:
o A higher variance means the data points are more spread out.
o A low variance means data points are clustered closely around the mean.
o Variance is the foundation for other statistical measures such as standard
deviation and confidence intervals.
43. Define skewness and kurtosis. How do these measures help in understanding
the shape of a distribution?
44. Discuss the importance of the interquartile range (IQR) in analyzing data.
How does it differ from standard deviation?
• IQR = Q3 − Q1
It captures the middle 50% of the data, i.e., the range between the first quartile (25%)
and the third quartile (75%).
• Importance:
o Resistant to outliers and skewed data.
o Helps in identifying spread and dispersion without being influenced by extreme
values.
o Used in box plots to detect outliers.
• Difference from Standard Deviation:
o Standard deviation includes all data points and is affected by outliers.
o IQR focuses on the central part of the data and is robust against extreme values.
45. Explain how you would determine the skewness of a dataset using Python.
Provide a step-by-step procedure.
Step-by-step procedure:
python
CopyEdit
import pandas as pd
from [Link] import skew
python
CopyEdit
data = pd.read_csv("your_dataset.csv")
python
CopyEdit
column_data = data['column_name']
4. Calculate skewness:
python
CopyEdit
skew_value = skew(column_data)
print("Skewness:", skew_value)
Interpretation:
• Mean is sensitive to outliers and skewness; it can give a misleading central value if the
data is not symmetrical.
• Median is robust to outliers and skewed data; it reflects the middle point and provides a
more reliable summary when data isn't normally distributed.
Use cases:
Example: If most salaries are ₹30k–₹40k but one person earns ₹1L, the mean rises, but the
median remains close to the majority.
47. Describe a real-life scenario where knowing the skewness and kurtosis of a
dataset would be crucial for decision-making.
• Skewness helps in understanding whether returns are more likely to be below or above
the average.
o Positive skew: Potential for higher gains
o Negative skew: Higher risk of losses
• Kurtosis helps assess risk:
o High kurtosis implies more extreme returns (more outliers).
o Low kurtosis implies stable returns.
Financial analysts use these to choose portfolios and assess market risks.
48. Discuss the limitations of using only measures of central tendency without
considering measures of dispersion when analyzing data.
• Central tendency (mean, median, mode) summarizes the data center but doesn’t tell
how spread out the data is.
• Without dispersion measures like variance, standard deviation, or IQR, we can't assess
data variability.
• Two datasets can have the same mean but completely different distributions.
Example:
• Dataset A: 50, 50, 50, 50
• Dataset B: 10, 30, 70, 90
Both have a mean of 50, but very different spreads.
Thus, dispersion provides context to central values and helps in accurate data interpretation.
49. Explain the difference between population and sample in statistics. Why is it
important to distinguish between the two?
• Population: The entire group you want to study (e.g., all citizens of India).
• Sample: A subset of the population used to infer conclusions (e.g., 1,000 citizens
surveyed).
Importance:
50. Describe the central limit theorem and its significance in inferential statistics.
How does it enable hypothesis testing?
• Central Limit Theorem (CLT) states that the distribution of the sample mean will
approximate a normal distribution as the sample size becomes large (typically n ≥ 30),
even if the population distribution is not normal.
Significance:
• It allows statisticians to use normal distribution models for inference, even when
dealing with non-normal data.
• Foundation for:
o Confidence intervals
o Hypothesis testing
o Z-scores and t-tests
CLT enables the use of probability-based conclusions about population parameters from
sample data.
51. Define Type I and Type II errors. Provide examples illustrating each type of
error in hypothesis testing.
In hypothesis testing, we test a null hypothesis (H0H_0H0) against an alternative hypothesis (H1H_1H1). Errors can
occur during this decision-making process:
Minimizing both types of errors is ideal, but reducing one often increases the other.
52. Discuss the concept of p-value in hypothesis testing. How is it used to make
decisions about rejecting or failing to reject the null hypothesis?
• The p-value is the probability of obtaining test results at least as extreme as the results observed,
assuming the null hypothesis is true.
• It helps us determine the strength of evidence against the null hypothesis.
Decision Rule:
Example:
If you get a p-value of 0.03 in a drug efficacy test with α = 0.05, you reject H0H_0H0 and conclude that the drug
likely has an effect.
54. Compare and contrast one-sample Z test and one-sample t test. Under what
circumstances would you choose one over the other?
When to use:
• Use Z test when population standard deviation is known and sample size is large.
• Use t test when population standard deviation is unknown or sample size is small.
55. Describe a real-world scenario where you would use a two-sample t test to
compare means of two populations.
Scenario:
Suppose an educational researcher wants to compare the effectiveness of two teaching methods on student
performance.
By collecting test scores from both groups, a two-sample t test can be used to determine if there's a statistically
significant difference in their average performance.
When to use:
If ANOVA shows significant results, post-hoc tests (like Tukey’s HSD) are used to identify which groups differ.
57. Describe the purpose of histograms in data visualization. How do they help in
understanding the distribution of data?
• A histogram is a graphical representation of the distribution of numerical data using bars to show the
frequency of data points within ranges (bins).
• It helps you:
o Understand the shape of the data (normal, skewed, etc.)
o Detect outliers or gaps
o Assess central tendency and spread
Example: A histogram of exam scores helps visualize how many students scored in different score ranges (0–10, 10–
20, etc.).
58. Explain the difference between box plots and line plots. When would you use
each type of plot?
59. Discuss the advantages of using scatter plots over other types of plots for
visualizing relationships between variables.
• Scatter plots show the relationship between two continuous variables.
• Each point represents one observation.
Advantages:
Example:
Visualizing the relationship between study hours and exam scores to check if more studying leads to better
performance.
60. Compare and contrast bar plots and pie charts. When is it more appropriate
to use one over the other?
Use Bar Plot:
• When showing percentage of market share held by different companies (only a few categories).
61. Explain how to create a box plot using Matplotlib. Provide an example dataset and the
corresponding Python code.
A box plot is used to represent the distribution of a dataset based on a five-number summary:
minimum, first quartile, median, third quartile, and maximum.
Example dataset:
python
CopyEdit
import [Link] as plt
import numpy as np
# Example dataset
data = [Link](0, 1, 100)
This code creates a random dataset using a normal distribution and plots the box plot using
[Link]().
62. Describe the steps involved in creating a scatter plot using Seaborn. How can you
customize the appearance of the plot?
Steps for creating a scatter plot in Seaborn:
Example code:
python
CopyEdit
import seaborn as sns
import [Link] as plt
# Example dataset
tips = sns.load_dataset('tips')
# Customizing appearance
[Link]('Total Bill vs Tip')
[Link]('Total Bill')
[Link]('Tip')
[Link]()
This code creates a scatter plot with customization options for color (hue), style (style), and
labels.
63. Discuss the advantages of using Seaborn's Catplot over traditional bar plots for
categorical data visualization.
• Multiple Plot Types: catplot() can display various plot types such as bar plots, box
plots, strip plots, and violin plots, all within one function.
• FacetGrid: It supports faceting, meaning you can easily create subplots for different
subsets of the data.
• Ease of Use: catplot() simplifies categorical data visualization by providing an
intuitive interface and handling many details like axis labels and legends automatically.
64. Describe a real-world scenario where you would use both Matplotlib and Seaborn to
visualize different aspects of a dataset.
65. Discuss the importance of handling missing values in a dataset before performing data
analysis. What are some common techniques for dealing with missing data?
66. Explain the difference between label encoding and one-hot encoding for categorical
data. When would you use each technique?
67. Describe the process of data normalization using Min-Max scaling. How does it help in
improving the performance of machine learning algorithms?
Min-Max scaling scales the features to a fixed range, typically [0, 1]. The formula used is:
It helps in:
68. Discuss the concept of feature selection in machine learning. What are some common
methods for selecting relevant features?
Feature selection involves identifying and selecting the most important features for a machine
learning model, helping reduce overfitting and improve model performance.
Common methods:
• Filter Methods: Select features based on statistical tests (e.g., correlation, Chi-square
test).
• Wrapper Methods: Evaluate feature subsets by training models (e.g., Recursive Feature
Elimination).
• Embedded Methods: Perform feature selection during model training (e.g., Lasso
regression, decision trees).
69. Explain the difference between feature engineering and dimensionality reduction. How
do they contribute to improving model performance?
• Feature Engineering: The process of transforming raw data into meaningful features
that improve the predictive power of a model (e.g., creating new features, encoding, or
normalizing).
• Dimensionality Reduction: The process of reducing the number of features in a dataset
while retaining important information (e.g., using PCA, t-SNE).
Both methods help by reducing overfitting, improving model generalization, and decreasing
computation time.
• Creating new features: E.g., creating a "price per square foot" feature.
• Handling categorical data: Encoding features like neighborhood or house type.
• Scaling numerical features: Normalizing square footage or age of the house to ensure
they are on the same scale.
• Advantages:
o Scales data within a specific range, usually [0, 1], making it suitable for algorithms that require a
fixed range.
o Works well when the data has a known range and is uniformly distributed.
o It does not assume any underlying distribution.
• Disadvantages:
o Sensitive to outliers: Extreme values in the data can distort the scaling.
o If the data distribution changes (for example, in online learning), the scaling may become
incorrect.
• Advantages:
o Less sensitive to outliers as it does not bound values to a specific range.
o Assumes data is normally distributed and is suitable for algorithms like linear regression, logistic
regression, and PCA.
o The resulting values have a mean of 0 and a standard deviation of 1, making it easier for many
algorithms to perform well.
• Disadvantages:
o It does not bound the data, so it may cause problems for algorithms like neural networks that use
activation functions sensitive to unbounded inputs (e.g., sigmoid).
o May not perform well if the data is not approximately normally distributed.
python
CopyEdit
from sklearn.feature_selection import SelectKBest, f_classif
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
python
CopyEdit
data = load_iris()
X = [Link]
y = [Link]
python
CopyEdit
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.3, random_state=42)
python
CopyEdit
selector = SelectKBest(score_func=f_classif, k=2) # Selecting top 2
features
X_train_selected = selector.fit_transform(X_train, y_train)
python
CopyEdit
model = LogisticRegression()
[Link](X_train_selected, y_train)
python
CopyEdit
X_test_selected = [Link](X_test)
print([Link](X_test_selected, y_test))
80. Real-World Scenario Using Both Machine Learning and Deep Learning
• Scenario: Autonomous Vehicle Navigation
o Machine Learning: Traditional ML models like Random Forests or Support Vector Machines
could be used to analyze sensor data for object detection and path planning.
o Deep Learning: Convolutional Neural Networks (CNNs) could be used for image-based tasks
like recognizing road signs and pedestrians.
Using both approaches would combine the advantages of traditional models (interpretability, efficiency) with the
power of deep learning (automatic feature extraction, high accuracy in complex tasks).
81. Explain the differences between mean, median, and mode, and provide examples
illustrating when each measure of central tendency is appropriate.
• Mean: The mean is the sum of all the values in a dataset divided by the number of
values. It is sensitive to outliers and skewed data.
o Example: In the dataset {1, 2, 3, 4, 100}, the mean is (1+2+3+4+100)/5 = 22,
which is skewed due to the outlier 100.
• Median: The median is the middle value when the data is sorted in ascending or
descending order. It is less affected by outliers.
o Example: In the dataset {1, 2, 3, 4, 100}, the median is 3. This is more
representative of the central tendency than the mean because it is not affected by
the outlier.
• Mode: The mode is the value that appears most frequently in the dataset. A dataset can
have no mode, one mode, or multiple modes.
o Example: In the dataset {1, 2, 2, 3, 4}, the mode is 2 because it appears twice.
• When to use each:
o Use the mean when the data is symmetric and there are no significant outliers.
o Use the median when the data is skewed or contains outliers.
o Use the mode when analyzing categorical data or when you want to identify the
most frequent value.
82. Discuss the process of conducting a one-sample t-test in Python. Provide step-by-step
instructions and interpret the results in the context of hypothesis testing.
A one-sample t-test is used to determine if the sample mean is significantly different from a
known or hypothesized population mean.
Steps in Python:
python
CopyEdit
import numpy as np
from scipy import stats
python
CopyEdit
sample_data = [value1, value2, value3, ...] # Replace with actual data
python
CopyEdit
t_statistic, p_value = stats.ttest_1samp(sample_data, population_mean)
83. Critically analyze the assumptions underlying the Central Limit Theorem (CLT) and
its implications for statistical inference. Provide examples of scenarios where the CLT
applies and where it may not be applicable.
The Central Limit Theorem (CLT) states that, for a sufficiently large sample size, the sampling
distribution of the sample mean will be approximately normal regardless of the population
distribution.
• Assumptions:
1. The samples are independent.
2. The sample size is large (typically n ≥ 30).
3. The underlying population has a finite variance.
• Implications:
1. CLT allows the use of normal distribution-based inference (e.g., confidence
intervals, hypothesis testing) even when the population distribution is not normal.
2. It enables estimation of population parameters from sample statistics.
• Where it applies:
1. When sampling from a large population (e.g., height, weight data) where the
underlying population may be skewed or unknown.
• Where it may not apply:
1. When the sample size is small and the population is highly skewed or has heavy
tails (e.g., income distribution).
2. When data is dependent (e.g., time series data).
84. Evaluate the impact of outliers on measures of central tendency and dispersion. Discuss
strategies for identifying and handling outliers in a dataset using Python.
python
CopyEdit
import numpy as np
data = [1, 2, 3, 4, 100] # Example data
Q1 = [Link](data, 25)
Q3 = [Link](data, 75)
IQR = Q3 - Q1
outliers = [x for x in data if x < Q1 - 1.5*IQR or x > Q3 +
1.5*IQR]
o Using Z-score:
python
CopyEdit
from [Link] import zscore
z_scores = zscore(data)
outliers = [data[i] for i in range(len(data)) if abs(z_scores[i])
> 3]
• Handling outliers:
o Remove outliers: For skewed data or when outliers are errors.
o Cap or transform outliers: Using methods like winsorization.
o Use robust statistics: For example, using median instead of mean.
85. Compare and contrast the advantages and limitations of using variance and standard
deviation as measures of dispersion. Provide examples to illustrate when each measure is
more informative in data analysis.
• Variance:
o Advantages: Simple to compute; useful for statistical analysis and modeling.
o Limitations: Units are squared, making interpretation harder.
o When to use: When comparing variability between datasets with the same units
or scale.
• Standard Deviation:
o Advantages: Provides a more interpretable measure of spread in the original
units.
o Limitations: Sensitive to outliers.
o When to use: When the data has a normal distribution or when interpretability is
important.
Example:
• If you want to understand how spread out exam scores are, the standard deviation is
more interpretable because it uses the same units as the scores.
86. Analyze the process of conducting a chi-squared test for independence in Python.
Discuss the steps involved in performing the test and interpreting the results in the context
of contingency tables.
The chi-squared test for independence is used to determine if there is a significant association
between two categorical variables.
Steps in Python:
python
CopyEdit
import pandas as pd
data = {'Category1': [10, 20, 30],
'Category2': [5, 15, 25]}
df = [Link](data)
python
CopyEdit
from [Link] import chi2_contingency
chi2, p_value, dof, expected = chi2_contingency(df)
87. Evaluate the ethical considerations associated with data collection and analysis in
descriptive statistics. Discuss potential biases, privacy concerns, and implications for
decision-making in real-world applications.
• Bias: Bias can arise during sampling, measurement, or analysis. It's crucial to ensure that
data collection methods are representative to avoid skewed conclusions.
o Example: Using only data from one demographic group may lead to biased
results.
• Privacy Concerns: Sensitive personal data must be anonymized or encrypted to protect
individual privacy.
o Example: Medical data should be handled following regulations like HIPAA to
protect patient confidentiality.
• Implications for decision-making: Inaccurate or biased data can lead to poor decision-
making, especially in fields like healthcare, finance, or marketing.
o Example: Misinterpreting survey data due to biased sampling could lead to
incorrect business decisions.
88. Assess the effectiveness of different visualization techniques, such as histograms, box
plots, and scatter plots, in conveying information about the distribution and relationships
within a dataset. Provide examples to support your analysis.
• Histograms: Useful for showing the distribution of a single variable. They provide
insights into the frequency of data points within different bins.
o Example: A histogram of exam scores can show whether the data is normally
distributed or skewed.
• Box plots: Effective for identifying outliers, the median, and the interquartile range
(IQR) of a dataset. Box plots give a visual summary of the distribution of the data.
o Example: A box plot of salaries can quickly show the spread, median, and
outliers in the data.
• Scatter plots: Best for visualizing the relationship between two continuous variables.
They can show trends, correlations, or clusters in the data.
o Example: A scatter plot showing height vs. weight can reveal a positive
correlation between the two variables.
89. Explain the concept of hypothesis testing and the role of p-values in statistical inference.
Provide examples to illustrate how p-values are interpreted in hypothesis testing.
• If you want to test if the average height of a population is 170 cm, and the p-value is 0.03,
you would reject the null hypothesis at a 0.05 significance level, concluding that the
average height is significantly different from 170 cm.
90. Discuss the assumptions underlying ANOVA and its applications in comparing means
across multiple groups. Provide examples of research scenarios where ANOVA would be
appropriate.
• Assumptions of ANOVA:
1. The data is normally distributed in each group.
2. The groups have equal variances (homogeneity of variance).
3. The observations are independent.
• Applications: ANOVA is used to compare the means of three or more independent
groups to determine if there is a statistically significant difference among them.
1. Example: Analyzing test scores from three different teaching methods (Group A,
Group B, and Group C) to see if the teaching method affects performance.
91. Apply the concept of Type I and Type II errors to real-world scenarios. Discuss the
consequences of each type of error and strategies for minimizing their occurrence in
hypothesis testing.
• Type I error (False Positive): Occurs when a null hypothesis is rejected even though it is
true. Example: A medical test incorrectly identifies a healthy person as diseased.
• Type II error (False Negative): Occurs when a null hypothesis is not rejected even
though it is false. Example: A test fails to detect a disease when it is present.
• Consequences:
o Type I error can lead to unnecessary treatments or false alarms.
o Type II error can lead to missed opportunities for early intervention or failure to
take corrective action.
• Minimizing Errors:
o For Type I: Set a stricter significance level (e.g., reduce alpha).
o For Type II: Increase sample size or use more powerful tests.
92. Implement a two-sample t-test in Python to compare the means of two independent
samples. Interpret the results and discuss the implications for decision-making.
python
CopyEdit
import numpy as np
from scipy import stats
# Example data: sample 1 and sample 2
sample1 = [Link]([12, 15, 14, 10, 13])
sample2 = [Link]([9, 7, 8, 6, 7])
# Print results
print(f"T-statistic: {t_stat}, P-value: {p_value}")
93. Analyze the process of conducting a Goodness of Fit Test (GOF) in Python. Discuss the
steps involved in performing the test and interpreting the results in the context of model
adequacy.
• Steps:
1. Define the observed and expected frequencies.
2. Calculate the chi-squared statistic: χ2=∑(Oi−Ei)2Ei\chi^2 = \sum \frac{(O_i -
E_i)^2}{E_i}χ2=∑Ei(Oi−Ei)2
3. Perform the test using [Link]().
python
CopyEdit
from [Link] import chisquare
• Interpretation: A p-value < 0.05 indicates that the model is a poor fit for the data, while
a larger p-value suggests no significant difference.
94. Compare and contrast the applications of one-sample Z test and one-sample t-test in
hypothesis testing. Discuss the factors influencing the choice between these two tests.
• One-sample Z-test: Used when the population variance is known and the sample size is
large (typically n > 30).
• One-sample t-test: Used when the population variance is unknown and/or the sample
size is small (n < 30).
• Choice of test: The Z-test assumes knowledge of the population standard deviation,
while the t-test is more flexible and often preferred when this information is not
available.
95. Evaluate the ethical implications of using statistical methods, such as hypothesis testing,
in decision-making processes. Discuss potential biases, ethical dilemmas, and
responsibilities of statisticians and data analysts.
• Ethical Implications:
o Biases: Statistical methods may perpetuate biases if not applied appropriately
(e.g., sampling bias, confirmation bias).
o Ethical dilemmas: Misuse of statistics to mislead or manipulate decision-makers
(e.g., cherry-picking data to fit a hypothesis).
• Responsibilities:
o Statisticians and data analysts have a duty to ensure their analyses are transparent,
accurate, and report findings honestly.
96. Assess the validity and reliability of statistical analyses conducted in research studies.
Discuss criteria for evaluating the quality of statistical evidence and implications for
drawing conclusions and making recommendations.
• Validity: Refers to whether the study measures what it intends to measure (internal and
external validity).
• Reliability: Refers to the consistency of the results across repeated trials or tests.
• Evaluating Evidence: Criteria include checking for sampling methods, control for
confounding variables, statistical power, and proper application of tests. If the evidence is
unreliable or invalid, conclusions and recommendations may be flawed.
97. Explain the purpose of using box plots in data visualization. Discuss how box plots
represent the distribution of data and provide insights into central tendency, dispersion,
and outliers.
98. Discuss the importance of data visualization in exploratory data analysis and hypothesis
generation. Provide examples of how visualizations can help identify patterns, trends, and
relationships in a dataset.
100. Implement a scatter plot matrix in Python using Seaborn. Interpret the
relationships between variables depicted in the scatter plots and discuss insights gained
from visualizing multivariate data.
Ans. A scatter plot matrix (pair plot) in Python, using Seaborn, visualizes relationships
between multiple numeric variables in a dataset. It creates scatter plots for each pair of variables
and histograms along the diagonal to show distributions.
Example:
python
CopyEdit
import seaborn as sns
import [Link] as plt
# Create pairplot
[Link](iris, hue='species')
[Link]()
Interpretation:
Insights:
This visualization is helpful for exploratory data analysis (EDA) and understanding
relationships between variables.
4o mini
101. Analyze the effectiveness of different types of visualizations, such as histograms, line
plots, and bar plots, in representing different types of data (e.g., continuous, categorical,
time-series). Discuss the strengths and limitations of each visualization type.
• Histograms:
o Best for: Continuous data, showing the distribution of a dataset.
o Strengths: Provide a clear view of data distribution, frequency of values, and
skewness.
o Limitations: Limited for categorical data and can be misleading with improperly
chosen bin widths.
• Line Plots:
o Best for: Time-series data, showing trends over time.
o Strengths: Useful for displaying changes over time and identifying trends or
cycles.
o Limitations: Less effective for categorical data or data that doesn’t have a
sequential order.
• Bar Plots:
o Best for: Categorical data, comparing frequencies or magnitudes of categories.
o Strengths: Simple, easy to interpret, and ideal for comparing different categories.
o Limitations: Not suitable for continuous data, can become cluttered with many
categories.
102. Evaluate the impact of data preprocessing techniques, such as data normalization and
feature scaling, on the effectiveness of data visualizations. Discuss how preprocessing can
influence the interpretation of visualizations and insights gained from the data.
103. Evaluate the ethical considerations associated with data visualization practices, such
as data representation, labeling, and storytelling. Discuss potential biases,
misinterpretations, and ethical responsibilities of data visualizers.
• Data Representation:
o Ethical considerations include accurately representing the data without
manipulating or distorting it to fit a particular narrative. Visualizations should not
mislead viewers about trends, distributions, or correlations.
• Labeling and Storytelling:
o Labels must be clear and accurately describe what the data points represent.
Misleading labels or color choices can misguide interpretation. Storytelling with
data should emphasize accuracy, ensuring that the visualization leads to informed
conclusions, not biased narratives.
• Bias and Misinterpretation:
o Bias can arise when data is cherry-picked to support a certain viewpoint, or when
statistical significance is overstated. Visualizations must be transparent and
should allow for the data to speak for itself.
• Ethical Responsibilities:
o Data visualizers have a responsibility to ensure transparency, avoid distortion, and
represent data ethically. They must be aware of how visualizations might
influence decision-making, especially in sensitive areas like healthcare or politics.
105. Explain the importance of handling missing values in a dataset before performing data
analysis. Discuss common techniques for handling missing data and their implications for
statistical analysis.
106. Discuss the concept of feature selection and its role in improving the performance and
interpretability of machine learning models. Provide examples of feature selection methods
and their applications in data preprocessing.
• Feature Selection:
o Feature selection refers to the process of selecting the most relevant features from
a dataset, which helps improve the performance of machine learning models by
reducing overfitting and computational cost.
• Role in Performance and Interpretability:
o By removing irrelevant or redundant features, models can become simpler and
more efficient, leading to improved accuracy and generalizability. Additionally,
fewer features make the model easier to interpret.
• Methods:
o Filter Methods: Using statistical techniques like correlation analysis to identify
the most relevant features.
o Wrapper Methods: Using machine learning models (e.g., forward selection,
backward elimination) to evaluate the impact of features.
o Embedded Methods: Feature selection performed during model training, like
Lasso regression.
107. Apply the concept of label encoding to convert categorical variables into numerical
format in Python. Discuss the advantages and limitations of label encoding and when it is
appropriate to use.
108. Analyze the impact of different feature engineering techniques, such as polynomial
features and interaction terms, on the predictive performance of machine learning models.
Discuss how feature engineering can improve model accuracy and generalization.
• Polynomial Features:
o Polynomial feature engineering creates new features by raising existing features
to a higher degree, which allows the model to capture non-linear relationships
between features and the target variable.
• Interaction Terms:
o Interaction terms create new features that represent interactions between two or
more features. This allows the model to capture more complex relationships,
potentially improving predictive performance.
• Impact on Accuracy and Generalization:
o Properly applied feature engineering can significantly improve the model’s
accuracy by providing additional information. However, excessive feature
engineering can lead to overfitting. Balancing between adding new features and
maintaining model generalization is key.
109. Implement data normalization using min-max scaling in Python. Discuss how
normalization affects the distribution of data and the performance of machine learning
models.
• PCA:
o PCA reduces the dimensionality of data by finding the directions (principal
components) that maximize the variance. It is effective for linear datasets and
helps in visualizing high-dimensional data in 2D or 3D while retaining the most
important features.
• t-SNE:
o t-SNE is a non-linear technique that is particularly good at visualizing complex,
high-dimensional datasets in lower dimensions (e.g., 2D or 3D). It’s more
computationally intensive but works well for visual exploration.
• Trade-offs:
o Dimensionality reduction often involves a trade-off between simplifying the
dataset and losing information. PCA can discard some variance in the data, while
t-SNE can sometimes distort global structures. The challenge is to find the
balance between reducing complexity and retaining important information.
111. Analyze the performance of different machine learning algorithms, such as K-Means
Clustering and ANN, in real-world applications. Compare the strengths and limitations of
each algorithm and discuss factors influencing their performance.
• K-Means Clustering:
o Strengths: Simple, fast, and effective for clustering large datasets. It works well
when clusters are spherical and well-separated.
o Limitations: Sensitive to initial cluster centroids, and it assumes clusters of
similar sizes. It doesn’t perform well when clusters have irregular shapes or if the
data is noisy.
o Factors affecting performance: The number of clusters (k), data scale, and the
distribution of data (e.g., dense vs. sparse). Choosing the right value for k can be
challenging, and the algorithm is sensitive to outliers.
• ANN (Artificial Neural Network):
o Strengths: Highly flexible and powerful for tasks like image classification,
speech recognition, and natural language processing. It can learn complex patterns
from large datasets.
o Limitations: Computationally expensive, requires large datasets for training, and
is prone to overfitting if not regularized properly. It may also lack interpretability,
making it difficult to understand how the model arrived at its decisions.
o Factors affecting performance: Network architecture (number of layers,
neurons), data quality, and the availability of labeled data for training.
Hyperparameter tuning, like the learning rate and batch size, also significantly
impacts model performance.
112. Evaluate the interpretability of machine learning models in case studies such as
market analysis and academic performance prediction. Discuss techniques for interpreting
model predictions and understanding the underlying factors driving the outcomes.
• Market Analysis: Models like linear regression or decision trees are more interpretable
because their outputs are easier to trace. For example, a decision tree can explicitly show
which features most influence sales prediction, such as advertising spend or seasonal
trends.
• Academic Performance Prediction: Simple models (like logistic regression) can be
interpreted by examining the coefficients to understand how factors like study time or
attendance affect student performance. More complex models like neural networks may
require techniques like LIME or SHAP to provide explanations for predictions.
• Interpretation Techniques:
o LIME (Local Interpretable Model-Agnostic Explanations) and SHAP
(SHapley Additive exPlanations): These techniques provide local explanations
for individual predictions, helping to understand the impact of each feature on the
final decision.
o Feature Importance: This helps to identify which features (e.g., age, income,
education level) contribute most to the model’s decision, providing transparency
into how the model works.
113. Evaluate the ethical implications of using machine learning and deep learning models
in sensitive domains such as finance and education. Discuss potential risks of algorithmic
bias, discrimination, and privacy violations, and propose strategies for ensuring fairness,
transparency, and accountability in model deployment.
• Ethical Implications:
o Bias and discrimination: Machine learning models can inherit biases from
historical data, leading to unfair decisions. For example, in finance, biased
lending algorithms might unfairly disadvantage minority groups. In education,
biased models may perpetuate systemic inequalities.
o Privacy violations: Models that process sensitive data, such as personal financial
information or student records, risk violating privacy if not properly managed.
Unauthorized data use or poor data anonymization practices can lead to privacy
breaches.
• Strategies for Fairness and Accountability:
o Bias Mitigation: Implement fairness-aware algorithms and fairness constraints
during model development to ensure that the models do not favor certain groups
over others.
o Transparency: Use interpretable models or model explanation techniques (e.g.,
SHAP or LIME) to provide insight into how models make decisions, which
fosters transparency.
o Regular Audits: Continuously evaluate and update models after deployment to
ensure they remain fair and unbiased. Engage third-party audits to verify fairness
and compliance with regulations.
114. Assess the societal impact of machine learning and deep learning applications in case
studies such as image analysis and audio analysis. Discuss implications for privacy,
security, and human rights, and propose frameworks for responsible AI development and
deployment.
115. Evaluate the ethical implications of using automated data preprocessing tools, such as
AutoML frameworks, in machine learning workflows. Discuss potential biases, privacy
concerns, and implications for decision-making in automated data preprocessing.
• Biases: Automated data preprocessing tools, like AutoML frameworks, often rely on
historical data. If the training data is biased, the automation process will likely perpetuate
or even amplify these biases. For example, if data preprocessing includes downsampling
underrepresented groups, the model will fail to generalize properly across the entire
population.
• Privacy Concerns: Automated tools may inadvertently expose sensitive information,
particularly if data anonymization processes are skipped or if personal data is mishandled
during preprocessing stages. There is also the risk of data leakage if the automated
system accesses sensitive user data without proper security checks.
• Implications for Decision-Making: The decisions made by automated systems could be
less transparent, as the data preprocessing steps may be hidden within the tool’s
algorithms. Without human oversight, it could lead to decisions that lack accountability
or are based on incomplete or inaccurate data processing.
116. Assess the impact of data preprocessing decisions on the fairness and transparency of
machine learning models. Discuss strategies for ensuring fairness and accountability in
data preprocessing practices and their implications for model interpretability and
trustworthiness.
117. Explain the applications of linear regression in market analysis and its limitations in
capturing nonlinear relationships. Discuss strategies for addressing nonlinearities in
regression modeling.
118. Discuss the concept of logistic regression and its applications in binary classification
tasks, such as text editing. Provide examples of scenarios where logistic regression is
suitable and discuss its advantages over other classification algorithms.
119. Apply the concept of K-Means Clustering to analyze academic performance data and
identify student clusters based on academic achievement. Discuss the interpretation of
clustering results and potential applications for personalized learning interventions.
120. Implement an Artificial Neural Network (ANN) in Python for image analysis tasks
such as image classification or object detection. Discuss the architecture of the ANN model
and its suitability for processing image data.
121. Evaluate the ethical implications of using descriptive statistics techniques in decision-
making processes within healthcare organizations.
Descriptive statistics (mean, median, mode, etc.) help summarize and interpret healthcare data,
aiding administrators and clinicians in making informed decisions. However, ethical concerns
arise when data is misrepresented or oversimplified.
122. Assess the effectiveness of different measures of dispersion, such as variance and
standard deviation, in analyzing the variability of healthcare data.
Variance and standard deviation quantify how data values deviate from the mean, essential in
identifying variability in outcomes like blood pressure, recovery time, etc.
• Effectiveness: Standard deviation is widely used due to interpretability (in original units).
High variability may indicate inconsistency in care quality.
• Implications: Low dispersion can suggest standardized procedures; high dispersion may
highlight areas for improvement.
Quality Improvement: Helps in benchmarking performance and setting realistic clinical
goals.
Patient Outcomes: Better variability management leads to more predictable, reliable
care.
123. Critically analyze the reliability and validity of statistical analyses conducted in
clinical research studies.
• Reliability: Refers to consistency. Can be compromised by small sample sizes, data entry
errors, or inconsistent measurement tools.
• Validity: Refers to accuracy. Threatened by selection bias, confounding variables, or
poor study design.
Evaluation Criteria:
• Use of confidence intervals and p-values.
• Appropriateness of statistical tests.
• Peer review and replication of findings.
Implications: Poor reliability/validity undermines trust in evidence-based practices and
can lead to ineffective or harmful interventions.
125. Assess the validity and reliability of statistical evidence presented in regulatory
submissions for new drug approvals.
• Validity: Should reflect true safety/efficacy. Threatened by small samples or short trial
durations.
• Reliability: Ensures reproducibility under similar conditions.
Statistical Role:
• Demonstrates treatment effects via inferential statistics.
• Supports dose selection, adverse effect risk, and efficacy comparison.
Implications: Weak evidence can lead to premature approval or withdrawal, affecting
public trust and patient health.
Best Practices: Require robust trial design, long-term safety follow-ups, and cross-
validation with real-world evidence.
126. Critically analyze the ethical implications of statistical modeling techniques, such as
logistic regression, in predicting patient outcomes and treatment responses.
• Bias: Models trained on biased data may discriminate against certain populations.
• Discrimination: Predictive outcomes may reinforce existing inequalities (e.g., race or
socioeconomic status).
• Privacy: Use of identifiable data without consent is unethical.
Strategies:
• Audit models for bias regularly.
• Use fairness-aware algorithms.
• Ensure transparent model documentation and informed consent practices.
128. Assess the ethical considerations associated with visual representations of healthcare
data, such as COVID-19 case counts and vaccination rates.
129. Critically analyze the impact of interactive data visualizations on health literacy and
patient engagement.
• Impact: Tools like interactive dashboards and symptom trackers empower users to
explore data relevant to them.
• Examples: CDC’s COVID Data Tracker, WHO vaccine dashboards.
Implications:
• Improves individual awareness and behavior.
• Enhances trust through transparency.
Challenges: Digital divide, misinformation risk.
Recommendations:
• Design for accessibility and multilingual support.
• Include educational components and guided interactions.
130. Evaluate the ethical implications of using automated data preprocessing tools, such as
AutoML frameworks, in healthcare analytics.
131. Assess the impact of data preprocessing decisions on the fairness and interpretability
of machine learning models used in clinical decision support systems.
132. Critically analyze the challenges of integrating electronic health records (EHR) data
from multiple sources for predictive modeling.
133. Evaluate the ethical considerations associated with using machine learning
models for personalized medicine. Discuss potential biases, privacy concerns, and
implications for patient autonomy and informed consent, and propose strategies
for ensuring fairness and transparency in predictive modeling.
Answer:
Machine learning (ML) models in personalized medicine tailor treatments to individual patient
profiles, improving outcomes. However, they raise several ethical challenges:
Strategies:
Answer:
ML has significantly impacted clinical workflows:
• AI-powered Diagnostic Tools: Examples include Google’s DeepMind for eye disease
and IBM Watson for oncology. These tools can identify patterns missed by humans.
• Treatment Recommendation Systems: ML models can suggest optimal treatment plans
based on past data, patient profiles, and real-world evidence.
Implications:
135. Critically analyze the societal implications of using deep learning models for
image analysis in radiology. Discuss the potential benefits of AI-assisted
diagnosis and challenges such as model interpretability, regulatory approval, and
workforce displacement.
Answer:
Benefits:
Challenges:
• Interpretability: Deep learning is a "black box"; lack of transparency can reduce trust.
• Regulatory Approval: AI tools must meet stringent FDA/EMA regulations, often
lacking clinical trial validation.
• Workforce Displacement: There are concerns that radiologists could be replaced,
although current consensus suggests AI will augment, not replace.
136. Write a Python function that takes a NumPy array as input and returns a
dictionary containing descriptive statistics such as mean, median, mode,
variance, and standard deviation. Test the function with sample data and
visualize the distribution using Matplotlib.
python
CopyEdit
import numpy as np
import [Link] as plt
from scipy import stats
def descriptive_stats(data):
return {
'mean': [Link](data),
'median': [Link](data),
'mode': [Link](data, keepdims=True)[0][0],
'variance': [Link](data),
'std_dev': [Link](data)
}
# Visualization
[Link](sample, bins=30, edgecolor='black', alpha=0.7)
[Link]("Distribution of Sample Data")
[Link]("Value")
[Link]("Frequency")
[Link]()
137. Develop a Python script that uses NumPy to generate a random sample from
a given dataset with replacement. Implement bootstrapping to estimate the
confidence interval for the mean of the sample and visualize the sampling
distribution using Matplotlib.
python
CopyEdit
import numpy as np
import [Link] as plt
# Visualization
[Link](means, bins=30, alpha=0.7)
[Link](lower, color='red', linestyle='dashed', label=f"{ci}% CI
Lower")
[Link](upper, color='green', linestyle='dashed', label=f"{ci}% CI
Upper")
[Link]("Bootstrap Sampling Distribution")
[Link]()
[Link]()
# Test
data = [Link](100, 15, 500)
ci_bounds = bootstrap_ci(data)
print(f"{ci_bounds[0]:.2f}, {ci_bounds[1]:.2f}")
class CustomDist:
def __init__(self, mean=0, std=1):
[Link] = mean
[Link] = std
def plot(self):
x = [Link]([Link] - 4*[Link], [Link] + 4*[Link], 100)
y = [Link](x)
[Link](x, y, label='PDF')
[Link]('Custom Normal Distribution')
[Link]('x')
[Link]('PDF')
[Link]()
[Link]()
# Test
dist = CustomDist(0, 1)
[Link]()
139. Develop a Python function that performs a two-sample t-test using only
NumPy arrays. Test the function with simulated data from two different
populations and visualize the distributions using Matplotlib.
python
CopyEdit
import numpy as np
import [Link] as plt
print(f"T-statistic: {t_value:.2f}")
140. Write a Python class that implements simple linear regression using NumPy.
Include methods for fitting the model, making predictions, and evaluating
performance using R-squared and MSE.
python
CopyEdit
import numpy as np
import [Link] as plt
class SimpleLinearRegression:
def fit(self, x, y):
self.x_mean = [Link](x)
self.y_mean = [Link](y)
self.coef_ = [Link]((x - self.x_mean)*(y - self.y_mean)) / [Link]((x
- self.x_mean)**2)
self.intercept_ = self.y_mean - self.coef_ * self.x_mean
# Test
x = [Link](100) * 10
y = 3 * x + 7 + [Link](100)
model = SimpleLinearRegression()
[Link](x, y)
r2, mse = [Link](x, y)
[Link](x, y, label='Data')
[Link](x, [Link](x), color='red', label='Regression Line')
[Link]("Linear Regression")
[Link]()
[Link]()
141. Create a Python function that computes the ANOVA table for a given
dataset with categorical variables using only NumPy.
python
CopyEdit
import numpy as np
def anova(groups):
k = len(groups)
n_total = sum([len(g) for g in groups])
grand_mean = [Link]([Link](groups))
df_between = k - 1
df_within = n_total - k
ms_between = ss_between / df_between
ms_within = ss_within / df_within
f_stat = ms_between / ms_within
return {
"SSB": ss_between, "SSW": ss_within,
"dfB": df_between, "dfW": df_within,
"MSB": ms_between, "MSW": ms_within,
"F": f_stat
}
# Test
group1 = [Link](10, 2, 30)
group2 = [Link](15, 2, 30)
group3 = [Link](20, 2, 30)
print(anova([group1, group2, group3]))
142. Develop a Python script that generates an interactive scatter plot using
Matplotlib and ipywidgets.
python
CopyEdit
import pandas as pd
import [Link] as plt
from ipywidgets import interact, Dropdown
# Sample data
df = [Link]({
"Age": [Link](20, 60, 100),
"BloodPressure": [Link](80, 150, 100),
"Cholesterol": [Link](150, 250, 100)
})
interact(plot_scatter,
x_axis=Dropdown(options=[Link], value='Age'),
y_axis=Dropdown(options=[Link], value='BloodPressure'))
143. Write a Python function that creates a custom box plot with outliers
highlighted.
python
CopyEdit
import pandas as pd
import numpy as np
import [Link] as plt
[Link](data)
[Link](np.full_like(outliers, 1), outliers, color='red',
label='Outliers')
[Link](f"Custom Box Plot: {column}")
[Link]()
[Link]()
# Test
df = [Link]({"Value": [Link]([Link](50, 10, 100), [120,
130])})
custom_boxplot(df, 'Value')
144. Create a Python script that generates a 3D surface plot with interactive
sliders.
python
CopyEdit
import numpy as np
import [Link] as plt
from mpl_toolkits.mplot3d import Axes3D
from ipywidgets import interact, FloatSlider
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
[Link]()
145. Develop a Python function for custom missing value imputation using
Pandas and NumPy.
python
CopyEdit
import pandas as pd
import numpy as np
# Test
df = [Link]({
"Age": [25, [Link], 30, 35, [Link]],
"Gender": ['M', 'F', [Link], 'F', 'M']
})
print(custom_imputer([Link](), method='mode'))
def min_max_normalize(df):
numerical_df = df.select_dtypes(include=[[Link]])
normalized_array = (numerical_df - numerical_df.min()) /
(numerical_df.max() - numerical_df.min())
return normalized_array
# Sample DataFrame
df = [Link]({
'Age': [25, 45, 35, 50, 23],
'Income': [30000, 60000, 45000, 80000, 20000]
})
normalized_df = min_max_normalize(df)
# Visualization
normalized_df.plot(kind='box', title='Normalized Feature Distribution')
[Link](True)
[Link]()
147. Create a Python function that performs principal component analysis (PCA)
using NumPy. The function should take a high-dimensional dataset as input and
return the transformed dataset with reduced dimensionality. Visualize the
explained variance ratio of principal components using Matplotlib.
python
CopyEdit
def pca_numpy(X, n_components=2):
X_meaned = X - [Link](X, axis=0)
cov_mat = [Link](X_meaned, rowvar=False)
eigen_vals, eigen_vecs = [Link](cov_mat)
sorted_idx = [Link](eigen_vals)[::-1]
eigen_vals = eigen_vals[sorted_idx]
eigen_vecs = eigen_vecs[:, sorted_idx]
explained_variance_ratio = eigen_vals / [Link](eigen_vals)
selected_vectors = eigen_vecs[:, :n_components]
reduced_data = [Link](X_meaned, selected_vectors)
# Sample data
X = [Link](100, 5)
reduced, var_ratio = pca_numpy(X)
# Visualization
[Link]([Link](var_ratio), marker='o')
[Link]('Number of Components')
[Link]('Cumulative Explained Variance')
[Link]('Explained Variance by Principal Components')
[Link](True)
[Link]()
class CustomKNN:
def __init__(self, k=3):
self.k = k
# Test
from [Link] import load_iris
iris = load_iris()
X, y = [Link], [Link]
indices = [Link](len(X))
X_train, y_train = X[indices[:-30]], y[indices[:-30]]
X_test, y_test = X[indices[-30:]], y[indices[-30:]]
model = CustomKNN(k=3)
[Link](X_train, y_train)
predictions = [Link](X_test)
149. Write a Python script that defines a custom neural network architecture
using NumPy arrays. Implement methods for forward propagation,
backpropagation, and parameter updates using gradient descent. Test the neural
network with a sample dataset for binary classification and visualize the decision
boundary using Matplotlib.
python
CopyEdit
import numpy as np
import [Link] as plt
from [Link] import make_moons
from sklearn.model_selection import train_test_split
class SimpleNN:
def __init__(self, input_size, hidden_size):
self.W1 = [Link](input_size, hidden_size)
self.b1 = [Link]((1, hidden_size))
self.W2 = [Link](hidden_size, 1)
self.b2 = [Link]((1, 1))
# Test
X, y = make_moons(n_samples=500, noise=0.2)
y = [Link](-1, 1)
nn = SimpleNN(input_size=2, hidden_size=5)
[Link](X, y, epochs=1000, lr=0.1)
# Decision boundary
x_min, x_max = X[:, 0].min(), X[:, 0].max()
y_min, y_max = X[:, 1].min(), X[:, 1].max()
xx, yy = [Link]([Link](x_min, x_max, 100), [Link](y_min,
y_max, 100))
grid = np.c_[[Link](), [Link]()]
probs = [Link](grid).reshape([Link])