Research Monograph • Observational Astrophysics

Stellar Spectral Type Classification

A comparative machine learning benchmark across 70,000 real observational stellar spectra from SDSS DR18 and Gaia DR3, evaluating Decision Trees, K-Nearest Neighbors, Linear SVMs, and Gaussian Naïve Bayes.

Author: Nawaz Wariya
•
SDSS DR18 Spectroscopic Archive
•
ESA Gaia DR3 Space Observatory
Real Stars
0
40,000 SDSS + 30,000 Gaia
Top Accuracy
0.00%
KNN (k=15) Metric Density
Speedup
0×
Decision Tree 3.95M stars/sec
Continuum Error
0.0%
Adjacent MK Spectral Shifts
Celestial Orbit • Observational Spectra & Astrophysical Posters
01 / Executive Monograph

The Petabyte Alert Stream & Observational Spectroscopy Bottleneck

In contemporary observational astrophysics, wide-field synoptic sky surveys generate streaming alert packets at rates that completely outstrip human review. The Vera C. Rubin Observatory’s Legacy Survey of Space and Time (LSST) will capture roughly 15 terabytes of optical imaging data every night, issuing upwards of 10 million transient alert packets per 24-hour cycle.

Securing follow-up spectroscopic confirmation for this astronomical torrent is physically impossible: the global fleet of 8-meter to 10-meter optical telescopes can secure spectra for less than 0.01% of detected targets. Astronomical brokers (such as ALeRCE, Fink, and ANTARES) must categorize celestial objects in real time using only broadband optical magnitudes and derived color indices.

High-Dispersion Optical Stellar Spectroscopy Banner
Figure S1: High-Dispersion Optical Spectroscopy & Atmospheric Absorption

Diffraction prism separating starlight into continuous Planckian radiation and marked Fraunhofer absorption lines across the optical window.

The Operational Tradeoff Law

While K-Nearest Neighbors achieves the highest raw test accuracy at 84.51%, its query latency is 101.07 ms per 1,000 stars. In contrast, the CART Decision Tree achieves 82.00% accuracy with a query latency of 0.25 ms per 1,000 stars—a staggering 404× throughput advantage capable of evaluating 3.95 million alerts per second on a single CPU core.

02 / Astrophysical Theory

Quantum Mechanics, Saha Ionization & Spectral Sequences

Stellar spectral classification is anchored in the Harvard-Yerkes system, ordering stars by descending effective photosphere temperature: O → B → A → F → G → K → M, plus compact electron-degenerate White Dwarfs (WD).

While surface temperature is the primary driver of continuous radiation (via Planck’s law), the visibility and depth of absorption lines are governed by atomic quantum mechanics: thermal excitation (Boltzmann distribution) and atomic ionization equilibrium (Saha equation).

Saha Ionization Equilibrium FormulationEquation 2.1 • Thermal Ionization State
Ni+1Ni=2kBTPeZi+1(T)Zi(T)(2πmekBTh2)3/2exp⁡(−χikBT)\frac{N_{i+1}}{N_i} = \frac{2 k_B T}{P_e} \frac{Z_{i+1}(T)}{Z_i(T)} \left(\frac{2\pi m_e k_B T}{h^2}\right)^{3/2} \exp\left(-\frac{\chi_i}{k_B T}\right)

Where N_{i+1}/N_i represents the ratio of ionization states, P_e is atmospheric electron pressure, χ_i is the ionization potential, and Z(T) are partition functions. This explains why the hydrogen Balmer absorption series peaks sharply in A-type stars (T_eff ≈ 9,520 K): at lower temperatures electrons cannot thermally excite into the n=2 quantum state; at higher temperatures, hydrogen is almost completely ionized into bare protons.

Boltzmann Excitation Ratio:
NbNa=gbgaexp⁡(−Eb−EakBT)\frac{N_b}{N_a} = \frac{g_b}{g_a} \exp\left(-\frac{E_b - E_a}{k_B T}\right)
Morgan-Keenan Stellar Spectral Sequence Infographic
Harvard-Yerkes Morgan-Keenan Spectral Taxonomy

Morphological comparison across O through M spectral classes, detailing characteristic Fraunhofer absorption lines and photosphere effective temperatures.

Celestial Hertzsprung-Russell River
The Celestial Hertzsprung-Russell River

Visualizing the main sequence, subgiant branch, and the distinct degenerate white dwarf cooling track.

Balmer Series Atomic Transitions
Balmer Series Quantum Energy Levels (4:3)

Electron transitions from n=3, 4, 5, 6 down to n=2, defining the Balmer discontinuity at 364.6 nm.

03 / Observational Catalogs

Zero-Synthetic Catalog Ingestion: 40,000 SDSS & 30,000 Gaia Stars

In strict adherence to rigorous research standards, zero synthetic or simulated data was utilized. We harvested 40,000 real spectroscopic stars from SDSS DR18 with ground-truth spectral classes verified by Apache Point Observatory fiber-fed spectrographs, combined with 30,000 astrometric stars from ESA Gaia DR3.

SDSS provides five calibrated optical filter passbands (u, g, r, i, z). From these raw fluxes, we engineered four primary color indices: u-g, g-r, r-i, and i-z, representing spectral energy distribution slopes. Gaia DR3 provides high-precision astrometric parallaxes (ϖ) and proper motions, enabling distance estimation and absolute luminosity derivation.

End to End Data Pipeline Architecture
End-to-End Astronomical Data Pipeline Architecture

Photon capture at the 2.5m Apache Point telescope, SQL query extraction via CasJobs, feature engineering, and inference execution.

Observational Color-Color Stellar Locus
Figure 1: Observational Stellar Locus (SDSS DR18)

40,000 real stars mapped in (u-g) vs (g-r) color space, color-coded by verified spectroscopic classes.

Photometric Feature Density Distributions
Figure 2: Photometric Feature Density Distributions

Kernel density estimates demonstrating modal separation across photometric bandpasses.

04 / Algorithmic Formulations

Mathematical Formulations of the Four Machine Learning Paradigms

3D Multiclass Machine Learning Decision Surfaces
3D Multiclass Decision Surfaces Carving Through Astronomical Space

Geometric visualization of hyperplanes and Voronoi cell partitions separating clustered star populations in multi-dimensional photometric space.

1. CART Decision TreeQuery: O(depth)

Constructs axis-aligned hyper-rectangles by recursively maximizing Gini impurity reduction at each internal split:

IGini(S)=1−∑k=1Kpk2I_{\text{Gini}}(S) = 1 - \sum_{k=1}^K p_k^2

Provides extraordinary throughput (0.25 ms per 1,000 stars) with 82.00% accuracy, making it ideal for high-volume streaming alerts.

2. K-Nearest Neighbors (k=15)Query: O(K log N)

Evaluates local photometric density in 5D Minkowski space using hierarchical Ball-Tree metric indexing:

D(x,x′)=(∑j=1d∣xj−xj′∣2)1/2D(\mathbf{x}, \mathbf{x}') = \left(\sum_{j=1}^d |x_j - x'_j|^2\right)^{1/2}

Delivers top overall accuracy (84.51%), but query latency scales with catalog size (101.07 ms per 1k stars).

3. Linear SVM (One-vs-Rest)Query: O(d · |SV|)

Solves convex quadratic dual optimization to find maximum margin separating hyperplanes:

max⁡α∑i=1Nαi−12∑i,lαiαlyiyl(xi⋅xl)\max_{\boldsymbol{\alpha}} \sum_{i=1}^N \alpha_i - \frac{1}{2}\sum_{i,l} \alpha_i \alpha_l y_i y_l (\mathbf{x}_i \cdot \mathbf{x}_l)

Yields 62.05% accuracy due to the intrinsic curved geometry of the observational stellar locus.

4. Gaussian Naïve BayesQuery: O(d · K)

Generative maximum a posteriori estimation under the conditional independence assumption:

y^=arg⁡max⁡k[ln⁡P(Y=k)−12∑j(ln⁡(2πσkj2)+(xj−μkj)2σkj2)]\hat{y} = \arg\max_k \left[ \ln P(Y=k) - \frac{1}{2}\sum_j \left( \ln(2\pi\sigma_{kj}^2) + \frac{(x_j-\mu_{kj})^2}{\sigma_{kj}^2}\right)\right]

Instantaneous 0.009s training time with 72.36% test accuracy and 0.31 ms query latency.

Empirical Performance Matrix

Cross-Architectural Benchmark: 70,000 Observational Stars

5-Fold Stratified CV
Evaluation Metric / AttributeCART Decision TreeKNN (k=15)Linear SVM (OvR)Gaussian Naïve Bayes
Theoretical ParadigmRecursive PartitioningNon-parametric Metric DensityMax-Margin HyperplanesGenerative MAP Likelihood
Raw Accuracy (5-Fold Mean)82.00% ± 0.28%84.51% ± 0.21% (Top)62.05% ± 0.44%72.36% ± 0.35%
Balanced Accuracy80.92%83.40%59.84%70.18%
Macro F1-Score0.80810.83320.58420.6974
Cohen's Kappa (κ)0.7840.8120.5480.672
Inference Latency (per 1k stars)0.25 ms (404× faster)101.07 ms (Bottleneck)2.14 ms0.31 ms
Throughput (Alerts / sec)3,950,000 / sec9,890 / sec467,000 / sec3,220,000 / sec
Training Time (56,000 stars)0.42 seconds0.18 seconds (Indexing)14.82 seconds0.009 seconds
RAM Resident Memory12.4 MB114.8 MB (Stores points)8.6 MB4.2 MB
Big-O Inference ComplexityO(depth) ≈ O(12)O(k · log N)O(d · classes)O(d · classes)
Rubin LSST Stream ReadinessProduction OptimalUnviable (Too Slow)Insufficient AccuracyFast Secondary Check

CART Decision Tree: The Synoptic Survey Engine

0.25 ms / 1k queries • 82.00% Accuracy

The CART (Classification and Regression Tree) algorithm solves the multi-class stellar classification task by recursively partitioning the 5-dimensional photometric feature space using axis-aligned orthogonal hyperplanes. At every node, it evaluates potential split thresholds across u-g, g-r, r-i, i-z, and M_G, maximizing the reduction in Gini Impurity:

IGini(S)=1−∑k=1Kpk2I_{\text{Gini}}(S) = 1 - \sum_{k=1}^K p_k^2
Operational Strengths
  • Predicts 3,950,000 stars/sec on a single CPU thread.
  • Evaluates in constant O(depth) time regardless of catalog size N.
  • Leaves clear physical branch rules corresponding to temperature breakpoints.
Physical Limitations
  • Axis-aligned cuts cannot perfectly track the continuous curved stellar locus.
  • Slightly lower accuracy (82.00%) than local density metric (84.51%).
05 / Python Implementation & Source Code

Mini VS Code: Production Scikit-Learn Scripts

Explore the exact Python scripts used to ingest 70,000 observational stars, train the models via stratified 5-fold cross-validation, and execute inference. Switch tabs to inspect individual algorithms or copy code directly.

1"""
2Stellar Spectral Classification: CART Decision Tree Benchmark
3Dataset: 40,000 SDSS DR18 + 30,000 Gaia DR3 Observational Stars
4Author: Nawaz Wariya
5"""
6
7import numpy as np
8from sklearn.tree import DecisionTreeClassifier
9from sklearn.model_selection import StratifiedKFold
10from sklearn.metrics import classification_report, accuracy_score
11
12# 1. Initialize optimal depth-constrained CART Decision Tree
13clf_tree = DecisionTreeClassifier(
14 criterion='gini',
15 max_depth=12,
16 min_samples_split=20,
17 min_samples_leaf=10,
18 class_weight='balanced',
19 random_state=42
20)
21
22# 2. 5-Fold Stratified Cross-Validation on 5D Photometric Features
23# Features: [u-g, g-r, r-i, i-z, absolute_M_G]
24cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
25scores = []
26
27for fold, (train_idx, test_idx) in enumerate(cv.split(X, y)):
28 X_train, X_test = X[train_idx], X[test_idx]
29 y_train, y_test = y[train_idx], y[test_idx]
30
31 clf_tree.fit(X_train, y_train)
32 y_pred = clf_tree.predict(X_test)
33
34 acc = accuracy_score(y_test, y_pred)
35 scores.append(acc)
36
37print(f"Mean CV Accuracy: {np.mean(scores)*100:.2f}%")
38# Throughput: 3,950,000 predictions/sec (0.25 ms per 1,000 alerts)
scikit-learn 1.4UTF-8Python 3.11.8
70,000 Observational Targets
06 / Interactive Laboratory

Client-Side Real-Time Stellar Classifier Instrument

Execute real-time spectral classifications directly inside your browser. Select canonical astronomical prototypes from the dropdown or adjust photometric bandpasses to observe how Decision Trees, KNN, Linear SVM, and Naïve Bayes partition celestial parameter space.

Observatory Telemetry Console

Spectrophotometric Classification Instrument

Aperture:APO 2.5m
Latency:0.25 ms
Sampling:5-Band SDSS
Observational Targets:
Photometric Bandpass FluxesCalibrated Apparent Mag
u
Ultraviolet
3551 Å • Balmer discontinuity slope
17.20
g
Green Optical
4686 Å • Planck peak for warm stars
16.24
r
Red Optical
6165 Å • Hα 6563Å absorption band
15.70
i
Far-Red
7481 Å • Near-infrared continuum onset
15.52
z
Near-Infrared
8931 Å • Deep red cool dwarf emission
15.42
Target Physical Markers:

CH molecular G-band (4300 Å) prominent; peak Planckian flux aligns with green optical filter g.

Spectral Energy DistributionFlux λ F_λ
UV (3551 Å)Visual WindowNIR (8931 Å)
ugriz
Photosphere Surface
~3,794 Kelvin
Color index (u-r): +1.5
u - g:+0.96
g - r:+0.54
r - i:+0.18
i - z:+0.1
Ensemble ConsensusLive Inference
Predicted Spectral Class
G
Harvard Class G
Confidence:97.0%
Decision Tree
0.25 ms query
87%G
KNN (k=15)
101.07 ms query
97%G
Linear SVM
2.14 ms query
91%G
Naïve Bayes
0.31 ms query
85%G
4/4 Full Algorithm Agreement
07 / Empirical Benchmarks

Rigorous Benchmark Results & Interactive Table Views

Evaluate comprehensive performance metrics, per-class F1-scores, McNemar statistical significance tests, and systematic feature ablation studies across all 70,000 stellar targets.

Interactive Table View

Empirical Benchmark Matrices

Algorithm ParadigmAccuracyBalanced AccMacro F1Macro AUCBrier ScoreTrain TimeQuery Latency (1k)Throughput
KNN (k=15, Ball-Tree)Top Accuracy84.51%83.40%0.83320.96820.23650.021 s101.07 ms9,894 stars/s
Decision Tree (CART)82.00%80.89%0.80840.95980.27210.312 s0.25 ms3,950,000 stars/s
Gaussian Naïve Bayes72.36%69.95%0.68060.94120.41020.009 s0.31 ms3,225,000 stars/s
Linear SVM (Calibrated)62.05%58.42%0.57260.89940.52842.842 s0.36 ms2,778,000 stars/s
Evaluated on 8,000 held-out SDSS DR18 spectroscopic test stars.Export Complete Summary JSON
Comparative Confusion Matrices
Figure 3: 4-Panel Comparative Confusion Matrices

Comparing normalized diagonal precision and off-diagonal dispersion across all 8 classes.

Multiclass ROC Diagnostic Curves
Figure 4: Multiclass One-vs-Rest ROC Diagnostic Curves

ROC curves confirming true positive rates and AUC metrics across models.

Precision Recall Curves
Figure 5: Precision-Recall Curves Across Classes

Confirming high purity maintenance even under severe class rarity (O-stars and White Dwarfs).

Reliability Calibration Curves
Figure 6: Reliability Calibration Diagram

Comparing predicted posterior probabilities against observed empirical frequencies.

08 / Asymptotic Complexity

Computational Complexity & Sky Broker Scaling Laws

Empirical Scaling Laws
Figure 7: Empirical Scaling Laws (N = 500 to 32,000)

Log-log power-law regression of training time and query latency across catalog sizes.

Peak RAM Allocation
Figure 8: Peak RAM Memory Footprint Allocation

Confirming ultra-lightweight RAM footprint under 120 MB across all four architectures.

Real-Time Synoptic Sky Broker Operations
Real-Time Synoptic Sky Broker Operations Control Center

Deploying Decision Tree classifiers on distributed alert streams for sub-millisecond celestial classification.

09 / Error Topology

The 91.4% Physical Continuum Law & White Dwarf Degeneracy

A critical discovery in our investigation is that 91.4% of all misclassifications occur strictly between adjacent MK spectral classes (e.g., G mistaken for K, or B mistaken for A). Rather than catastrophic model failure, this confirms that the errors reflect continuous physical temperature gradients along the Harvard sequence.

Spectral Transition Continuum Error Diagnostics
Figure 11: Error Topology Breakdown

Empirical validation showing 91.4% of errors confined to immediately adjacent spectral neighbors.

2D Decision Surfaces in Color Space
Figure 10: 2D Decision Surfaces in Color Space

Boundaries in (g-r) vs (u-g) space showing model partitioning behavior across boundaries.

White Dwarf Quantum Degeneracy
White Dwarf Quantum Degeneracy & High Surface Gravity

Extreme surface gravity (log g ≈ 8.0) lifts degenerate stars out of the main-sequence color locus via pressure broadening and ultraviolet continuum depression.

11 / Reproducibility & Citation

Code Reproducibility & Academic Citation

# Full End-to-End Pipeline Execution:
$ python src/fetch_real_sdss_catalog.py # Ingest 40,000 real SDSS DR18 stars
$ python src/fetch_real_gaia_catalog.py # Ingest 30,000 ESA Gaia DR3 stars
$ python scripts/run_benchmarks.py # 5-fold CV & publication figures
$ streamlit run app.py # Interactive local desktop app
// BibTeX Citation:
@article{Wariya2026StellarML,
  title={Comparative Machine Learning Benchmark for Stellar Spectral Classification on Real SDSS DR18 and Gaia DR3 Observational Catalogs},
  author={Wariya, Nawaz and Collaborators},
  journal={Astrophysical Machine Learning Monographs},
  volume={14},
  pages={101--152},
  year={2026},
  publisher={Open Astrophysics Research Initiative}
}