02 Representation Learning: Extracting Core Insights from High-Dimensional Data
90-Minute Main Lesson: From Scale to PCA Evidence
Objectives: Diagnose scale and missingness; calculate a two-dimensional PCA by hand; interpret variance ratios and loadings; distinguish PCA, LDA, and exploratory nonlinear embeddings.
learning path:
prerequisites and preprocessing 15 min → PCA intuition, calculation, and derivation 30 min → LDA comparison and check 15 min → Yangtze Delta main case 25 min → synthesis 5 min.
MDS, manifold learning, and sparse representation are extensions.
Answer first: If variable A has 100 times the standard deviation of B, what happens when PCA uses the raw covariance matrix?
Feedback: A may dominate PC1 only because of units. Unless units carry intended economic meaning, fit the scaler on training data only.
Welcome to Chapter 2: Representation Learning
Today’s Agenda:
Introduction: Why do Economics and Finance need ‘dimensionality reduction’?
Data Preprocessing: The cornerstone of success
Part 1: Linear Methods (PCA, LDA, MDS)
Part 2: Nonlinear Manifold Learning (Isomap, LLE, t-SNE)
Part 3: Advanced Topics (Sparse Representation)
Conclusion: How to choose the right tool for your problem
Core Question: Why Study ‘Dimensionality Reduction’ in Economics?
Imagine we want to predict a company’s stock return. How many variables might we have?
Firm-Level Data: Hundreds of financial ratios (P/E, ROA, leverage…)
Alternative Data: Satellite imagery, news sentiment, supply chain info…
We can easily end up with a dataset of hundreds or even thousands of dimensions.
We Face a ‘Data-Rich, Insight-Poor’ Dilemma
The explosive growth in data volume does not directly translate to an increase in insight. The goal of representation learning is to extract the signal from the noise.
This is the so-called ‘Curse of Dimensionality’.
What is the ‘Curse of Dimensionality’?
As dimensionality d increases, a fixed sample becomes progressively sparser. Maintaining the same grid resolution can require exponentially many cells or samples; whether distances concentrate still depends on the distribution, metric, and scaling.
The Curse of Dimensionality is an Enemy of Modeling and Analysis
When data dimensionality d is too high, a series of serious problems arise:
Problem Category
Specific Manifestation
Impact on Economic Research
Computational Efficiency
Grid search or exhaustive state counts can grow exponentially; many specific algorithms remain polynomial-time
Separate sample requirements and search-space growth from the complexity of the implemented algorithm.
Data Sparsity
A fixed number of samples becomes very sparse
Samples are not representative; hard to find significant relationships.
Model Overfitting
The model learns noise, not the true pattern
Perfect in-sample performance, but poor out-of-sample (predictive) power.
Multicollinearity
Many features are highly correlated
Difficult to identify the true impact of individual variables; unstable parameter estimates.
Representation learning (or dimensionality reduction) is the key to solving this problem.
The Goal of Representation Learning: Simplify with Minimal Information Loss
Our goal is to map a high-dimensional sample set \(X \in \mathbb{R}^{d \times N}\) to a low-dimensional space \(Z \in \mathbb{R}^{l \times N}\), where \(l \ll d\).
The new representation \(Z\) must preserve the most important ‘structure’ or ‘information’ from the original data \(X\). Different algorithms define ‘structure’ differently, leading to various reduction methods.
Before We Begin: Preprocessing is the Foundation of Success
Before applying any complex dimensionality reduction algorithm, we must clean the raw data. This is like laying the foundation before building a house.
Preprocessing Issue 1: Outliers
Extreme values can severely distort a model’s variance calculation (e.g., in PCA), pulling it towards the direction of the outlier.
Common Treatments: Winsorization, log transformation, or direct removal.
Preprocessing Issue 2: Missing Data
Most algorithms cannot handle missing values (NaN).
Common Strategies:
Deletion: If the missing proportion is small, delete the row or column.
Imputation: Fill with the mean, median, or more complex models (like K-Nearest Neighbors).
Preprocessing Issue 3: Inconsistent Scales
If ‘Market Cap’ (trillions) and ‘P/E Ratio’ (tens) are analyzed together, market cap will completely dominate the results.
Solution: Feature Scaling. The most common is Standardization, which transforms data to have a mean of 0 and a variance of 1.
Principal Component Analysis (PCA): Finding the Directions of Maximum Variance
PCA is the most classic and commonly used linear dimensionality reduction method.
Core Idea: Rotate the coordinate system so that the new axes (principal components) explain the maximum possible variance in the data.
Goal: Preserve the largest sample variance; this does not automatically preserve information most relevant to prediction, causal identification, or economic interpretation.
PCA Geometry: PC1 Follows the Maximum-Variance Direction
PCA seeks a projection direction (a unit vector \(w\)) that maximizes the variance of the projected data.
One-direction projection: Under the feature-by-sample convention \(X\in\mathbb{R}^{d\times N}\), \(\mathbf z=X^T\mathbf w\in\mathbb{R}^{N}\).
Projected variance:\(\operatorname{Var}(\mathbf z)=\mathbf w^T S\mathbf w\), where \(S=XX^T/N\in\mathbb{R}^{d\times d}\) is the covariance matrix of centered data.
The optimization problem is:
\[
\large{\max_{w} \quad w^T S w}
\]
\[
\large{\text{s.t.} \quad w^T w = 1}
\]
PCA’s Derivation: The Lagrangian
We use the method of Lagrange multipliers to solve this constrained optimization problem.
Formulate the Lagrangian: The goal is to maximize \(w^T S w\) subject to the constraint that \(w\) is a unit vector, i.e., \(w^T w = 1\).
\[ \large{L(w, \lambda) = w^T S w - \lambda(w^T w - 1)} \]
PCA’s Derivation: The First-Order Condition
Take the derivative with respect to \(w\) and set it to zero: This finds the critical points of the Lagrangian function.
Along \(\mathbf{v}_1\): \(z=(\sqrt5,0,-\sqrt5)\) and \(s_z^2=(5+0+5)/2=5\).
Along \(\mathbf{v}_2\): \(z=(0,0,0)\) and \(s_z^2=0\).
Check: \(\mathbf{S}\mathbf{v}_1=5\mathbf{v}_1\) and \(\mathbf{S}\mathbf{v}_2=0\mathbf{v}_2\).
Thus PC1 is \(\mathbf{v}_1\) and explains \(5/(5+0)=100\%\) of variance. It also retains more variation than the raw horizontal direction, whose projected variance is \(4\).
Linear Discriminant Analysis (LDA): Reduction for Classification
LDA is a supervised learning algorithm for dimensionality reduction.
Unlike PCA, which seeks maximum variance, LDA’s goal is to find a projection direction that maximizes the separation between different classes while minimizing the variance within each class.
LDA’s Objective: The Within-Class Scatter Matrix
Within-class Scatter Matrix (\(S_w\)): Measures the scatter of data points within each class.
We want to maximize this. It represents how far apart the classes are from each other.
LDA’s Objective Function: Maximizing the Ratio
For one direction \(w\), Fisher’s criterion is a generalized Rayleigh quotient. For a multidimensional projection, take leading generalized eigen-directions; equivalently, maximize projected between-class scatter under an \(S_w\)-orthonormality constraint:
If \(S_w\) is singular, use regularization or a generalized-eigenvalue/SVD solver rather than a literal inverse.
PCA: Maximum Variance Can Preserve Class Overlap
PCA: maximizes overall variance; here the horizontal PC1 still leaves substantial class overlap.
LDA: Supervision Rotates the Projection Toward Separation
LDA improves between-class relative to within-class scatter, helping separation without guaranteeing perfection.
Solving LDA: A Generalized Eigenvalue Problem
Maximizing the ratio \(J(W)\) can be transformed into solving a generalized eigenvalue problem:
\[
\large{S_b w = \lambda S_w w}
\]
Multiplying both sides by \(S_w^{-1}\), we get a more familiar form:
\[
\large{S_w^{-1} S_b w = \lambda w}
\]
Conclusion
The optimal projection directions \(w\) for LDA are the eigenvectors of the matrix \(S_w^{-1} S_b\).
Multidimensional Scaling (MDS): Reconstructing a ‘Map’ from Distances
Optional topic: after the PCA/LDA comparison, Core goes directly to the Yangtze Delta main case. MDS and the following nonlinear/sparse methods form a returnable extension branch.
MDS has a completely different starting point from PCA and LDA. It doesn’t work with the feature matrix \(X\) directly but starts from a known distance (or dissimilarity) matrix\(D\).
Core Idea: Find a set of points \(Z\) in a low-dimensional space such that the Euclidean distances between these points are as close as possible to the original distance matrix \(D\).
Use Case: When we don’t have the original features but can measure the dissimilarity between objects. For example, survey data on ‘brand similarity’ or the ‘edit distance’ between genetic sequences.
MDS Analogy: Reconstructing a City Map
Imagine you only know the straight-line flight distances between major cities, but you have no latitude or longitude information.
The goal of MDS is to find the optimal 2D coordinates for each city based on this distance matrix.
Part 2: Nonlinear Dimensionality Reduction (Manifold Learning)
The Limitation of Linear Methods: When Data Structure is Curved
Linear methods like PCA and LDA assume that the data lies on a flat hyperplane. But what if the data’s intrinsic structure is curved?
A linear method like PCA would incorrectly project distant points (like A and B) close together, failing to ‘unroll’ the data.
The Core Idea of Manifold Learning: Data Lives on a Low-Dimensional Manifold
Manifold Hypothesis: The high-dimensional data we observe is actually generated by a few latent variables (the intrinsic dimension), and these data points lie on a low-dimensional manifold embedded in the high-dimensional space.
Goal: To ‘unroll’ this manifold and find low-dimensional coordinates that reflect the true neighborhood relationships of the data.
Difference from Linear Methods: Manifold learning focuses on local structure, assuming that Euclidean distances are only reliable between nearby points.
Isomap: Measuring Distance Along the ‘Surface’
Isomap is a clever extension of MDS that replaces Euclidean distance with Geodesic Distance.
Steps:
Construct Neighborhood Graph: For each point, connect it only to its K-nearest neighbors.
Compute Shortest Paths: Use a graph algorithm (like Dijkstra’s) to compute the shortest path between all pairs of points, approximating the geodesic distance.
Apply MDS: Use the resulting shortest-path distance matrix as input to the classical MDS algorithm.
Locally Linear Embedding (LLE): Preserving Local Linear Relationships
LLE assumes that each data point can be linearly reconstructed by its neighbors, and this local geometric relationship should be preserved in the low-dimensional space.
The Heart of LLE: Preserve Reconstruction Weights, Not Distances
t-SNE: The Swiss Army Knife of Data Visualization
t-SNE (t-distributed Stochastic Neighbor Embedding) is a widely used exploratory visualization tool that embeds local neighborhoods into 2D or 3D; it does not establish a “most powerful” ranking or clustering correctness.
Core Idea (Probabilistic Matching):
In high-D space, convert Euclidean distances between points into conditional probabilities that represent the likelihood that point \(i\) would pick point \(j\) as its neighbor (using a Gaussian distribution).
In low-D space, define a similar conditional probability (using a heavier-tailed t-distribution).
Adjust the positions of points in the low-D space to make the two probability distributions as similar as possible (by minimizing the KL divergence).
Advantage: It can reveal local neighborhoods and possible group structure; confirm any apparent clusters with a validation measure chosen before viewing the result.
t-SNE Key Parameter: Perplexity
Perplexity:
This is the most important parameter. It can be loosely interpreted as the ‘effective number of neighbors’ each point considers.
Typical values are between 5 and 50.
A lower value focuses on local structure, while a higher value considers more of the global structure.
Important Cautions for Interpreting t-SNE plots
Do not over-interpret distances between clusters: The distance between two clusters on a t-SNE plot does not meaningfully represent how ‘far apart’ they are in the original space.
Do not over-interpret the size of clusters: The area of a cluster on the plot does not mean it contains more data points or has a larger variance.
t-SNE is an exploratory visualization tool, not a rigorous clustering analysis method.
Part 3: Advanced Topic: Sparse Representation
Sparse Representation: Building Signals with the Fewest ‘Blocks’
Previous methods aimed to ‘compress’ data, but sparse representation has a different starting point.
Core Idea: Any signal (e.g., an economic time series) can be represented as a linear combination of a few ‘atoms’ (basis vectors) from a ‘dictionary’ \(\Psi\).
\[ \large{x = \Psi s} \]
Here, \(s\) is a sparse vector, meaning most of its elements are zero.
Visual: Dictionary × Sparse Coefficients Builds a Signal
Sparse Representation: Economic Intuition
Economic Intuition
The complex dynamics of the market might be driven by a combination of only a few ‘latent economic states’ or ‘shocks’. Sparse representation aims to find these core drivers.
Compressed Sensing: Recovering the Full Signal from Fewer Samples
The sparsity assumption leads to a surprising conclusion: compressed sensing.
If \(x=\Psi s\) has a \(k\)-sparse coefficient vector and \(\Theta=\Phi\Psi\) satisfies a restricted-isometry or suitable incoherence condition, roughly \(l\gtrsim Ck\log(d/k)\) measurements can support stable recovery.
Exact recovery is possible only in the noiseless case under the theorem’s solver conditions; with noise, the guarantee is an error bound.
\[
\large{z = \Phi x = \Phi \Psi s = \Theta s}
\]
\(z\): a small number of observations (\(l \times 1\))
\(\Phi\): the measurement matrix (\(l \times d\), \(l \ll d\))
\(\Theta\): the sensing matrix
Compressed Sensing: Recovery Conditions and Failure Modes
Recovery conditions: sparsity, sensing geometry, sample size, and solver assumptions must hold together; sparsity alone is insufficient.
Failure cases: recovery may be biased or non-unique when sensing and dictionary atoms are highly coherent, \(l\) is too small, noise is large, or the signal is only approximately sparse.
Goal: Given \(z\) and \(\Theta\), solve for the sparse vector \(s\). This is the foundation of modern signal processing, MRI, and more.
Reconstruction Algorithm: Matching Pursuit
Finding the sparse vector \(s\) from \(z\) and \(\Theta\) is an NP-hard problem. Matching Pursuit is a greedy algorithm that approximates the solution iteratively.
Find Most Correlated Atom: Find the atom in the dictionary \(\Theta\) that is most correlated with the current residual \(r\) (has the largest inner product).
Update Solution: Add the contribution of this atom to the solution \(s\).
Update Residual: Subtract the contribution of this atom from the current residual \(r\).
Iterate: Repeat steps 2-4 until the residual is small enough or a maximum number of iterations is reached.
Economic Application: Screening Sparse Jumps and Outliers
With an identity dictionary, sparse first differences screen unusual jumps; a spike alone does not establish a structural break.
Signal (x): The first difference of an economic time series.
Dictionary (Ψ): An identity matrix.
Sparse Coefficients (s): With an identity dictionary, s is the differenced series; a large nonzero entry marks a candidate jump.
Ordinary innovations, outliers, seasonality, and volatility shifts can create the same spike.
A regime-change claim needs a change-point model that names the changing parameter, states noise/dependence assumptions, and validates false positives out of sample.
After the optional topic: after the MDS/manifold/sparse branch, continue to the final thought without replaying the main case or re-entering the branch.
Retrieve the Core objectives: diagnose scale/missingness, interpret PCA eigenvalues, distinguish unsupervised PCA from supervised LDA, and evaluate a representation on a held-out test period.
Retrieval prompt: If variable A’s standard deviation is 100 times variable B’s, what happens in covariance-based PCA?
Answer: A may dominate PC1 through units alone. Unless units carry the intended economics, standardize using training-period moments only.
Formative Check 1: A PCA Calculation
A standardized two-dimensional covariance matrix has eigenvalues 1.6 and 0.4. What variance share does one principal component explain?
Answer
\(1.6/(1.6+0.4)=0.8\), or 80%. Eigenvectors give directions; eigenvalues give variance along those directions.
Main Case: Yangtze Delta Stock PCA
Data used in this example:
Source: data/stock/stock_price_pre_adjusted.h5, key=data, four representative Yangtze River Delta A-shares.
Scope: 2018–2024 pre-adjusted close on common trading days only.
Boundary: the scaler and PCA use only 2018–2022 training observations.
Nearby method source:Jolliffe & Cadima (2016), PCA review; both loadings and explained variance below are estimated from training observations only.
Code
from pathlib import Path # Locate the downloaded data fileimport pandas as pd # Read and align local quotes in a tablefrom sklearn.preprocessing import StandardScaler # Unify stock yield scales during the training periodfrom sklearn.decomposition import PCA # Extract Common Direction of Fluctuation with Principal Component# Public download: https://assets.qiufei.site/data/stock/stock_price_pre_adjusted.h5# After downloading, change the next line to the file's actual location on your device.# Course-relative option: Path("data/stock/stock_price_pre_adjusted.h5")# Windows: Path(r"C:\qiufei\data\stock\stock_price_pre_adjusted.h5")# macOS: Path("/Users/your_name/data/stock/stock_price_pre_adjusted.h5")# Linux: Path("/home/your_name/data/stock/stock_price_pre_adjusted.h5")price_path = Path("/home/ubuntu/r2_data_mount/data/stock/stock_price_pre_adjusted.h5")company_ids = ['600276.XSHG', '600660.XSHG', '002648.XSHE', '002920.XSHE'] # Select representative listed company codes in the Yangtze River Deltaprice_parts = [pd.read_hdf(price_path, key='data', where=[f'order_book_id=="{company_id}"', 'date>=Timestamp("2018-01-01")', 'date<=Timestamp("2024-12-31")'], columns=['close']) for company_id in company_ids] # Selective Loading of Closing Prices by Company and Periodprice_panel = pd.concat(price_parts).reset_index().pivot(index='date', columns='order_book_id', values='close') # Construct Date Multiplied by Company's Price Panelreturn_panel = price_panel.pct_change(fill_method=None).dropna() # Calculate the common trading day yield and delete the missing rowstraining_returns = return_panel.loc[:'2022-12-31'] # Fixed 2018-2022 as Training Periodreturn_scaler = StandardScaler().fit(training_returns) # Estimate means and standard deviations from the training period onlyscaled_training_returns = return_scaler.transform(training_returns) # Convert the training yield to a comparable scalereturn_pca = PCA(n_components=2).fit(scaled_training_returns) # Extracts the first two common fluctuating principal componentspca_loadings = pd.DataFrame(return_pca.components_.T, index=training_returns.columns, columns=['PC1', 'PC2']) # Map the load back to the real stock codepd.concat([pd.Series(return_pca.explained_variance_ratio_, index=['PC1', 'PC2'], name='variance_ratio'), pca_loadings.stack().rename('loading')], axis=0) # Output variance evidence and loads for interpretation
Two clusters are far apart on a t-SNE map. May we conclude they are equally far apart in the original space?
Answer
No. t-SNE prioritizes local neighborhoods; global distance, area, and direction are generally not quantitative evidence. Vary seeds/perplexity and validate in the original space.
Step-by-Step Exercise: Why Standardize?
Task: Fit PCA to raw and standardized returns over the same training period; compare PC1 variance share and loading rank.
Complete solution:
Fit raw_pca = PCA(2).fit(training_returns) on the same dates.
Compare explained_variance_ratio_ and rank absolute values of both components_[0] vectors.
Interpret a changed rank as scale/volatility sensitivity—not causal importance.
Code
raw_pca = PCA(n_components=2).fit(training_returns) # Fit Non-standardized PCA on Same Training Dateraw_rank = training_returns.columns[abs(raw_pca.components_[0]).argsort()[::-1]].tolist() # Raw return variables by PC1 Absolute Loadscaled_rank = training_returns.columns[abs(return_pca.components_[0]).argsort()[::-1]].tolist() # Standardized Variables by PC1 Absolute Loadpd.DataFrame({'input version': ['raw returns', 'standardized returns'], 'pc1_variance_ratio': [raw_pca.explained_variance_ratio_[0], return_pca.explained_variance_ratio_[0]], 'absolute_loading_rank': [raw_rank, scaled_rank]}) # Compare the two PCA results side by side
Table 1
input version
pc1_variance_ratio
absolute_loading_rank
0
raw returns
0.500617
[002920.XSHE, 002648.XSHE, 600660.XSHG, 600276...
1
standardized returns
0.471032
[600660.XSHG, 002920.XSHE, 002648.XSHE, 600276...
Apply It to a New Case
From local financial_statement.h5/financial_data, select four Yangtze Delta firms, at least 12 quarters, and five financial ratios; compare two-dimensional PCA and LDA.
The income-statement fields in this file are cumulative year-to-date, so the target is whether cumulative net profit disclosed for the exact next calendar quarter is positive.
Complete-answer reminder
report fields and units, respect when information became available, fit preprocessing on training data only, interpret PCA variance and loadings, report the LDA target and out-of-sample result, and discuss limitations.
Features must use the version disclosed by the decision time, and later restatements or full-sample moments must not enter earlier decisions.
Complete Solution for the New Case: Financial-Ratio Panel
Table 2
Code
from pathlib import Path # Locate the downloaded data fileimport pandas as pd # Read and Organize Local Quarterly Financial Statementsfrom sklearn.preprocessing import StandardScaler # Estimate Unified Ratio Scale by Training Period Moment Onlyfrom sklearn.decomposition import PCA # Extract Unsupervised 2D Financial Representationfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis # Estimating supervised linear discriminant directions# Public download: https://assets.qiufei.site/data/stock/financial_statement.h5# After downloading, change the next line to the file's actual location on your device.# Course-relative option: Path("data/stock/financial_statement.h5")# Windows: Path(r"C:\qiufei\data\stock\financial_statement.h5")# macOS: Path("/Users/your_name/data/stock/financial_statement.h5")# Linux: Path("/home/your_name/data/stock/financial_statement.h5")statement_path = Path("/home/ubuntu/r2_data_mount/data/stock/financial_statement.h5")transfer_ids = ['600418.XSHG', '600460.XSHG', '600537.XSHG', '600596.XSHG'] # Select four Yangtze River Delta companiesstatement_columns = ['order_book_id', 'quarter', 'info_date', 'operating_revenue', 'net_profit', 'total_assets', 'total_liabilities', 'equity_parent_company'] # Define the original fieldstatement_parts = [pd.read_hdf(statement_path, key='financial_data', where=f'order_book_id=="{company_id}"', columns=statement_columns) for company_id in transfer_ids] # Selective Loading of Required Columns by Companystatement_frame = pd.concat(statement_parts, ignore_index=True) # Merging Four Companies for Quarterly Panel
Table 3
Code
statement_frame['info_date'] = pd.to_datetime(statement_frame['info_date']) # Unifying Disclosure Date Typesstatement_frame['quarter_period'] = pd.PeriodIndex(statement_frame['quarter'], freq='Q') # Convert Quarterly Label to Sortable Periodstatement_frame = statement_frame[statement_frame['quarter_period'] <= pd.Period('2024Q4')]statement_frame = statement_frame.sort_values(['order_book_id', 'quarter_period', 'info_date']).drop_duplicates(['order_book_id', 'quarter_period'], keep='first') # Keep the first disclosed version of each quarter and exclude later restatementsratio_definitions = {'profit_margin': ('net_profit', 'operating_revenue'), 'roa': ('net_profit', 'total_assets'), 'debt_ratio': ('total_liabilities', 'total_assets'), 'asset_turnover': ('operating_revenue', 'total_assets'), 'equity_turnover': ('operating_revenue', 'equity_parent_company')} # Define Five Dimensionless Ratiosfor ratio_name, (numerator_name, denominator_name) in ratio_definitions.items(): # Construct a ratio under the same accounting convention statement_frame[ratio_name] = statement_frame[numerator_name] / statement_frame[denominator_name] # Calculate ratios with a report original valuestatement_frame = statement_frame.sort_values(['order_book_id', 'quarter_period']) # Inside the Company Maintain Quarterly Orderstatement_frame['target_quarter'] = statement_frame.groupby('order_book_id')['quarter_period'].shift(-1) # Retain the next record's quarter so exact calendar adjacency can be verifiedstatement_frame['next_profit'] = statement_frame.groupby('order_book_id')['net_profit'].shift(-1) # keep next quarter net profit consecutive valuestatement_frame['target_available_at'] = statement_frame.groupby('order_book_id')['info_date'].shift(-1) # Record when the next-quarter outcome first becomes verifiablestatement_frame = statement_frame.replace([float('inf'), float('-inf')], pd.NA).dropna() # Remove missing ratios, unknown outcomes, and non-finite recordsstatement_frame = statement_frame[(statement_frame['target_quarter'] == statement_frame['quarter_period'] +1) & (statement_frame['info_date'] < statement_frame['target_available_at'])] # Reject skipped quarters and tasks whose outcomes are not disclosed laterstatement_frame['next_profit_positive'] = (statement_frame['next_profit'] >0).astype(int) # Construct symbol labels only for observed profitsassert (statement_frame['target_quarter'] == statement_frame['quarter_period'] +1).all() # Verify that every target is the exact next calendar quarterassert (statement_frame['info_date'] < statement_frame['target_available_at']).all() # Verify that every feature disclosure precedes its outcome disclosure
All five ratios are unit-free;
Raw amount fields: retain the HDF data dictionary’s RMB unit.
Accounting convention:operating_revenue and net_profit are cumulative year-to-date values.
Target: the sign of cumulative net profit disclosed for the exact next calendar quarter—not single-quarter profit.
Complete Solution for the New Case: PCA and LDA Evidence
Code
from sklearn.metrics import balanced_accuracy_score, confusion_matrix # Evaluate Classification Performance of fixed Test Periodratio_names =list(ratio_definitions) # Fixed Five Dimension Model Input Sequencestatement_train = statement_frame[statement_frame['target_available_at'] <= pd.Timestamp('2022-12-31')] # Require both features and outcomes to be known by the training cutoffstatement_test = statement_frame[(statement_frame['info_date'] >= pd.Timestamp('2023-01-01')) & (statement_frame['target_available_at'] <= pd.Timestamp('2024-12-31'))]assert statement_train['target_available_at'].max() < statement_test['info_date'].min() # Verify that training outcomes precede the first test feature disclosureratio_scaler = StandardScaler().fit(statement_train[ratio_names]) # Use only the training period to estimate the scalescaled_statement_train = ratio_scaler.transform(statement_train[ratio_names]) # Transform Training Period Ratioscaled_statement_test = ratio_scaler.transform(statement_test[ratio_names]) # Transform test-period ratios with the training-period scalerstatement_pca = PCA(n_components=2).fit(scaled_statement_train) # Only extracting two principal components during the training periodstatement_test_scores = statement_pca.transform(scaled_statement_test) # Generate 2D Coordinates for Test Periodstatement_lda = LinearDiscriminantAnalysis().fit(scaled_statement_train, statement_train['next_profit_positive']) # Learning the direction of supervision only during the training periodstatement_lda_prediction = statement_lda.predict(scaled_statement_test) # Forecast Profit Symbol for fixed Test Periodpd.Series({'train_n': len(statement_train), 'test_n': len(statement_test), 'pc1_share': statement_pca.explained_variance_ratio_[0], 'pc2_share': statement_pca.explained_variance_ratio_[1], 'lda_balanced_accuracy': balanced_accuracy_score(statement_test['next_profit_positive'], statement_lda_prediction), 'confusion_matrix': confusion_matrix(statement_test['next_profit_positive'], statement_lda_prediction).tolist(), 'first_test_score': statement_test_scores[0].round(3).tolist()}) # Output verifiable comparison of real key results with two-dimensional coordinate samples
PC1/PC2 explain 0.4874/0.3368; LDA balanced accuracy is 0.5000 and the confusion matrix is \([[0,5],[0,13]]\).
Every test quarter is classified as profitable, so all loss quarters are missed and this is not robust predictive evidence.
Formative Check 3: Compressed-Sensing Conditions
“The signal is sparse, so any three measurements must recover a 100-dimensional signal.” True or false?
Answer: False. Measurements must scale with \(k\log(d/k)\), the sensing geometry needs RIP/incoherence, and noiseless exact recovery must be separated from noisy stable recovery.
Sources and Further Reading
Jolliffe & Cadima (2016), “Principal component analysis: a review and recent developments.”
van der Maaten & Hinton (2008), “Visualizing Data using t-SNE.”
Candès & Tao (2005/2006), original compressed-sensing and RIP papers.
Data: local data/stock/financial_statement.h5, HDF key=financial_data, with the fields and cumulative convention stated in the transfer task; the PCA worked example separately uses the local pre-adjusted A-share data.
Requires class labels, has assumptions about class distribution
Extension Summary: Distance, Manifold, and Sparse Methods
Method
Preserves
Key boundary
MDS
Pairwise distances
Depends on the metric; computationally expensive
Isomap / LLE
Geodesics / local reconstruction
Sensitive to neighborhoods and noise
t-SNE
Local neighborhood probabilities
Exploratory only; global distances are not quantitative evidence
Sparse / compressed sensing
A few atoms
Requires sensing geometry, sample size, and solver conditions
Final Thought: Reduction is a Means to an End, Not the Goal Itself
In this chapter, we have explored a range of representation learning (dimensionality reduction) methods, from linear to nonlinear.
They are powerful tools for exploratory data analysis, helping us discover hidden structures like factors, clusters, and low-dimensional manifolds in seemingly chaotic high-dimensional data.
They are also a crucial preprocessing step for building predictive models, effectively improving model stability and generalization.
The key is to always combine your domain knowledge (economics, finance) to interpret the results of dimensionality reduction, giving real-world meaning to these abstract dimensions and structures.