Manuscript Offprint
arXiv:2610.38816UnEZ: A Fully Unsupervised Self-Templating Neural Network for Redshift and Line Strength Estimation
ABSTRACT
As spectroscopic surveys grow, estimating galaxy properties such as metallicity, star formation rate, and redshift becomes computationally cumbersome. Methods of estimating such properties rely on template spectra or curated redshift catalogs, which fail to represent the diversity of objects seen in large-scale surveys. We present UnEZ, a fully unsupervised, physics-informed machine learning model that can predict spectroscopic redshifts and line strengths with no prior redshift or line strength labels. An encoder predicts emission and absorption line amplitudes/widths, and a fixed deterministic decoder constructs a unique template, estimated redshift, redshift confidence curve, and spectral model. UnEZ was tested on the Sloan Digital Sky Survey (SDSS) Data Release 18 due to its large dataset and thoroughly vetted redshift catalog which serves as an independent benchmark. Despite the lack of templates, line strength labels, or redshift labels, UnEZ's performance competes with modern redshift estimation algorithms. At SNR > 10, UnEZ achieves an outlier fraction of 0.459% and a normalized median absolute deviation (NMAD) of . At SNR > 3, UnEZ achieves an outlier fraction of 3.89% and an NMAD of . Furthermore, we demonstrate how UnEZ's line strength and redshift predictions can be utilized for various purposes such as constructing template spectra required in traditional redshift estimation algorithms. UnEZ illustrates how a fully unsupervised neural network can allow redshift, among other galaxy properties, to emerge naturally from the spectra themselves, providing a template-free, label-free approach that scales to the demands of future surveys.
Key words: software: machine learning – techniques: spectroscopic – galaxies: distances and redshifts – surveys
1 INTRODUCTION
Recent efforts in astronomical surveying have yielded vast datasets ranging across many redshift regimes and areas of the sky. Such large datasets enable high-precision statistical modeling of the universe.
Redshift carries information that is vital to such cosmological models. Measures such as scale factor or lookback time (Hogg 2000) can be calculated from redshift for example. Other important galaxy characteristics such as rotation curves (Sofue & Rubin 2001) can also be isolated given the redshift of an object. Large-scale surveys allow statistical analyses across millions of spectra, such as measurements of the galaxy clustering power spectrum (Tegmark et al. 2004), making them valuable for verifying cosmological models (Abdul Karim et al. 2025).
Photometry has also been used to estimate redshifts. Traditional algorithms fit template spectral energy distributions (SEDs) to the broad features traced out between photometric filters (Benítez 2000). Photometric redshift can suffer from degeneracies resulting in catastrophic redshift prediction failures (Massarotti et al. 2001) and have larger uncertainties due to the lack of highly resolved emission/absorption lines. While photometric redshifts are cheap in both observational resources and compute needs, they lack the precision of spectroscopic redshifts (Newman & Gruen 2022).
Spectroscopy, while being more resource-expensive than photometry, is particularly important for high precision redshift measurements. Modern fiber-fed spectrographs can collect thousands of spectra in a single pointing allowing for large surveys (Smee et al. 2013). Redshift surveys were not always conducted on the scale they are today. The first surveys were composed of only a few dozen redshifts due to the hours or sometimes nights required to collect a spectrum on photographic plates.
Endeavors such as mapping out galaxy clusters require a large number of precise redshift measurements to understand how distant they are. Later surveys such as the Center for Astrophysics (CfA) survey collected several thousand spectra automatically. Such surveys led to the discovery of large-scale structures in the universe (Huchra et al. 1988). The 1990s and early 2000s brought even larger surveys such as the 2dF Galaxy Redshift Survey which produced almost 250,000 spectra (Colless et al. 2003), with later surveys such as the Sloan Digital Sky Survey (SDSS) producing millions of spectra (Almeida et al. 2023). Future and current endeavors such as the Dark Energy Spectroscopic Instrument (DESI) survey will bring tens of millions more spectra (DESI Collaboration et al. 2026), creating a unprecedented amount of data available for analysis.
Many methods of estimating the redshift of spectra have been adopted over the years. The first method required manually identifying spectral lines and comparing their distances to one another with a reference line list (Humason et al. 1956). This method was very
★ E-mail: aabd@swin.edu.au
© 2026 The Authors
Abd et al.
labor-intensive although it did come with the benefit of being human-verified for every data point. Modern methods of estimating redshift generally utilize a set of templates and a or cross-correlation algorithm. The algorithm fits templates to a spectrum at trial redshifts to minimize (Bolton et al. 2012). The cross-correlation algorithm, on the other hand, computes the correlation between templates and spectra in log-wavelength space to find the redshift corresponding with the highest correlation (Tonry & Davis 1979). AUTOZ, an algorithm for estimating redshift, removes the continuum from spectra, removes potential skyline or cosmic ray contamination, and cross-correlates the processed spectrum with a set of templates to estimate redshift (Baldry et al. 2014). Further endeavors such as MARZ have refined that process with a larger template library and a user interface (Hinton et al. 2016).
As astronomical datasets grow in area and depth, estimating redshifts quickly becomes cumbersome. The SDSS dataset alone contains millions of spectra, and future surveys promise tens of millions more. Machine learning models are a good candidate for analyzing such datasets due to their capacity to learn complex non-linear relationships in the data (Fluke & Jacobs 2019). The use of neural networks in astronomy dates as far back as the 1990s for tasks such as correcting atmospheric aberrations in adaptive optics and object classification (Miller 1993). As neural networks became larger and more sophisticated, their accuracy and precision made them a much more enticing candidate for tasks such as morphological classification (Dieleman et al. 2015), photometric redshift estimation (Collister & Lahav 2004), and stellar classification (Liu et al. 2019). Neural networks can be classified into two generic categories, supervised and unsupervised, which come with different benefits and shortcomings.
Supervised machine learning models are very well studied. Models have been trained to predict redshift using redshift labels from traditional fitting algorithms (Zhong et al. 2024). SpecPT, for example, uses a unique transformer architecture to predict redshifts directly by training on spectra with their corresponding redshift label (Pattnaik et al. 2025). Such supervised neural networks learn by comparing predictions with ground-truth labels (Rumelhart et al. 1986). The ground-truth redshift labels are often sourced from template-fitting algorithms that have been heavily vetted for bad fits (Lan et al. 2023; Alexander et al. 2023).
Unsupervised learning, however, operates under fundamentally different constraints. Unsupervised models have no access to a label to directly compare their predictions to. These neural networks typically compress high-dimensional data (e.g. spectra) to a lower-dimensional space while preserving the important features of the data. For example, autoencoders compress their input data into a low-dimensional latent space before decompressing to recreate the input data (Bourlard & Kamp 1988). Another powerful unsupervised algorithm is the self-organizing map (SOM). SOMs map each input to a discrete and finite two-dimensional map (Kohonen 1982). Self-organizing maps are ideal for clustering because they preserve the topology of the input space (Carrasco Kind & Brunner 2014). Further research has been conducted combining such methods in a joint learning effort. The deeply-embedded self-organizing map (DESOM) embeds a SOM in the latent-space of an autoencoder. Such models use a unique method of backpropagation that updates the encoder based on the typical autoencoder loss and the SOM loss by modifying the SOM to be differentiable (Mong et al. 2023). DE-SOMs have been used to classify galaxy morphology, inclination angle, and star formation history (Teimoorinia et al. 2022). All of the mentioned unsupervised models attempt to recreate the data from a compressed representation, therefore using the input data itself as
the ground truth. Without prior labels for measures such as redshift, machine learning models cannot output directly interpretable values.
Numerous examples of using machine learning for redshift prediction have been introduced; however, they are all fully or semi-supervised models. Such supervised methods require spectra (Zhong et al. 2024) or photometry (Collister & Lahav 2004) with associated predetermined redshifts for training. These redshift labels are often created using templates. Examples of semi-supervised models for photometric redshift have been introduced such as SOMz (Carrasco Kind & Brunner 2014), which uses an underlying unsupervised machine learning mechanism with post-inference supervised steps that require redshift labels. However, all of the methods described thus far require prior redshift labels either in training, template construction, or post-inference calibration. Without prior labels, conventional unsupervised models compress and reconstruct data, but do not output directly interpretable physical measures such as redshift.
Modern conventional algorithms remain constrained by their reliance on human-made redshift catalogs and template spectra. SDSS templates are created by grouping objects with similar redshifts and spectral shapes together, stacking them, and using PCA to identify the eigenspectra or templates (Bolton et al. 2012). However, such templates are prone to their own biases, which translate to estimated redshift measures (Hewett & Wild 2010). As surveys grow and the diversity of objects observed increases, a small set of templates is not sufficient to model spectra that exhibit extreme features (Anand et al. 2024). Limitations in template-based redshift algorithms carry over to the redshift catalogs used to train neural networks, creating the need for a label-free method of estimating redshift.
We introduce UnEZ, a novel fully unsupervised redshift and line strength prediction model. UnEZ addresses the weaknesses of previous redshift estimation algorithms while maintaining high precision and accuracy. The model requires initialization with physical parameters such as a line list, redshift sampling resolution, and maximum expected redshift. UnEZ accurately predicts redshifts and line strength ratios while requiring no labels for training. These measures can then be used for further analysis such as creating templates for traditional redshift fitting algorithms, performing AGN diagnostics (Veilleux 2002), and identifying outliers. Importantly, this model learns how to predict redshift and line strengths from first-principles by constraining the model to only output scientifically significant measures.
This paper will discuss the training, architecture, performance, and shortcomings of UnEZ. Beginning in Section 2 the data used for training/validation is reviewed alongside the various data cuts applied before training and testing. Section 3 describes the UnEZ pipeline from the model priors to the final output. Furthermore, Section 4 analyzes UnEZ's precision and accuracy in both redshift and line strength prediction. Lastly, Section 5 concludes with discussion of the quality of UnEZ's outputs, shortcomings/benefits of the pipeline, and future endeavors.
The SDSS team has implemented a redshift estimation algorithm that utilizes a fit between eigenspectra and observed spectra (Bolton et al. 2012). Although they mention a catastrophic redshift error rate of well below 1%, others have found that the error rate could be 1-2 times higher than cited by SDSS (Wu & Shen 2022). This is important to note because UnEZ is being directly compared to the SDSS pipeline redshifts. Some objects may be labeled as a catastrophic redshift error due to the reliance on SDSS redshifts as the “ground truth.”
Although both the original SDSS and BOSS spectrographs contributed to the DR18 dataset, they use different target selection methods to yield a diverse set of spectra. The original SDSS spectrograph primarily contributed to the Legacy Survey’s Main Galaxy Sample (MGS) (Strauss et al. 2002), Luminous Red Galaxy (LRG) sample (Eisenstein et al. 2001), and a quasar sample selected from objects with colors significantly different from the stellar locus (Richards et al. 2002). These samples cover galaxies and quasars up to redshift 5.46. The BOSS spectrograph further extended the legacy dataset to include dimmer and bluer targets alongside high redshift (z>2.1) quasars (Ross et al. 2012).
While UnEZ is designed to be implemented across different instruments and datasets, its performance on other instruments is not tested in this paper. The diverse dataset containing over 5 million objects provided by SDSS makes it ideal for training UnEZ and testing its reliability. The massive dataset provided by SDSS also provides robust performance metrics when testing UnEZ across various SNR and redshift regimes. The high count and diversity of objects available from SDSS is ideal for statistical analysis and is often required for training large neural networks.
3 ARCHITECTURE
UnEZ consists of an encoder and decoder component as shown in Figure 1. The decoder is composed of fixed algorithmic functions with no learnable parameters, ensuring that there is a systematic, unchanging reconstruction method for every spectrum. The encoder features several modern techniques such as a multi-headed attention mechanism and a series of convolutional embedding blocks to properly learn line strengths in each spectrum. Taking advantage of a sophisticated encoder and a fixed decoder, we show that UnEZ can accurately and precisely predict redshifts for millions of spectra. The configuration shown in Figures 1 and 2 has a total of 15,899,724 parameters.
UnEZ was designed to function similar to an autoencoder while meeting an additional requirement not native to autoencoder architectures. While both autoencoders and UnEZ transform data into a highly compact latent space, UnEZ is tasked with ensuring that latent space is directly interpretable as well. While an autoencoder can compress a spectrum into a few variables that contain the spectrum’s line strength features, those features cannot be directly read from the latent space. UnEZ fills that gap by ensuring that every value of the latent space represents a unique spectral line that can be directly read and interpreted without further processing. The architecture and loss

Redshift, Spectral Model, Confidence Curve, & Template
Figure 1. Diagram of the UnEZ neural network. The blue embedding block has learnable parameters while orange blocks are fixed deterministic functions with no learnable parameters.
function are carefully chosen to encourage learning behavior that results in a directly interpretable latent space.
The overall architecture follows a similar encoder-decoder architecture seen in autoencoders. The encoder receives a preprocessed spectrum as the input, and outputs a set of line strengths and a global line width. The decoder receives these line strengths as input, and deterministically outputs an unique template, a redshift, and a redshift confidence distribution. The deterministic nature of this decoder is not seen in traditional autoencoders which have a learned decoder. However, they both share the same goal of attempting to recreate the input spectrum from a latent space, hence we still refer to this portion of the pipeline as a decoder. The entire model is constrained by the physics information provided including spectral resolution, a maximum expected redshift, and line classifications among other variables discussed in Section 3.1.
3.1 Physics Priors
Before training, UnEZ must be initialized with physics priors. These priors influence many aspects of the model, including the size of the model and the spectral lines the model can detect.
The initial use of the physics information is for preprocessing. Given a maximum expected redshift, maximum observed wavelength
Abd et al.
Table 1. Architecture of the UnEZ model ( = batch size). All Conv1D layers use same padding and ReLU activation. A uniform dropout rate is applied after every Conv1D. The line branch provides the attention query; The depth branch provides the key and value.
| Stage | Layer | Configuration | Output shape | Parameters |
|---|---|---|---|---|
| Input | InputLayer | — | 0 | |
| Conv Block 1 | Conv1D | 64 filters, | 384 | |
| MaxPooling1D | pool size = 2 | 0 | ||
| Dropout | rate = 0.2 | 0 | ||
| Conv Block 2 | Conv1D | 128 filters, | 90 240 | |
| MaxPooling1D | pool size = 2 | 0 | ||
| Dropout | rate = 0.2 | 0 | ||
| Conv Block 3 | Conv1D | 256 filters, | 688 384 | |
| MaxPooling1D | pool size = 2 | 0 | ||
| Dropout | rate = 0.2 | 0 | ||
| Line Branch(Query) | Conv1D | 128 filters, | 2 097 280 | |
| Dropout | rate = 0.2 | 0 | ||
| Conv1D | 45 filters, | 401 457 | ||
| Dropout | rate = 0.2 | 0 | ||
| Depth Branch(Key / Value) | Conv1D | 256 filters, | 4 194 560 | |
| Dropout | rate = 0.2 | 0 | ||
| Conv1D | 512 filters, | 8 389 120 | ||
| Dropout | rate = 0.2 | 0 | ||
| Attention | MultiHeadAttention | 4 heads, key dim of 32 | 38 245 | |
| Column-wise Mean | Custom | — | 0 | |
| Output Heads | Custom Activations + ScaledSigmoid | 44 line strengths + 1 velocity dispersion () | 45 | |
| Total trainable parameters | 15 899 724 | |||
of the spectrograph, redshift sampling resolution, and number of pixels per spectrum, the pipeline defines a range of rest frame wavelengths the model can probe. The wavelength bins also serve as a basis for interpolating each spectrum onto a uniform wavelength axis, ensuring a constant length for all spectra. Details of the native and resampled parameters used for SDSS are highlighted in Table 2.
The relationship between redshift and wavelength is a quotient in linear space as shown in Equation 1, while being a difference in log-space as shown in Equation 2.
We use new wavelength bins with equal distance in log-space rather than linear-space. This allows redshift to be computed directly as a function of shift in log-space rather than a quotient in linear-space.
The variability in the wavelength bins also allows the model to adjust its redshift probing resolution to various instruments and redshift regimes. Increasing probing resolution (super-resolution) beyond the telescope’s native capabilities can reduce scatter in redshift predictions (Bezanson et al. 2016). Conversely, decreasing probing resolution allows the user to optimize for computational efficiency at the cost of redshift prediction precision.
In addition to preprocessing priors, UnEZ requires a comprehensive list of spectral lines. Each line entry must include:
(i) Line Center: The rest-frame wavelength of the spectral line.
(ii) Line Name: A label used for visualization and interpretation.
(iii) Line Classification: An assignment of each line as either absorption-only, emission-only, or both.
The line list used for this experiment, sourced from the SDSS
Table 2. Native and resampled spectral properties including resolution and wavelength range, and pixel spacing.
| SDSS | BOSS | |
|---|---|---|
| Native Min/Max Wavelength | 3800Å–9200Å | 3600Å–10400Å |
| Native Resolution | 1500 at 3800Å, 2500 at 9000Å | |
| Native Pixel Spacing | dex | |
| Resampled Pixel Spacing | dex | |
| Resampled Min/Max Wavelength | 3600Å– 9400Å |
DR6 pipeline line list (Sloan Digital Sky Survey 2008), is further discussed in Appendix A and listed in Table A1. This line list with its corresponding classifications directly influences UnEZ’s architecture at almost every layer. Most notably, it affects the encoder’s output dimension, the shape of the attention mechanism, and the Gaussian template construction layer found in Figures 1 and 2.
This prior physics information is critical to UnEZ’s architecture. By constraining UnEZ’s outputs to only what is physically possible, the probability of the model being trapped in a local minimum or fitting to degeneracies is greatly reduced. Constraining the parameter-space made available to UnEZ makes the problem of learning line strengths easier for the model by forcing its predictions into a smaller and more physical latent space.
3.2 Preprocessing
The preprocessing pipeline is designed to emphasize the emission and absorption lines while removing any information that is not important for line strength and redshift prediction. This process involves three key steps: masking bad pixels, removing the continuum, and mitigating edge effects, as shown in Figure 3. The spectral pre-

Figure 2. Diagram of the embedding layer in Figure 1. The red blocks contain a max-pooling layer while the cyan blocks do not. The last cyan blocks feed into the multi-headed attention mechanism, with the right-side block being the keys and the left-side block being the queries. Detailed specifications and hyperparameters are listed in Table 1.
processing steps largely follow those used in MARZ (Hinton et al. 2016).
Prior to preprocessing, the SDSS catalog is utilized to apply a cut. This is one of the most important limitations of the UnEZ pipeline. Star spectra display a wide diversity of continua that cannot always be approximated with a polynomial as we do below. This major limitation will be addressed in future work, however, as a proof of concept we remove these low redshift spectra from our training and testing dataset.
In addition, two signal to noise ratio (SNR) cuts are applied to the data. SNR is defined in Equation 3 where pixel flux is defined as , standard deviation of is defined as , and the number of pixels is defined as p.
For this experiment, a cut was applied as it constrains the distribution of spectral lines in the dataset. Training and validation spectra are held to a high quality standard with a SNR cut of SNR > 10. Performance metrics are conducted on a wide range of SNR cuts as discussed later in Section 4.
After all cuts have been applied, 771,086 spectra remain for testing. Of the over 700 thousand spectra left, 83,333 spectra are randomly selected for training and 16,667 random spectra are used for validation.
After all data cuts have been applied, we remove bad pixels from the spectra. Pixels that meet this criteria include cosmic rays, human-specified sky lines (Sloan Digital Sky Survey 2008), NaN pixels, zero inverse-variance pixels, and pixels exceeding a predetermined power threshold. Cosmic rays are flagged as any pixel that exceeds 30 standard deviations above the mean of the four surrounding pixels. These pixels are replaced by the mean intensity of the nine neighboring pixels on both sides of the cosmic ray. If neighboring pixels are flagged as bad pixels, the pixel intensity defaults to zero. For all other bad pixels (sky line residuals, NaNs, zero inverse-variance, power threshold exceedances), each pixel is replaced by the mean intensity of the four neighboring pixels on either side. This attempts to remove any noise or anomalous data that may not be native to the object being observed.
Once bad pixels have been masked, the pipeline moves on to the continuum removal step. A sixth-order polynomial is recursively fit to the spectrum and subtracted from the flux. Pixels with an intensity exceeding 3.5 standard deviations from the mean are excluded from the fitting process. Each time the polynomial is fit, it is then subtracted from the spectrum and the process is repeated again. This is done recursively until the spectrum no longer changes, or 15 iterations of this fitting method have been completed. This step aims to keep the sharp emission and absorption features in the spectrum while eliminating the broad and smooth continuum. Lastly, edge effects must be addressed, as they have been shown to critically degrade UnEZ's ability to predict line strengths and redshift during testing. To reduce edge effects, the last 75 pixels on either side of the spectrum are set to zero intensity, effectively removing them completely from the spectrum. This last step is critical as testing UnEZ without the removal of edge effects has led to catastrophic failure in redshift prediction across the entire dataset due to the excess noise near the edge of the detector. Stellar spectra were omitted from this pipeline due to this continuum subtraction method failing for stars. Star continua cannot be systematically modeled using a low-order polynomial due to their wide diversity in continuum shapes.
In summary, the preprocessing pipeline removes bad pixels (e.g. cosmic rays, skylines, etc.), removes the continuum with a recursive polynomial fit, interpolates the spectrum into uniform wavelength bins, and clips the noisy edges. These preprocessing steps produce a spectrum that has been optimized for accurate line strength and redshift measurements.
3.3 Encoder
The encoder mechanism utilizes several modern and custom techniques to perform its sole task of predicting line strengths. It takes a preprocessed spectrum in the observed frame as an input and outputs a series of line strengths for the lines listed in the physics priors. The encoder's role is to map spectra to directly interpretable and redshift-invariant spectral line parameters. The specific parameters of the model are highlighted in Table 1.
The embedding layer, detailed in Figure 2, consists of several convolutional blocks and a multi-headed attention mechanism. The model begins with three convolutional blocks with each block including dropout and max pooling. Each block also has an increasing number of filters and kernel size. The last of these blocks are then fed into two separate and disconnected lines of convolutional blocks without max-pooling. While one branch is left unconstrained, the other is constrained by the number of lines, allowing the number of learnable parameters to scale with the complexity of the physics priors. Testing has shown the lack of max-pooling yields more accurate results. One branch, referred to as the depth branch, ends with
Abd et al.

Figure 3. (top) Raw SDSS spectrum. (middle) Spectrum with bad pixels such as skylines, zero variance pixels, and cosmic rays removed. (bottom) Final preprocessed spectrum with the continuum removed that has been interpolated into uniform wavelength bins and clipped at the ends to remove edge effects. Bad pixels are denoted by the gray shaded region.
512 filters and a kernel width of 64, as testing has shown little to no benefit from increasing the dimensionality of this branch. The other branch, referred to as the line branch, has filters, where is the number of lines in the provided line list and is the number of line widths predicted for each spectrum. To constrain the latent-space as much as possible we use . The line branch output is constrained by the physics information, serving as a mechanism for the number of predicted lines, , to affect the embedding architecture. The depth layer serves as a larger abstract interpretation of the line strengths. As the input size of a model increases, more parameters are often needed to prevent undertraining. The depth branch allows for this modification in future endeavors while the line branch maintains a physics-constraint on the architecture as well. The last layer in the line branch, with filters, is meant to represent the initial line strength predictions for each line. However, it has been shown that convolutional layers are inefficient in cross-referencing data that are far apart in high-dimensional inputs (Vaswani et al. 2023). Meaning, if there is a line on one end of the spectrum and another line
on the other end of the spectrum, it cannot effectively compare the two to make an accurate prediction without increasing the depth of the model. With high-dimensional spectra this can become a critical problem. However, this can be mitigated with the multi-headed attention mechanism.
Attention mechanisms are a modern technique that Google researchers developed to address the shortcomings of recurrent neural networks (RNNs) and convolutional neural networks (CNNs) in processing high-dimensional data (Vaswani et al. 2023). The creation of the attention mechanism led to a massive growth in neural network applications, particularly large language models such as GPT-3 (Brown et al. 2020). Attention mechanisms have been shown to be exceptional in processing high-dimensional inputs and identifying correlated features. In the context of large language models, some words have many different meanings depending on the context. For example, the word "star" might refer to an exceptional pupil such as a star athlete, or it could refer to an astrophysical object. The attention mechanism will correlate the word "star" with other words in the sentence, perhaps the word “space” or “plasma”, to understand which meaning of the word is intended. In the context of UnEZ, the attention mechanism is meant to find correlations between different spectral lines. For example, a strong Hα emission might correlate with a strong [O III] emission line, since they are both associated with star formation. The attention mechanism will learn to recognize these patterns between lines, even when they are far apart, to better predict which lines are present and at what strength.
The multi-headed attention layer in UnEZ has 4 heads with a key dimension of 32. Although utilizing more heads or a higher dimensionality for the keys could be beneficial, these values were chosen due to hardware limitations. The purpose of the multi-headed attention mechanism is to use the initial line strength predictions and the depth layer in order to update the initial line strength predictions. By comparing the depth layer with the initial line strength predictions it is able to accurately compare two lines despite their distance from one another in the spectrum to make a more accurate prediction. In essence, it acts as an updating layer that updates the initial line strength predictions to a final line strength prediction. This multi-headed attention mechanism outputs an updated set of vectors, each representing an individual line's strength. The mean of each vector is then taken as the final line strength prediction in the column-wise mean layer.
Lastly, these final line strength predictions are passed through the classification activation functions labeled as custom activations in Figure 1. As discussed in Section 3.1, each line must be classified prior to training. If a line is classified as emission/absorption, then the line strength prediction is passed through a linear activation function. If the line is classified as emission-only, the line strength prediction is passed through a ReLU activation function. Lastly, if the line is absorption-only, it is passed through a negative ReLU activation function. This ensures that the line strength predictions are constrained to only what is physically possible, mitigating the chances of fitting to degeneracies and maintaining a directly interpretable latent space. The final vector corresponding to the line width prediction is passed through a scaled sigmoid activation function. While a typical sigmoid function is constrained to values from 0 to 1, the scaled sigmoid function is normalized to output values from a defined minimum and maximum value. This prevents the model from predicting line widths that are too narrow or broad causing a disappearing/exploding gradient problem. This final output of the encoder is a set of line strengths and widths that can be used for various tasks such as creating BPT diagrams as in Section 4.2, creating templates as in Section 4.2.1, or estimating redshift as discussed in Section 3.4.
3.4 Decoder
The decoder reconstructs the input spectrum using a Gaussian curve to model each spectral line. The decoder's role is to transform the predicted line strengths into a unique template, spectral model, redshift confidence curve, and estimated redshift. Although we refer to this portion of the architecture as the decoder, it does not have any learned parameters that a traditional autoencoder decoder has. It is a fixed deterministic decoder (e.g. video decoder, text decoder, audio decoder, etc.), that recreates the input spectrum from its predicted line strengths.
The first layer of the decoder creates the unique Gaussian template. This template spans the length of the wavelength bins and includes all possible rest-frame wavelengths within the constraints of the provided physics information. Each line is modeled by a Gaussian shape with two primary parameters: amplitude and width. The Gaussians are centered on the wavelength of each spectral line . The ampli-
tude is determined by the expected line strength provided by the encoder. However, the width parameter is uniform across all lines of a spectrum in this model. The final Gaussian template is modeled by the sum of all Gaussians G shown in equation 4.
It is important to note that not all lines in a spectrum will have the same width. Variance in line widths can be caused by several different mechanisms. For example, lines can have different widths depending on the line of sight and disc inclination (Kollatschny et al. 2006). However, this intentional constraint is enforced to stabilize unsupervised learning and constrain the parameter-space UnEZ learns from.
The subsequent decoder function predicts the redshift and calculates the training loss. This algorithm aligns the input spectrum I with the Gaussian template G and shifts the spectrum one pixel at a time, covering the entire range of possible redshifts. This is similar to how template fitting functions operate, however there are some critical differences. The Gaussian template used by UnEZ is unique to each spectrum, while template fitting methods utilize a few fixed templates for all spectra. Additionally, a unique loss function is utilized to compute a similarity while template fitting methods generally use either a or cross-correlation algorithm for computing similarity. At each incremental shift z, a composite loss function that utilizes both a cosine similarity and a mean squared error is calculated. The cosine similarity shown in equation 5
is useful for measuring alignment between two spectra but is insensitive to a difference in amplitude. This is due to the L2 normalization factor required in calculating a cosine similarity exhibited by equations 6 and 7.
The mean squared error shown in equation 8 on the other hand, carries information about differences in magnitude and alignment between two spectra.
By using a weighted sum of these two functions shown in equation 9
the model is able to robustly measure both alignment and magnitude measures, improving the accuracy and reliability of line strength and redshift predictions. With each shift, the loss is recalculated and assigned to the shift's corresponding redshift. The collection of these loss values is referred to as the inverse confidence curve, and the lowest point on the inverse confidence curve corresponds to the most probable redshift of the spectrum.
Traditional redshift estimation methods typically utilize template
Abd et al.
eigenspectra and either a cross-correlation or algorithm to estimate redshift (Glazebrook et al. 1998; Baldry et al. 2014; Bolton et al. 2012). These methods are very similar to the custom loss layer in UnEZ's architecture in that they measure similarity across many trial redshifts. However, UnEZ predicts a unique set of line strengths for every object, rather than projecting a spectrum onto a set of templates. Given the deterministic nature of the decoder, one might ask whether the line strengths can also be estimated deterministically by projecting the spectrum onto Equation 4 at every redshift and line width. This avenue is further explored in Appendix B. We find that UnEZ performs better in every metric.
The final step of the decoder reconstructs the spectrum using the redshift prediction and Gaussian template. The redshift is obtained from the inverse confidence curve and the Gaussian template is precisely spliced at the corresponding redshift. The model effectively extracts the segment from the Gaussian template that best matches the input spectrum. Both the spectrum and Gaussian template segment are normalized via L2 normalization and multiplied by the spectrum normalization factor to ensure similar scaling. This segment is the decoder's reconstruction of the input spectrum. Both UnEZ's final layer and autoencoders reconstruct the spectrum, however the UnEZ reconstruction is constrained to only what is physically possible.
Using such a decoder brings various benefits to redshift prediction. While modern automatic redshift algorithms use a series of fixed templates for their estimates, UnEZ's decoder creates a unique template for every spectrum. This diversity in templates will ideally fit a more diverse distribution of spectra.
3.5 Training Loss
The losses, , computed at trial redshifts form the inverse confidence curve where low values correspond to the best fit. However, neural networks require a single scalar loss value to train (Damadi et al. 2023), not a collection of loss values. The mean or sum of the inverse confidence curve can be used as a training loss, but that comes with downsides. While UnEZ probes thousands of trial redshifts, only one is assumed to be correct. A vast majority of trial redshifts are bad fits, therefore a training method that focuses learning on only the most probable redshifts would reduce catastrophic redshift estimation failures.
The inverse confidence curve is further processed to encourage this “focused” learning. We negate this curve so we have the confidence curve, , and sort it in descending order such that corresponds to the most probable redshift. Only the top values are retained (k=120 for this experiment) and weighted by a decaying exponential curve and normalized to sum one as in Equation 10.
The radius, , exponentially decays with training epochs from to over the training epochs. This ensures the model initially learns from a broad range of candidate redshifts before narrowing its focus on only the most probable few.
The training loss is the re-inverted weighted sum of the retained values as in Equation 11.
The gradient through the training loss, , scales with the exponential weights. This ensures that improbable
redshifts contribute very little to the learned parameter-space during training. Restricting the loss to the top- fits further prevents the model from learning from improbable redshifts and reduces its sensitivity to degeneracies between lines. This training loss updates only the embeddings highlighted in Figures 1 and 2.
4 PERFORMANCE
UnEZ was trained on a NVIDIA 80GB A100 GPU for approximately 6 hours while testing was conducted on up to five A100s simultaneously in approximately 2 hours. Varying the training set size and width of the wavelength bins have a linear impact on training/inference time and performance. Doubling the training set size will double training time, while doubling the wavelength bin width will halve the training time.
Various metrics can be used to understand the redshift and line strength performance of UnEZ. By comparing with commonly used software alongside the SDSS catalog measures, both the strengths and weaknesses of UnEZ emerge.
4.1 Redshift
UnEZ achieves performance comparable to state-of-the-art methods across a wide range of signal-to-noise ratios. Figure 4 shows an outlier fraction of 0.459% at SNR > 10, and Figure 5 shows an outlier fraction of 3.888% at SNR > 3 when comparing to the SDSS redshifts. Figure 6 further highlights UnEZ's abilities as the model maintains stable and predictable performance metrics across a wide range of noise levels. Despite the lack of templates or redshift labels UnEZ demonstrates the high accuracy and precision seen in traditional redshift estimation methods.
An outlier cutoff of (approximately ) is chosen in accordance with traditional automatic redshift software such as MARZ (Hinton et al. 2016) and AUTOZ (Baldry et al. 2014). Several valuable metrics, including , are used to evaluate UnEZ's performance to varying degrees.
, defined here in equation 12,
approximates a difference in redshifts as a velocity (Baldry 2018) making it widely used as a measure of precision in automatic redshift algorithms. The bottom panel of Figures 4 and 5 show how varies for inliers across various redshifts. Figure 7 is a similar plot showing in units of . A clear trend between these plots is the wider scatter quasars exhibit when compared to galaxies. This is expected as quasars often have very broad lines creating higher statistical uncertainties in redshift estimation.
Another commonly used measure to gauge the precision of such a model is the normalized median absolute deviation, or NMAD shown in Equation 13 (Pattnaik et al. 2025).
The NMAD is also a robust performance metric due to its lack of sensitivity to catastrophic redshift prediction failures (Molino et al. 2014). The NMAD for SNR > 10 is (37 km·s⁻¹) while for SNR > 3 is (44 km·s⁻¹), exhibiting a high level of precision which is comparable to or better than existing automatic redshift algorithms such as MARZ (Hinton et al. 2016). This demonstrates UnEZ's ability to predict redshifts with high precision and accuracy.

Figure 4. Comparison of SDSS catalog redshifts with UnEZ predictions for objects with 0.003 < z < 1.0 and SNR > 10. Top: Distribution of catalog redshifts, highlighting the dominance of galaxies (blue) and the increasing prevalence of quasars (orange) at higher redshift. Middle: Predicted versus catalog redshift, with the red dashed line marking the 1:1 relation. The concentration along this line indicates accurate recovery, while horizontal and parallel features mark common misidentifications. Bottom: and (in ) versus catalog redshift showing how the spread trends with increasing redshift. UnEZ achieves NMAD = with an outlier fraction of 0.46% across 771,086 spectra.
It is important to note that the NMAD is heavily dependent on the wavelength bin width chosen in the model's physics priors. Decreasing the wavelength bin width leads to a lower NMAD, but only to an extent. As the bin width approaches the resolution of the telescope the NMAD no longer decreases. Additionally, the computational re-
sources required to train such a large model makes decreasing the bin width redundant. All of the mentioned performance metrics are highlighted in Table 3 for SNR > 10 and Table 4 for SNR > 3.
Further analysis of the catastrophic redshift estimation failures revealed 3 systematic outlier classifications. At SNR > 10, stellar
Abd et al.

Figure 5. As Figure 4, but for the lower SNR > 3 sample. All panels, colors, and symbols are identical to Figure 4. At this cut, UnEZ achieves NMAD = with an outlier fraction of 3.89% across 1,817,847 spectra. Skyline contamination becomes markedly more prevalent as noise increases, and the strongest line-confusion degeneracies appear as ridges parallel to the 1:1 relation.
contamination from nearby stars make up approximately 500 of the outliers (0.06% of the entire dataset), skyline contamination make up approximately 600 of the outliers (0.08% of the dataset), and line confusion degeneracies are responsible for another 31 outliers (0.004% of the dataset). These outliers are further discussed in Section 5.1.
4.1.1 Outliers and Inliers
Both inliers and outliers in UnEZ's predicted redshift catalog reveal the strengths and shortcomings of the model. Figure 8 showcases representative examples of spectra where UnEZ predicts the redshift accurately. A starburst galaxy, quasar, and quiescent galaxy are all shown with their UnEZ models and rest frame lines. Here, a weakness of UnEZ is highlighted. Although the model is very robust when

Figure 6. (top) Outlier fraction as a function of signal-to-noise ratio. (middle) NMAD as a function of SNR. The dashed lines in these plots correspond to NMAD and outlier fraction values shown in the main plot of Figure 4. (bottom) Distribution of SNR across the entire dataset, with the dashed line representing the cutoff for how many points are needed for a meaningful measure of outlier fraction and NMAD and their errors. Performance quickly degrades with lower SNR regardless of quasar (orange) or galaxy (blue) classification.

Figure 7. Distribution of for galaxies (blue) and quasars (orange). The outlier threshold is highlighted by the red dashed line at or km s.
Table 3. Sample size, inlier fraction, and NMAD of each spectral class at SNR > 10.
| Class | Sample Size | Inlier % | NMAD |
|---|---|---|---|
| QSO | 45,516 | 97.1% | (123 km s) |
| Galaxy | 725,391 | 99.7% | (36 km s) |
| Total | 771,086 | 99.5% | (37 km s) |
Table 4. As Table 3, but for the SNR > 3 sample.
| Class | Sample Size | Inlier % | NMAD |
|---|---|---|---|
| QSO | 147,326 | 94.5% | (104 km s) |
| Galaxy | 1,670,069 | 96.3% | (42 km s) |
| Total | 1,817,847 | 96.1% | (44 km s) |
tasked with predicting the redshift, its line strength predictions are not always accurate. This is shown for example in the quiescent galaxy spectrum’s Mg b 5176Å absorption where UnEZ overestimates the absorption line.
A majority of UnEZ’s catastrophic failures in redshift prediction are caused by either sky line contamination or by line degeneracies. However, hidden among these outliers are some uniquely interesting spectra. Three examples are shown in Figure 9. The middle panel displays an iron low-ionization broad absorption line (FeLoBAL) quasar candidate, while the top and bottom panels show spectra of superimposed galaxies. FeLoBAL quasars exhibit extreme properties that are not yet fully understood. This particular spectrum is a FeLoBAL candidate at a redshift of 2.58 (Leighly et al. 2025) with thousands of iron absorption lines superimposed and velocity dispersions exceeding 3000 km s. Models such as SimBAL have been utilized to model properties such as the outflow ionization factor, however the mechanism driving such extreme objects has not yet been confirmed (Choi et al. 2022). The top and bottom panel showing superimposed galaxy spectra are also interesting because the SDSS automatic redshift prediction algorithm found one redshift, while UnEZ found the other. The photometry in the top right panel of Figure 9 reveals multiple sources overlapping. The spectrum shows a clear H and K absorption at the SDSS redshift (), with H and several oxygen emission lines at the UnEZ redshift (). The bottom panel’s photometry does not show multiple sources in the photometry, but two clear sets of H and K lines are visible at both the SDSS and UnEZ redshifts. The superimposed nature of the spectrum is further confirmed by the two minima highlighted on the inverse confidence plot in Figure 10.
To quantify how often redshift outliers are real UnEZ failures, 980 randomly selected outlier spectra with SNR > 10 were visually inspected to further verify the redshift. These objects are categorized into the following six groups:
(i) SDSS Correct
(ii) UnEZ Correct
(iii) Both Correct: Superimposed spectra at different redshifts
(iv) Close: Spectra were too noisy to distinguish between the two candidate redshifts
(v) Neither: Both the UnEZ and SDSS redshift were incorrect
(vi) Unknown: Could not visually confirm a redshift
The results in Table 5 show that approximately 63.8% of the time SDSS recovers the correct redshift and UnEZ does not. On the other hand, in 12.8% of cases UnEZ recovers the correct redshift where SDSS does not. A further 9% are superimposed spectra with different redshifts where UnEZ recovers one redshift and SDSS the other. Another 5.9% are too noisy to confirm one redshift or the other. Together, the UnEZ-correct and superimposed cases show that at least
Abd et al.

Figure 8. Inlier examples. (top) Starburst Galaxy. (middle) Quasar. (bottom) Quiescent Galaxy. SDSS spectra are shown in black while UnEZ's spliced template is shown in red. The right panels show the SDSS photometry for each object with the fiber placement overlaid in cyan.
Table 5. Visual classification of 980 inspected UnEZ redshift outliers.
| Category | N | Percentage |
|---|---|---|
| SDSS correct | 625 | 63.8% |
| UnEZ correct | 125 | 12.8% |
| Both (superimposed) | 88 | 9.0% |
| Close | 58 | 5.9% |
| Neither | 51 | 5.2% |
| Unknown | 33 | 3.4% |
21.8% of redshift outliers are not failures of UnEZ, rising to 27.7% if the ambiguous close cases are included. This further supports the interpretation of the quoted outlier fraction as a lower limit on the model's performance in Section 5.1.
4.2 Line Strength Predictions
UnEZ has shown promising results with respect to redshift prediction, however Figure 1 highlights a potential weak point for the model. Line strengths are predicted first, then redshift is estimated as a proxy. Therefore, having inaccurate line strength predictions will lead to many catastrophic redshift estimation failures.
We compare UnEZ line fluxes with those in the SDSS catalog in Figure 11. UnEZ fluxes are computed from the predicted Gaussian amplitude S and shared line width as shown in Equation 14 after rescaling S by the spectrum's normalization factor.
The comparison is restricted to redshift inliers ( ), lines

Figure 9. As Figure 8, but for outliers. (top) Superimposed objects at different redshifts with multiple distinct sources in the photometry. (middle) Iron low-ionization broad absorption line (FeLoBAL) quasar spectrum. (bottom) Superimposed objects at different redshifts with the second source not visible in the SDSS photometry.
with SDSS SNR > 5, and lines with non-zero UnEZ amplitude, causing the sample size differences between lines.
UnEZ systematically under-predicts line fluxes, most strongly for [O III] λ5008, and the discrepancy grows as the line fluxes weaken. On the other hand, Hα line fluxes are closest in agreement. Individual UnEZ fluxes are therefore not yet reliable for scientific use. Because the under-prediction is consistent in sign across lines, it may partly cancel in line ratios.
One method of comparing line ratio predictions is through a Baldwin, Phillips, and Terlevich (BPT) diagram (Baldwin et al. 1981). BPT diagrams utilize ratios of various emission line strengths to classify spectra, making them an ideal candidate for understanding how UnEZ's systematic under-prediction of line fluxes translates to line ratios. The BPT diagram in Figure 12 presents one such set of
line ratios commonly used to distinguish AGN from star-forming galaxies (Kewley et al. 2006).
The Earth Mover's Distance (EMD) is a measure of how much work is required to convert one distribution into another (Rubner et al. 2000). The EMD, unlike median offset, is sensitive to differences in shape and spread as well as location. It is also defined for non-overlapping distributions and is expressed in physical units (dex), unlike the KL divergence. Comparing UnEZ and SDSS catalog line strength ratios in Figure 12 shows an EMD of approximately 0.1668 dex. The EMD is in units of the x and y axes of Figure 12. It can therefore be converted from log-space to linear-space to find UnEZ's line ratio predictions are, on average, off by a factor of 1.468. The SDSS pipeline fits template continua for continuum subtraction during its line fitting process (Bolton et al. 2012) as opposed to
Abd et al.

Figure 10. UnEZ's predicted loss landscape for superimposed galaxies shown in the bottom panel of Figure 9.

Figure 11. Comparison of emission line fluxes predicted by UnEZ () with those from the SDSS catalog () for Hβ, [O III] λ5008, Hα, and the [N II] λ6550,6585 doublet. Only redshift inliers with SDSS line SNR > 5 and a non-zero UnEZ amplitude are shown. gives the number of objects in each panel. UnEZ fluxes are computed using Equation 14. The [N II] doublet is the sum of both line fluxes in each catalog. The color bar shows the normalized count per bin. The thick and thin contours enclose 68% and 95% of the objects, while the dashed line marks the 1:1 relation.
UnEZ's sixth-order polynomial fit. Choice of continuum removal has been shown to have an effect on spectral modeling (Aihara et al. 2011), which can lead to the discrepancy in line-strength fits. Despite individual fluxes being systematically under-predicted, the line ratios differ by an EMD of 0.1668 dex, showing that the under-prediction largely cancels.
4.2.1 Self Organizing Map Clustering
Another method to test the effectiveness of UnEZ's line strength predictions is to cluster similar spectra together by their predicted line strengths and see if any expected patterns are apparent. One expected pattern in clustering line strengths is a separation between galaxies and quasars. Galaxies are much dimmer, have much narrower lines, can contain predominantly or exclusively absorption lines, and are
at generally lower redshifts. On the other hand, quasars have very broad lines, are extremely bright, have mostly emission lines, and are at generally higher redshifts. Considering UnEZ's predictions include line widths and strengths, quasars and galaxies should have substantially different predicted line strengths from UnEZ's pipeline.
A 60×60 SOM was trained for 200,000 training epochs on 491,323 UnEZ-predicted line strengths and widths to produce the clustering maps shown in Figure 13 and Figure 14. A clear cluster emerges in the center of the SOM that has a peculiarly high redshift and velocity dispersion when compared to the rest of the map. This cluster likely contains a majority of the quasars in the dataset and very few galaxies.
To confirm this, a clustering algorithm was deployed on the SOM's weights. A connectivity-constrained agglomerative clustering algorithm (Murtagh 1995) was used to find 3 clusters denoted by the red points on Figure 13 and Figure 14. This clustering algorithm ensures that clusters do not overlap or cross gaps without connec-

Figure 12. BPT Diagram composed from UnEZ's predicted line strength ratios with SDSS catalog line strength ratios overlaid. The red dashed line is an AGN diagnostic line separating AGN from starburst galaxies (Kewley et al. 2001).

Figure 13. SOM map showing redshift topology across the map indices. The color represents the median of the spectra belonging to that node. The red scatter points, labeled by their corresponding template spectrum, are the cluster centroids of the map's node weights, while the white outlines show the cluster boundaries.
tivity. K-means clustering, for example, creates clusters that might be split on opposite sides of the map. The SOM clusters similar objects close together, therefore spatially disconnected clusters would group objects from different regions of the map, introducing severe cross-class contamination. One of these cluster centers falls onto the suspected quasar cluster in the center of the map. The median redshift and velocity dispersion of each cluster is then computed. By using a velocity dispersion cut of km s, the suspected quasar

Figure 14. SOM map showing velocity dispersion topology across the map indices. The color represents the median velocity dispersion, predicted by UnEZ, of the spectra belonging to that node. The red scatter points, labeled by their corresponding template spectrum, are the cluster centroids, while the white outlines show the cluster boundaries.
Table 6. Table of SDSS classifications compared to UnEZ classifications.
| QSO → QSO | Galaxy → Galaxy | QSO → Galaxy | Galaxy → QSO |
|---|---|---|---|
| 13,778 | 475,533 | 929 | 1083 |
cluster is separated and classified by UnEZ as quasars. Any cluster falling below the cut is classified as a galaxy.
Table 6 shows the results of the SOM clustering and classification technique. Of the 476,616 spectra classified as galaxies by SDSS, 1083 were classified as quasars by UnEZ. Of the 14,707 spectra classified as quasars by SDSS, 929 were classified as galaxies by UnEZ.
All of the spectra were then shifted to the rest-frame using UnEZ's predicted redshifts, and the median spectrum of each cluster was taken. Ideally, these median spectra would be the final template, however, the clusters do not perfectly separate quasars and galaxies. Some high redshift quasars can contaminate the galaxy templates leading to an unphysical transition between quasar and galaxy-like features. To mitigate this effect the number of spectra contributing to each pixel's median is counted. Any pixels with less than 5% of the total count are omitted from the template. This creates different wavelength ranges in some templates shown in Figure 15. Template 1 exhibits a strong continuum with absorption lines as expected from high metallicity elliptical galaxies, template 2 shows strong and narrow emission lines from HII regions, and template 3 shows strong and wide emission lines expected from AGN.
As no redshift, velocity dispersion, or classification labels were used during the training of the SOM, this extension of the UnEZ pipeline exhibits the ability to classify spectra and produce template spectra from large datasets without any prior labels.
5 DISCUSSION
UnEZ serves as a compelling proof of concept that a neural network can learn the concept of redshift from first principles. An architec-
Abd et al.

Figure 15. Three templates constructed from median spectrum of each cluster predicted by UnEZ line strengths.
ture designed to compress spectra into only scientifically significant values makes this possible. In contrast to conventional redshift estimation pipelines, the training of this model requires no redshift or line strength labels as it is primarily driven by its physics-informed constraints. This shows how competitive redshift performance can emerge from the structure of spectral data and minimal prior physics information. UnEZ creates a pathway toward scalable spectral analysis in new redshift regimes and where data labels are scarce.
5.1 Output Quality
UnEZ maintains high redshift accuracy even at relatively low signal-to-noise ratios, achieving over 95% inlier performance down to SNR > 3 and over 99.5% inlier performance at SNR > 10. It is important to note, the SDSS redshift estimation pipeline is not perfect and its reliability suffers particularly at lower SNR. Approximately 0.2% of
galaxy redshifts and 0.5% of quasar redshifts have been found to be incorrect through visual inspection (Bolton et al. 2012). This further highlights that the mentioned performance metrics, such as the outlier fraction, represent the lower limit of UnEZ's overall performance as mentioned in Section 4.1. Crucially, UnEZ does not rely on template spectra at any stage. Rather, the only priors required are the physics information that is mostly specific to the instrument being used and the spectral lines expected from different galaxies.
Despite its strength, there are some caveats to UnEZ's performance. UnEZ's performance is heavily linked to the quality of the data. Figure 6 shows a stark increase in NMAD at SNR < 3, and a gradual increase in outlier fraction at SNR < 10. The increase in NMAD is likely attributed to how well individual lines are being fit, as noisier lines leave more room for error in the line fit. The increase in outlier fraction at lower SNR can be attributed to line misidentification. As the noise across the spectrum decreases, UnEZ is less likely to fit to the noise or the incorrect lines. Counterintuitively, there is also a slight increase in outlier fraction at very high SNR in Figure 6, likely due to selection effects or a lack of representation of such data in the training set. There are very few data points available at such high SNR which can prohibit UnEZ's ability to learn from such data properly. The plateau in both NMAD and outlier fraction at SNR > 10 represents UnEZ's best possible performance. Such catastrophic outliers at high SNR can either be attributed to bad data, or systematic shortcomings of UnEZ's ability to identify and fit lines.
Such systematic catastrophic errors in redshift prediction, as shown in Figure 4, can be categorized into three main classes. The first class of catastrophic errors are the sky lines that appear as horizontal bands in Figure 4. Because sky lines are redshift-invariant and occur at fixed observed wavelengths, if UnEZ mistakenly fits an emission line to a sky line feature, it will consistently assign the same incorrect redshift. The model can be modified in the future to predict a rest frame template of skylines in addition to the template of the target. Additionally, a precursor model could be trained to de-noise spectra before training and inference in the future (Scourfield et al. 2023).
Another systematic error is caused by a line confusion degeneracy that manifests as faint parallel lines (due to redshifts being plotted as ) to the 1:1 line in Figure 5. Galaxies primarily suffer from a 5008 confusion while quasars show primarily Mg II 2799→C II 2326 and Mg II 2799→[O III] 5008 line confusions. These degeneracy examples can typically be mitigated by reducing sky line contamination, which in turn allows the model to be more confident in its prediction of which lines are and are not real. Although this degeneracy is not yet corrected, future analysis may reveal a more effective method of addressing the degeneracy problem.
Accurate line strength prediction is important for UnEZ because they act as a prior in the redshift estimation process. Although these predictions are sufficiently accurate to enable precise and reliable redshift estimates, its systematic under-prediction of individual line fluxes in Figure 11 makes it unreliable for single-line measurements. However, as shown in Figure 12, the SDSS and UnEZ line-ratio distributions differ significantly less than individual line flux measurements. Future improvements to the normalization procedure used throughout the pipeline may help reduce this discrepancy in line flux estimations. UnEZ currently applies an L2 normalization to all spectra before training and inference. Other normalization techniques, such as min-max normalization, may be more suitable for line-strength fitting in the future. It is important to note, however, that UnEZ and SDSS use different continuum fitting methods during the preprocessing stage. This is known to cause discrepancies in line strength measurements (Aihara et al. 2011) and can be a potential cause of the discrepancy seen between UnEZ and the SDSS catalog.
5.2 Benefits and Drawbacks
UnEZ is a highly capable neural network with diverse applications. Although UnEZ's primary goal is to predict redshifts of astronomical spectra, it shows promise of also being used for line strength prediction and outlier detection. The model is successful in reliably and accurately predicting redshifts in a fully unsupervised manner. We re-emphasize that at no point did we include redshifts in the training data. The model learns how to precisely predict redshifts independently by trying to match the provided rest frame lines from the provided line list to features in spectra.
Although unsupervised machine learning methods have been historically used for clustering, the results are not physically interpretable. Algorithms such as SOMz require further supervised steps
to map a physical meaning (e.g. redshift) to an abstract latent space (Carrasco Kind & Brunner 2014). UnEZ, however, produces physically meaningful representations of data that require no supervision. Each latent space node is directly associated with a specific spectral line and wavelength, meaning the latent space can be directly interpreted and used for further scientific analysis.
The unsupervised nature of the model's training and inference means that UnEZ is effectively learning what redshift is and how to predict it with no reference to any ground truths. This unsupervised theme is what makes UnEZ far less labor intensive to use and less prone to biases introduced by templates. However, like all data-driven models, unsupervised neural networks are not immune to all biases. For example, the choice of lines to fit can influence the model's performance. Without enough lines to fit, the model cannot predict an accurate redshift. Also, unsupervised neural networks are prone to the biases of the training data itself, such as selection effects. Fortunately, large-scale surveys help mitigate this issue by offering diverse and representative samples of astronomical objects for training.
In terms of performance, UnEZ outperforms conventional redshift estimation methods. Its redshift prediction precision and accuracy are slightly better than tools such as MARZ which cited a 3.5% outlier fraction on high SNR spectra at z < 1. However, the model's lack of reliance on template spectra or redshift labels makes it a more appealing solution to the redshift estimation problem.
Some physics priors described in Section 3.1 are specific to the spectroscopic instrument. For example, the maximum expected redshift, redshift sampling resolution, and maximum observed wavelength of the spectrograph are all specific to the instrument. The expected line list can also change depending on the redshift range being observed and wavelength range of the instrument. All of these parameters can be tuned in a configuration file, which should make adapting UnEZ to a new instrument straightforward and potentially allow it to be used in more diverse cases than traditional redshift estimation methods.
Like most unsupervised models, UnEZ requires a large amount of data for training. Unsupervised neural networks learn directly from the distribution of the dataset. This means they require large amounts of data to properly probe the parameter-space without overtraining. Luckily, larger surveys such as DESI (Levi et al. 2019) and SDSS (Almeida et al. 2023) are perfect candidates for training UnEZ.
5.3 Future Endeavors
The fully unsupervised aspect of the model gives it the flexibility needed for new and unseen redshift regimes. If a new telescope, such as JWST, allows us to peer into the previously unseen universe, new templates are required for conventional redshift estimation algorithms. However, UnEZ's lack of templates is expected to allow quick and easy deployment on new surveys conducted with instruments such as JWST. This not only saves time but also reduces human-labor and biases inherent to template spectra.
UnEZ demonstrates that templates and vetting spectral fits by hand are not required for effective redshift prediction. There is plenty of room for improvement however. The biggest drawback of UnEZ that can be remedied is the line strength prediction. Currently the model uses L2 normalization throughout its pipeline, but there are other normalization techniques that could potentially be more effective for line strength prediction. The relationship between line strength prediction and redshift estimation accuracy is not yet fully understood. Future work will benefit greatly from understanding how line strength predictions directly impact redshift performance.
Another area for improvement is reducing reliance on manual hy-
Abd et al.
perparameter tuning such as the top-k redshifts used for learning during training as mentioned in Section 3.5. This requires more tuning which counteracts the unsupervised theme of the model. Some of the hyperparameters can potentially be set to automatically scale with other parameters such as maximum expected redshift and number of redshift bins in each spectrum. This can allow the model to operate with even less tuning than is currently required.
Beyond architectural changes, auxiliary pipelines can also be set up to separate interesting objects during inference. This can be done by either clustering the latent space or referencing another redshift catalog for disagreements. Some objects have already been found manually such as the superimposed galaxies and FeLoBAL quasar in Figure 9.
Finding outliers in large datasets utilizing UnEZ's predictions is the ideal next step. UnEZ outputs a wide range of data that should organically reveal interesting outliers in the SDSS dataset. Expanding the search for outliers beyond the current SDSS dataset will verify UnEZ's ability to directly encode physical properties of spectra spanning across different telescopes, datasets, and redshift regimes.
ACKNOWLEDGEMENTS
This work was performed on the OzSTAR national facility at Swinburne University of Technology. The OzSTAR program receives funding in part from the Astronomy National Collaborative Research Infrastructure Strategy (NCRIS) allocation provided by the Australian Government, and from the Victorian Higher Education State Investment Fund (VHESIF) provided by the Victorian Government.
Funding for the Sloan Digital Sky Survey V has been provided by the Alfred P. Sloan Foundation, the Heising-Simons Foundation, the National Science Foundation, and the Participating Institutions. SDSS acknowledges support and resources from the Center for High-Performance Computing at the University of Utah. SDSS telescopes are located at Apache Point Observatory, funded by the Astrophysical Research Consortium and operated by New Mexico State University, and at Las Campanas Observatory, operated by the Carnegie Institution for Science. The SDSS web site is www.sdss.org.
SDSS is managed by the Astrophysical Research Consortium for the Participating Institutions of the SDSS Collaboration, including the Carnegie Institution for Science, Chilean National Time Allocation Committee (CNTAC) ratified researchers, Caltech, the Gotham Participation Group, Harvard University, Heidelberg University, The Flatiron Institute, The Johns Hopkins University, L'Ecole polytechnique fédérale de Lausanne (EPFL), Leibniz-Institut für Astrophysik Potsdam (AIP), Max-Planck-Institut für Astronomie (MPIA Heidelberg), Max-Planck-Institut für Extraterrestrische Physik (MPE), Nanjing University, National Astronomical Observatories of China (NAOC), New Mexico State University, The Ohio State University, Pennsylvania State University, Smithsonian Astrophysical Observatory, Space Telescope Science Institute (STScI), the Stellar Astrophysics Participation Group, Universidad Nacional Autónoma de México, University of Arizona, University of Colorado Boulder, University of Illinois at Urbana-Champaign, University of Toronto, University of Utah, University of Virginia, Yale University, and Yunnan University.
DATA AVAILABILITY
This work uses publicly available spectra from the Sloan Digital Sky Survey Data Release 18 (Almeida et al. 2023), accessible through the SDSS Science Archive Server. The UnEZ predictions and code will be shared on reasonable request.
REFERENCES
Abdul Karim M., et al., 2025, Physical Review D, 112
Aihara H., et al., 2011, ApJS, 193, 29
Alexander D. M., et al., 2023, AJ, 165, 124
Almeida A., et al., 2023, ApJS, 267, 44
Anand A., et al., 2024, AJ, 168, 124
Baldry I. K., 2018, Reinventing the slide rule for redshifts: the case for logarithmic wavelength shift (arXiv:1812.05135), https://arxiv.org/abs/1812.05135
Baldry I. K., et al., 2014, Monthly Notices of the Royal Astronomical Society, 441, 2440
Baldwin J. A., Phillips M. M., Terlevich R., 1981, PASP, 93, 5
Benítez N., 2000, ApJ, 536, 571
Bezanson R., et al., 2016, ApJ, 822, 30
Bolton A. S., et al., 2012, The Astronomical Journal, 144, 144
Bourlard H., Kamp Y., 1988, Biological cybernetics, 59, 291
Brown T. B., et al., 2020, Language Models are Few-Shot Learners (arXiv:2005.14165), https://arxiv.org/abs/2005.14165
Carrasco Kind M., Brunner R. J., 2014, Monthly Notices of the Royal Astronomical Society, 438, 3409
Choi H., Leighly K. M., Terndrup D. M., Dabbieri C., Gallagher S. C., Richards G. T., 2022, The Astrophysical Journal, 937, 74
Colless M., et al., 2003, arXiv e-prints, pp astro-ph/0306581
Collister A., Lahav O., 2004, Publications of the Astronomical Society of the Pacific, 116, 345
DESI Collaboration et al., 2026, Data Release 1 of the Dark Energy Spectroscopic Instrument (arXiv:2503.14745), https://arxiv.org/abs/2503.14745
Damadi S., Moharrer G., Cham M., 2023, The Backpropagation algorithm for a math student (arXiv:2301.09977), https://arxiv.org/abs/2301.09977
Dieleman S., Willett K. W., Dambre J., 2015, Monthly Notices of the Royal Astronomical Society, 450, 1441
Eisenstein D. J., et al., 2001, AJ, 122, 2267
Fluke C. J., Jacobs C., 2019, WIREs Data Mining and Knowledge Discovery, 10
Glazebrook K., Offer A. R., Deeley K., 1998, The Astrophysical Journal, 492, 98
Hewett P. C., Wild V., 2010, Monthly Notices of the Royal Astronomical Society, 405, 2302
Hinton S., Davis T. M., Lidman C., Glazebrook K., Lewis G., 2016, Astronomy and Computing, 15, 61
Hogg D. W., 2000, Distance measures in cosmology (arXiv:astro-ph/9905116), https://arxiv.org/abs/astro-ph/9905116
Huchra J. P., Geller M. J., de Lapparent V., Burg R., 1988, in Audouze J., Pelletan M. C., Szalay A., Zel'dovich Y. B., Peebles P. J. E., eds, IAU Symposium Vol. 130, Large Scale Structures of the Universe. p. 105
Humason M. L., Mayall N. U., Sandage A. R., 1956, AJ, 61, 97
Kewley L. J., Dopita M. A., Sutherland R. S., Heisler C. A., Trevena J., 2001, ApJ, 556, 121
Kewley L. J., Groves B., Kauffmann G., Heckman T., 2006, Monthly Notices of the Royal Astronomical Society, 372, 961
Kohonen T., 1982, Biological Cybernetics, 43, 59
Kollatschny W., Zetzl M., Dietrich M., 2006, A&A, 454, 459
Lan T.-W., et al., 2023, ApJ, 943, 68
Leighly K. M., Gallagher S. C., Choi H., Terndrup D. M., Voelker J. R., Richards G. T., Morabito L. K., 2025, Balmer Absorption in Iron
Low-Ionization Broad Absorption Line Quasars (arXiv:2509.07611), https://arxiv.org/abs/2509.07611
Levi M. E., et al., 2019, The Dark Energy Spectroscopic Instrument (DESI) (arXiv:1907.10688), https://arxiv.org/abs/1907.10688
Liu W., et al., 2019, Monthly Notices of the Royal Astronomical Society, 483, 4774
Massarotti M., Iovino A., Buzzoni A., 2001, Astronomy & Astrophysics, 368, 74
Miller A. S., 1993, Vistas in Astronomy, 36, 141
Molino A., et al., 2014, Monthly Notices of the Royal Astronomical Society, 441, 2891
Mong Y.-L., et al., 2023, MNRAS, 518, 752
Murtagh F., 1995, Pattern Recognition Letters, 16, 399
Newman J. A., Gruen D., 2022, Annual Review of Astronomy and Astrophysics, 60, 363
Patnaik R., Kartaltepe J. S., Binu C., 2025, The Astrophysical Journal, 988, 139
Richards G. T., et al., 2002, AJ, 123, 2945
Ross N. P., et al., 2012, ApJS, 199, 3
Rubner Y., Tomasi C., Guibas L., 2000, International Journal of Computer Vision, 40, 99
Rumelhart D. E., Hinton G. E., Williams R. J., 1986, Nature, 323, 533
Scourfield M., Saintonge A., de Mijolla D., Viti S., 2023, Monthly Notices of the Royal Astronomical Society, 526, 3037
Sloan Digital Sky Survey 2008, Table of Spectral Lines Used in SDSS spectrold, https://classic.sdss.org/dr6/algorithms/linestable.php
Smee S. A., et al., 2013, The Astronomical Journal, 146, 32
Sofue Y., Rubin V., 2001, ARA&A, 39, 137
Strauss M. A., et al., 2002, AJ, 124, 1810
Tegmark M., et al., 2004, The Astrophysical Journal, 606, 702
Teimoorinia H., Archinuk F., Woo J., Shishehchi S., Bluck A. F. L., 2022, The Astronomical Journal, 163, 71
Tonry J., Davis M., 1979, AJ, 84, 1511
Vaswani A., Shazeer N., Parmar N., Uszkoreit J., Jones L., Gomez A. N., Kaiser L., Polosukhin I., 2023, Attention Is All You Need (arXiv:1706.03762), https://arxiv.org/abs/1706.03762
Veilleux S., 2002, Spectroscopic Diagnostics for AGNs (arXiv:astro-ph/0201118), https://arxiv.org/abs/astro-ph/0201118
Wu Q., Shen Y., 2022, The Astrophysical Journal Supplement Series, 263, 42
York D. G., et al., 2000, AJ, 120, 1579
Zhong F., et al., 2024, Monthly Notices of the Royal Astronomical Society, 532, 643
APPENDIX A: SPECTRAL LINE LIST
Table A1 lists the spectral lines supplied to UnEZ as physics priors. Rest-frame vacuum wavelengths are taken from the SDSS spectro1d line table (Sloan Digital Sky Survey 2008). The index column gives the position of each line in the configuration file, which is also the index of the corresponding node in UnEZ's latent space.
Each line is assigned a classification that determines the activation function applied to its predicted strength (Section 3.3): emission-only lines (E) are passed through a ReLU, absorption-only lines (A) through a negative ReLU, and lines that may appear in either emission or absorption (B) through a linear activation. Classifications were assigned based on the physical origin of each transition rather than being taken from any catalogue: nebular forbidden lines are restricted to emission, stellar photospheric features to absorption, and resonance lines that may appear in absorption in broad absorption line quasars are left unconstrained. The four sky lines listed by Sloan Digital Sky Survey (2008) are not fitted; they are masked during preprocessing (Section 3.2).
Table A1. Spectral lines used as physics priors in UnEZ. Wavelengths are rest-frame vacuum values from the SDSS SPECTRO1d line table (Sloan Digital Sky Survey 2008). Classifications: E = emission-only, A = absorption-only, B = emission or absorption.
| # | Species | ( ) | Cl. | # | Species | ( ) | Cl. |
|---|---|---|---|---|---|---|---|
| 1 | O v I | 1033.82 | B | 23 | H | 4341.68 | B |
| 2 | Ly | 1215.24 | B | 24 | [O m] | 4364.44 | E |
| 3 | N v | 1240.81 | B | 25 | H | 4862.68 | B |
| 4 | O i | 1305.53 | E | 26 | [O m] | 4932.60 | E |
| 5 | C ii | 1335.31 | E | 27 | [O m] | 4960.30 | E |
| 6 | Si iv | 1397.61 | E | 28 | [O m] | 5008.24 | E |
| 7 | Si iv + O iv] | 1399.80 | E | 29 | [O i] | 6302.05 | E |
| 8 | C iv | 1549.48 | B | 30 | [O i] | 6365.54 | E |
| 9 | He II | 1640.40 | B | 31 | N i | 6529.03 | E |
| 10 | O III] | 1665.85 | E | 32 | [N ii] | 6549.86 | E |
| 11 | Al III | 1857.40 | B | 33 | H | 6564.61 | B |
| 12 | C III] | 1908.73 | E | 34 | [N ii] | 6585.27 | E |
| 13 | C II] | 2326.00 | E | 35 | [S ii] | 6718.29 | E |
| 14 | Ne iv | 2439.50 | B | 36 | [S ii] | 6732.67 | E |
| 15 | Mg II | 2799.12 | B | 37 | Ca II K | 3934.78 | A |
| 16 | [Ne v] | 3346.79 | B | 38 | Ca II H | 3969.59 | A |
| 17 | Ne vi | 3426.85 | B | 39 | G band | 4305.61 | A |
| 18 | [O u] | 3727.09 | E | 40 | Mg b | 5176.70 | A |
| 19 | [O u] | 3729.88 | E | 41 | Na D | 5895.60 | A |
| 20 | He I | 3889.00 | B | 42 | Ca II | 8500.36 | A |
| 21 | [S ii] | 4072.30 | E | 43 | Ca II | 8544.44 | A |
| 22 | H | 4102.89 | B | 44 | Ca II | 8664.52 | A |
APPENDIX B: BRUTE FORCE EXPERIMENT
UnEZ deterministically estimates redshift from a neural network line strength prediction. As posed in Section 3.4, we test whether the line strengths can be estimated deterministically. Here we show why a neural network that has learned the distribution of spectra performs better than brute force fitting every line at every redshift.
The brute force method we use measures , indicated in equation B1
at trial redshifts and line widths . At a fixed z and the model in Equation B1 is linear in the line strengths. Each Gaussian is a fixed basis vector, and the spectrum is modeled as a linear combination of them. Therefore, the line strengths that minimize are given by a single linear least-squares projection of the spectrum onto this basis, with no iteration required. This makes the computation fast and exact at each trial. It recovers the optimal amplitudes at every trial (z, ), making it the strongest non-learned counterpart to UnEZ's decoder rather than an approximation of it.
This is the same linear-in-amplitude method used by traditional pipelines. The SDSS redshift pipeline (Bolton et al. 2012) and PCAz (Glazebrook et al. 1998) project each spectrum onto a fixed basis of PCA eigenspectra at each trial redshift. UnEZ, the brute force method, and these traditional algorithms differ only in basis and in how the amplitudes are obtained. The brute force projects onto a fixed line basis, SDSS onto fixed eigenspectra, and UnEZ predicts per-object amplitudes over the physics-constrained line set with an encoder trained on the distribution of real spectra. Comparing UnEZ against this baseline tests the contribution of that learned prediction.
The same preprocessing pipeline was used for both UnEZ and the brute force method. We also sampled the same redshifts as UnEZ for the brute force fit so the two methods can easily be compared. The
Abd et al.
brute force method samples 32 trial line widths across the same line width range as UnEZ.
100,000 randomly selected spectra were chosen across the entire SNR range for fitting. Of those, approximately 52,500 fall above the SNR>3 threshold as seen in Figure B1. We found that the brute force method is much more prone to fitting skylines and confusing lines than UnEZ, achieving an outlier fraction of approximately 21% as opposed to UnEZ's 3.9% at the same SNR range. Additionally, Figure B2 shows that UnEZ performs better than the brute force method in all performance metrics across the entire SNR range. Not only does UnEZ consistently perform better, but the performance tends towards peak performance at a lower SNR than the brute force. Although this method is very efficient at individual trial redshifts and line widths, due to the hundreds of thousands of trials it ends up far less efficient than UnEZ. UnEZ's inference takes approximately 25 milliseconds per spectrum, while the brute force method takes approximately 250 milliseconds. This order of magnitude increase in inference speed and redshift prediction performance makes UnEZ a much more viable candidate for modern large-scale surveys.
This experiment does systematically calculate the redshift with the lowest , however, that does not always lead to the correct redshift. If skyline or noise contamination is too strong, can be lower when fitting skylines as they drown out spectral features native to the observed object. UnEZ on the other hand has learned from the distribution of spectra, and can recognize and encode spectral features native to the object being observed, rather than just searching for the strongest features and fitting to those.
We conclude that the neural network in UnEZ's architecture is critical to ensuring the pipeline can effectively predict redshift as it reduces the likelihood of fitting noise or confusing different lines while also reducing the amount of compute time needed. This experiment serves to uphold the need for UnEZ's machine learning architecture.
This paper has been typeset from a TX/LX file prepared by the author.

Figure B1. As Figure 5 but for the brute force method. Line confusion degeneracies and skyline contamination become much more prevalent using the brute force method.
Abd et al.

Figure B2. As Figure 6 with the brute force method plotted as well. Only 100,000 random spectra were selected for each method due to the long compute time required for the brute force method. UnEZ consistently performs better across the entire SNR range and converges toward peak performance at a lower SNR.