1. Data
Deadline and Submission
27.aug (thursday)
Commits until 23:59
Individual
Submission the GitHub Pages' Link (yes, only the link for pages) via insper.blackboard.com.
Activity: Data Preparation and Analysis for Neural Networks
This activity is designed to test your skills in generating and manipulating synthetic datasets, handling real-world data challenges, and preparing data to be fed into neural networks.
The thread running through the activity is the spread of the data: how much a point cloud spreads out, in which direction it spreads, and how that changes the difficulty of the classification problem.
Technical rules (they apply to the whole activity)
- Fix the random seed β
rng = np.random.default_rng(42)β and use the samerngthroughout the report. Results that cannot be reproduced score no points; - Every plot must have a title, axis labels, and a class legend;
- Allowed libraries:
numpy,pandas,matplotlib/seaborn,scikit-learnβ the latter for PCA and preprocessing only; no model is trained in this activity; - Whenever the statement asks for a number (mixing rate, explained variance, missing counts), report the number in the text β not only in the code output;
- Organize the report with one heading per exercise and one subheading per item (
Exercise 1,A,B, β¦), in the same order as the statement, and number the figures as indicated. The last section of the report must be the Results summary described at the end of this page.
Exercise 1
Point Clouds: Geometry and Spread in 2D
Understanding how data is distributed is the first step before designing a network architecture. In this exercise you will generate and measure two-dimensional point clouds, observing how the distribution affects the complexity of the decision boundaries a neural network would need to learn.
A β Generate the clouds
Create a synthetic dataset with a total of 400 samples, divided equally among 4 classes (100 samples each). Use a Gaussian distribution to generate the points for each class based on the following parameters:
- Class 0: Mean = \([2, 3]\), Standard Deviation = \([0.8, 2.5]\)
- Class 1: Mean = \([5, 6]\), Standard Deviation = \([1.2, 1.9]\)
- Class 2: Mean = \([8, 1]\), Standard Deviation = \([0.9, 0.9]\)
- Class 3: Mean = \([15, 4]\), Standard Deviation = \([0.5, 2.0]\)
Produce Figure 1: a 2D scatter plot with all the points, one color per class, with the center of each cloud (its mean) marked on the plot.
B β More or less spread out
The standard deviation controls how much each cloud spreads around its center. Generate the same 4 classes from item A, four times over, multiplying all standard deviations by a scale factor \(s\) β the means never change, only the spread:
So this is 4 datasets of 4 classes each β not one dataset of 4 scales with different classes.
- Produce Figure 2: 4 subplots (one per value of \(s\)), sharing the same axis limits, so the comparison is honest.
-
Compute, for \(s = 1\) only, the separation ratio of each pair of classes \((i, j)\):
\[ r_{ij} = \frac{\lVert \mu_i - \mu_j \rVert}{\bar{\sigma}_i + \bar{\sigma}_j}, \qquad \bar{\sigma}_k = \frac{\sigma_{k,x} + \sigma_{k,y}}{2} \]High values mean well separated clouds; low values, clouds that blend into each other. There are 6 pairs β report them in a table and say which is the smallest. Since the means do not change, \(r_{ij}\) scales with \(1/s\): state what that smallest \(r_{ij}\) becomes at \(s = 2\) without generating anything new. 1. Compute, for each \(s\), the mixing rate: the fraction of points whose nearest class center is not the one of their own class. With NumPy this is comparing each point against the 4 means β a purely geometric measure, with nothing to train. 1. Produce Figure 3: a plot of mixing rate \(\times\) \(s\). Answer: from which scale factor on can the clouds no longer be separated by straight lines? What happens to the smallest \(r_{ij}\) at that point?
C β Analysis
- Describe the overlap of the four classes in the original dataset (\(s = 1\)). Could a single linear boundary separate all classes? What about a set of linear boundaries?
- Sketch on Figure 1 the decision boundaries you think a trained neural network might learn.
- Relate your sketch to item B: the more spread out the clouds are, what happens to the region where the network necessarily makes mistakes?
Exercise 2
Non-Linearity in Higher Dimensions
Simple neural networks (like a Perceptron) can only learn linear boundaries. Deep networks shine when the data is not linearly separable. This exercise contrasts two datasets of the same dimensionality to make that difference explicit.
A β Dataset I: shifted Gaussians
Generate 500 samples for Class A and 500 for Class B, using a multivariate normal distribution with the parameters below.
-
Class A:
Mean vector:
\[\mu_A = [0, 0, 0, 0, 0]\]Covariance matrix:
\[ \Sigma_A = \begin{pmatrix} 1.0 & 0.8 & 0.1 & 0.0 & 0.0 \\ 0.8 & 1.0 & 0.3 & 0.0 & 0.0 \\ 0.1 & 0.3 & 1.0 & 0.5 & 0.0 \\ 0.0 & 0.0 & 0.5 & 1.0 & 0.2 \\ 0.0 & 0.0 & 0.0 & 0.2 & 1.0 \end{pmatrix} \] -
Class B:
Mean vector:
\[\mu_B = [1.5, 1.5, 1.5, 1.5, 1.5]\]Covariance matrix:
\[ \Sigma_B = \begin{pmatrix} 1.5 & -0.7 & 0.2 & 0.0 & 0.0 \\ -0.7 & 1.5 & 0.4 & 0.0 & 0.0 \\ 0.2 & 0.4 & 1.5 & 0.6 & 0.0 \\ 0.0 & 0.0 & 0.6 & 1.5 & 0.3 \\ 0.0 & 0.0 & 0.0 & 0.3 & 1.5 \end{pmatrix} \]
Note that the two classes have different spreads: \(\Sigma_B\) has larger variances and a negative correlation between the first two features, while \(\Sigma_A\) has a positive one.
B β Dataset II: concentric shells
Generate a second dataset, also with 500 samples per class and also in 5 dimensions, but with radial structure:
- Draw directions uniformly on the unit sphere of \(\mathbb{R}^5\) β draw \(v \sim \mathcal{N}(0, I_5)\) and normalize, \(u = v / \lVert v \rVert\);
- Class C (core): radius \(\rho \sim \mathcal{N}(2.0,\ 0.4)\);
- Class D (shell): radius \(\rho \sim \mathcal{N}(5.0,\ 0.4)\);
- Each point is \(x = \rho \cdot u\).
C β Visualize and compare
You cannot plot a 5D graph directly, so reduce the dimensionality.
- Produce Figure 4: apply PCA to project each dataset into 2 dimensions and plot the two scatter plots side by side, colored by class;
- Report the explained variance of the first two components in each case. In which dataset does the 2D projection better preserve the information relevant for classification?
- For each dataset, compute in 5D and report:
- the distance between the class centers, \(\lVert \mu_1 - \mu_2 \rVert\);
- Figure 5: the histogram of the radius \(\lVert x \rVert\) of each point, with both classes overlaid on the same axis.
D β Analysis
- In Dataset II the distance between the centers is close to zero, yet the radius histograms are well separated. What does that combination tell you about the possibility of separating the classes with a hyperplane?
- Explain why the structure of Dataset II cannot be solved by a linear boundary, no matter how much data is collected.
- PCA is a linear transformation. Discuss: does a 2D projection in which the classes look mixed prove that they are inseparable in the original space? Justify with your own results, and write a simple function of the inputs that separates Dataset II (hint: look at \(\lVert x \rVert^2 = \sum_i x_i^2\)).
Exercise 3
Preparing Real-World Data for a Neural Network
This exercise uses a real dataset from Kaggle. Your task is to perform the preprocessing required to make it suitable for a neural network that uses the hyperbolic tangent (tanh) activation function in its hidden layers.
A β Get to know the data
- Download the Spaceship Titanic dataset (use
train.csv, the only labeled file). - Describe the goal of the dataset: what does the
Transportedcolumn represent? What is the class balance between the two labels? - List the features, separating numerical (e.g.,
Age,RoomService) from categorical (e.g.,HomePlanet,Destination). - Build a table of missing values per column, in absolute count and in percentage.
- For the spending columns (
RoomService,FoodCourt,ShoppingMall,Spa,VRDeck), report mean, median, and maximum. Compare mean and median: what does that difference tell you about the spread and the skewness of those distributions?
B β Split before you transform
Data leakage
Every statistic used in the transformation β mean, standard deviation, median, observed categories β must be computed only on the training set. Computing it on the full dataset and splitting afterwards is data leakage, and the reported performance stops being trustworthy.
- Split train and test 80/20, stratified by the target, with a fixed seed;
- Explain, in two or three sentences, why this split comes before imputation and scaling.
C β Preprocess
The tanh activation outputs values in \([-1, 1]\), so the inputs must be on a compatible scale.
- Missing data: define and implement a strategy per column type (numerical Γ categorical) and justify each choice. Fit the imputer on the training set and apply it to the test set;
- Categorical features: convert
HomePlanet,CryoSleep,Destination, andVIPto numerical format (one-hot encoding is a good choice). Explain how your code handles a category that appears in the test set but not in the training set; - Feature engineering: create the
TotalSpendfeature, the sum of the five spending columns (dropCabin,Name, andPassengerId); - Heavy tails: apply \(\log(1 + x)\) to the spending columns and show the histogram of one of them before and after. Why does this transformation help a network with
tanh? - Scaling: scale the numerical columns with Standardization (mean 0, std 1) or Normalization to \([-1, 1]\). Implement one of them, explain the choice, and report the resulting minimum and maximum values.
D β Verify and visualize
- Figure 6: histogram of one heavy-tailed feature (
FoodCourt, for instance) before and after preprocessing; - Final checks, explicitly reported: no remaining
NaN; the final shape of the feature matrix; the value range is compatible withtanh; - In one paragraph: which of your preprocessing decisions do you think would most affect the network's training, and why?
Results summary
Close the report with this table filled in. It replaces no analysis β it is an index of the numbers you already computed, gathered in one place so grading can check each value without hunting for it.
| # | Item | Your value |
|---|---|---|
| 1 | Mixing rate at \(s = 0.5\) | |
| 2 | Mixing rate at \(s = 1.0\) | |
| 3 | Mixing rate at \(s = 2.0\) | |
| 4 | Mixing rate at \(s = 4.0\) | |
| 5 | Smallest \(r_{ij}\) at \(s = 1.0\), and which pair | |
| 6 | Distance between centers β Dataset I | |
| 7 | Distance between centers β Dataset II | |
| 8 | Explained variance PC1 + PC2 β Dataset I | |
| 9 | Explained variance PC1 + PC2 β Dataset II | |
| 10 | Share of the positive class in Transported | |
| 11 | Mean and median of FoodCourt on the training set, before transforming | |
| 12 | Final shape of the training feature matrix | |
| 13 | Minimum and maximum of the training and test sets after scaling |
Evaluation Criteria
The deliverable for this activity is a report that includes:
- A brief description of your approach to each exercise.
- The code used to generate the datasets, preprocess the data, and create the visualizations, with comments explaining each step.
- The plots and visualizations requested in each exercise.
- Your analysis and answers to the questions posed in each exercise.
Important Notes:
-
The deliverable must be submitted in the specified format: GitHub Pages. No other format will be accepted. There is a course template you may use β template;
-
There is a strict no-plagiarism policy. Any form of plagiarism will result in a zero grade for the activity;
-
The deadline for each activity is not extended β NO EXCEPTIONS will be made for late submissions.
-
AI collaboration is allowed, but each student MUST UNDERSTAND and be able to explain every part of the submitted code and analysis. Any use of AI tools must be properly cited. ORAL EXAMS may be conducted.
Grading Criteria:
Each row is worth the points indicated, awarded in full, partially (half), or not at all: in full when the item is complete and correct; partially when it is implemented but missing the requested analysis, or when the analysis lacks the numerical result that supports it; zero when absent or incorrect.
Exercise 1 β Point clouds (3 points):
| Points | Criterion | What earns full credit |
|---|---|---|
| 0.5 | Generating the 4 clouds (A) | Correct parameters, 100 samples per class, fixed seed, readable Figure 1 with the centers marked. |
| 1.5 | Spread study (B) | The 4 datasets generated (the same 4 classes, 4 scales), Figure 2 with shared axes, table of \(r_{ij}\) at \(s = 1\), the 4 mixing rates, and Figure 3. |
| 1.0 | Analysis (C) | Identifies the scale factor where linear separability is lost, connects that point to \(r_{ij}\), and the sketched boundaries are consistent with the plotted data. |
Exercise 2 β Non-linearity in 5D (3 points):
| Points | Criterion | What earns full credit |
|---|---|---|
| 0.5 | Dataset I (A) | Multivariate Gaussians generated with the specified means and covariances. |
| 0.5 | Dataset II (B) | Correct concentric shells, with the directions normalized on the unit sphere. |
| 0.5 | PCA projection (C) | PCA applied to both datasets, comparable scatter plots, and explained variance reported. |
| 0.5 | Geometric measures (C) | Distance between centers and per-class radius histograms, computed in 5D on both datasets. |
| 1.0 | Analysis (D) | Uses coincident centers Γ separated radii to reach the correct conclusion about the hyperplane, answers that a poor linear projection does not prove inseparability, and proposes a function of the inputs that separates Dataset II. |
Exercise 3 β Real-world data (4 points):
| Points | Criterion | What earns full credit |
|---|---|---|
| 0.75 | Data description (A) | Goal, target balance, feature types, missing-value table, and mean/median/maximum of the spending columns, with the mean Γ median reading. |
| 0.75 | Leakage-free split (B) | Stratified split with a fixed seed before any statistic, with a correct justification. |
| 1.5 | Preprocessing (C) | Imputation, encoding, TotalSpend, \(\log(1+x)\), and scaling β all fitted on the training set and applied to the test set, each choice justified. |
| 0.5 | Visualization (D) | Figure 6 before/after showing the effect of the transformation, with labeled axes. |
| 0.5 | Final checks and reflection (D) | No NaN, shape and value range explicitly reported, plus the reflection paragraph. |
Deductions:
| Deduction | Reason |
|---|---|
| β0.5 | Non-reproducible results (seed not fixed, or code that does not run end to end). |
| β0.5 | Plots without a title, axis labels, or class legend. |
| β1.0 | Preprocessing statistics computed on the full dataset (data leakage) in Exercise 3. |