303.6. Galaxy stellar mass regression#
303.6. Galaxy stellar mass regression¶
For the Rubin Science Platform at data.lsst.cloud.
Data Release: Data Preview 2
Container Size: Large
LSST Science Pipelines version: r30.0.11
Last verified to run: 2026-10-26
Repository: github.com/lsst/tutorial-notebooks
DOI: 10.11578/rubin/dc.20250909.20
Learning objective: Train a scikit-learn regression model to estimate galaxy stellar mass from DP2 photometry, structural measurements, and photometric redshift, using full SED-fitting stellar masses from an external catalog as ground truth, then apply it across the full field using DP2's own native photometric redshifts.
LSST data products: Object table, object_photoz (LSDB)
Packages: lsst.rsp, lsdb, astroquery, astropy.cosmology, scikit-learn, numpy, pandas, matplotlib
Credit:
Originally developed by the Rubin Community Science team.
Photometric redshifts from DP2's own object_photoz catalog (see the 310-series tutorials on photometric redshifts).
Stellar masses from Weaver et al. 2022, ApJS, 258, 11 (the COSMOS2020 catalog, VizieR catalog J/ApJS/258/11).
Please consider acknowledging them if this notebook is used for the preparation of journal articles, software releases, or other notebooks.
Get Support: Everyone is encouraged to ask questions or raise issues in the Support Category of the Rubin Community Forum. Rubin staff will respond to all questions posted there.
1. Introduction¶
The two previous notebooks in this series classify and cluster DP2 galaxies by morphology. This notebook explores a different application: estimating a galaxy's stellar mass, a continuous physical quantity, from its photometry, structure, and redshift. Unlike classification (a discrete label) or clustering (an unsupervised grouping), this is a regression problem, the third major category of machine learning methods. The model used throughout this notebook is a RandomForestRegressor.
Estimating stellar mass generally requires fitting a galaxy's full spectral energy distribution (SED) against stellar population synthesis models, which is the approach used to derive the COSMOS2020 stellar masses used as ground truth here. These estimates serve as training labels for a machine-learning model that predicts stellar mass from the observables available in DP2, including photometry, structural properties, and photometric redshift. The aim is to learn the relationship between these observables and stellar mass, making it possible to estimate stellar masses for galaxies beyond the COSMOS2020 sample for which no reference mass is available.
Unlike the previous two notebooks, the redshift used here comes from DP2's own object_photoz catalog rather than a cross-match to COSMOS2020. DP2 provides photometric redshifts for every object from six different estimators (BPZ, DNF, FlexZBoost, GPz, kNN, TPZ) through a catalog accessed separately from the Object table (see the 310-series tutorials on photometric redshifts for a dedicated introduction). These estimates are noisier than COSMOS2020's own deep, many-band SED-fit redshifts, but they are the only redshift available for the vast majority of the field.
1.1. Import packages¶
Import common scientific analysis packages numpy, pandas, and matplotlib.
Import LSST Science Pipelines package utilities for remote data access, lsst.rsp, and lsst.utils.plotting for the standard Rubin plot style.
Import lsdb and upath to access DP2's native photometric redshift catalog, and astroquery to cross-match against the external COSMOS2020 catalog for stellar mass ground truth.
Import astropy.cosmology to convert angular and apparent measurements to physical units, and scikit-learn utilities for splitting data and fitting regression models.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import lsdb
from upath import UPath
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy.cosmology import Planck18 as cosmo
from astroquery.vizier import Vizier
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from lsst.rsp import RSPDiscovery
from lsst.utils.plotting import set_rubin_plotstyle
set_rubin_plotstyle()
plt.rcParams["figure.dpi"] = 150
np.random.seed(1)
1.2. Define parameters and functions¶
Set up the TAP service client used for data access throughout the notebook, and the sky position and radius of the COSMOS field used for every query and cross-match below.
discovery = RSPDiscovery("dp2")
tap_service = discovery.get_tap_client()
field_centre = SkyCoord(ra=150.1, dec=2.2, unit="deg")
field_radius = 0.8
Define a helper function to query VizieR, cycling through known mirrors of the service in case the primary server is unreachable.
VIZIER_MIRRORS = [
"vizier.cds.unistra.fr", "vizier.cfa.harvard.edu",
"vizier.china-vo.org", "vizier.idia.ac.za", "vizier.nao.ac.jp",
]
def query_vizier(columns, catalog, *region_args, **region_kwargs):
"""Query VizieR, trying each known mirror in turn."""
errors = []
for server in VIZIER_MIRRORS:
survey = Vizier(columns=columns, catalog=catalog, row_limit=-1, vizier_server=server)
try:
return survey.query_region(*region_args, catalog=catalog, **region_kwargs)[0]
except Exception as error:
errors.append(f"{server}: {error}")
details = " | ".join(errors)
raise RuntimeError(
"Could not reach VizieR on any known mirror. This may be a wider CDS "
f"outage, so try again later. Details: {details}") from None
2. Query for galaxy photometry and structure in the COSMOS field¶
Query the Object table in the same 0.8 degree radius around the COSMOS field centre, and with the same clean-sample cuts, used by the previous two notebooks: refExtendedness = 1 to exclude point sources, a signal-to-noise cut in each of g, r, and i, and the same Sersic-fit-quality flags. Include objectId, needed to join against the photometric redshift catalog in the next section.
query = '''SELECT objectId, coord_ra, coord_dec, sersic_index, sersic_reff_major,
sersic_reff_minor, g_cModelMag, r_cModelMag, i_cModelMag,
g_cModelMag - r_cModelMag AS g_minus_r, r_cModelMag - i_cModelMag AS r_minus_i
FROM dp2.Object
WHERE CONTAINS(POINT('ICRS', coord_ra, coord_dec), CIRCLE('ICRS', {}, {}, {}))=1
AND refExtendedness = 1
AND g_cModel_flag = 0
AND r_cModel_flag = 0
AND i_cModel_flag = 0
AND g_cModelFlux/g_cModelFluxErr > 10
AND r_cModelFlux/r_cModelFluxErr > 10
AND i_cModelFlux/i_cModelFluxErr > 10
AND i_cModelMag < 23
AND sersic_unknown_flag = 0
AND sersic_no_data_flag = 0
'''.format(field_centre.ra.deg, field_centre.dec.deg, field_radius)
job = tap_service.submit_job(query)
job.run()
job.wait(phases=["COMPLETED", "ERROR"])
assert job.phase == "COMPLETED"
dp2_tab = job.fetch_result().to_table()
job.delete()
print(f"Retrieved {len(dp2_tab)} DP2 objects")
Retrieved 69157 DP2 objects
3. Join against DP2's own photometric redshift catalog¶
DP2's photometric redshifts are found in a separate, LSDB-formatted catalog, object_photoz, not in the Object table itself. Open it with lsdb, restrict it to the same field with a cone search, and join it to the Object query above on objectId. Use the FlexZBoost estimator's point estimate, fzboost_z_best -- one of six estimators available, and the one RTN-124 identifies as the most performant for DP2; see the 310-series tutorials for the full list and how to compare them.
dp2 = dp2_tab.to_pandas()
dp2_renamed = dp2.rename(columns={"coord_ra": "ra", "coord_dec": "dec"})
dp2_lsdb = lsdb.from_dataframe(dp2_renamed, catalog_name="object")
base_path = UPath("/rubin/lsdb_data/dp2")
pz_cat = lsdb.open_catalog(
base_path / "object_photoz", columns=["objectId", "ra", "dec", "fzboost_z_best"])
pz_cat_cone = pz_cat.cone_search(
ra=field_centre.ra.deg, dec=field_centre.dec.deg, radius_arcsec=field_radius * 3600.0)
joined = pz_cat_cone.join(
dp2_lsdb, left_on="objectId", right_on="objectId", suffix_method="all_columns")
dpz = pd.DataFrame(joined.compute())
assert len(dpz) > 0, "FlexZBoost photometric redshift join returned no rows"
print(f"Joined {len(dpz)} DP2 objects with a FlexZBoost photometric redshift")
Joined 69157 DP2 objects with a FlexZBoost photometric redshift
Rename the joined columns back to their original names, cast them to a consistent numeric type, and keep only objects with a usable redshift.
dpz = dpz.rename(columns={
"fzboost_z_best_object_photoz": "zphot", "objectId_object": "objectId",
"sersic_index_object": "sersic_index", "sersic_reff_major_object": "sersic_reff_major",
"sersic_reff_minor_object": "sersic_reff_minor", "g_cModelMag_object": "g_cModelMag",
"r_cModelMag_object": "r_cModelMag", "i_cModelMag_object": "i_cModelMag",
"g_minus_r_object": "g_minus_r", "r_minus_i_object": "r_minus_i",
"ra_object": "coord_ra", "dec_object": "coord_dec",
})
numeric_cols = ["zphot", "sersic_index", "sersic_reff_major", "sersic_reff_minor",
"g_cModelMag", "r_cModelMag", "i_cModelMag", "g_minus_r", "r_minus_i",
"coord_ra", "coord_dec"]
dpz[numeric_cols] = dpz[numeric_cols].astype("float64")
dpz = dpz[dpz["zphot"] > 0.01].reset_index(drop=True)
print(f"DP2 galaxies with a usable FlexZBoost redshift: {len(dpz)}")
DP2 galaxies with a usable FlexZBoost redshift: 69157
4. Cross-match against COSMOS2020 for stellar mass ground truth¶
DP2 has no stellar mass product of its own, so cross-match against the COSMOS2020 catalog (Weaver et al. 2022, VizieR catalog J/ApJS/258/11) for loglpMassmed, the median stellar mass in log solar mass from a full LePhare SED fit. Keep only objects with FlagCOMBINED = 0 and a reasonably narrow stellar mass confidence interval (B_loglpMassmed - b_loglpMassmed < 0.5 dex). This cross-match is for the training labels only: the redshift used throughout this notebook is still DP2's own FlexZBoost estimate from Section 3, not COSMOS2020's.
Warning: This VizieR query can take a few minutes to run.
cosmos2020_cat = query_vizier(
["RAJ2000", "DEJ2000", "loglpMassmed", "b_loglpMassmed", "B_loglpMassmed", "FlagCOMBINED"],
"J/ApJS/258/11/classic", field_centre, radius=field_radius * u.deg)
assert len(cosmos2020_cat) > 0, "COSMOS2020 VizieR query returned no rows"
coord_cosmos2020 = SkyCoord(
ra=np.array(cosmos2020_cat["RAJ2000"]), dec=np.array(cosmos2020_cat["DEJ2000"]), unit="deg")
coord_dpz = SkyCoord(ra=dpz["coord_ra"].values, dec=dpz["coord_dec"].values, unit="deg")
idx_cosmos2020, separation, _ = coord_dpz.match_to_catalog_sky(coord_cosmos2020)
is_matched = np.array(separation < 1.0 * u.arcsec)
dpz["logmass"] = np.nan
dpz["mass_lo"] = np.nan
dpz["mass_hi"] = np.nan
dpz["quality_flag"] = -1
dpz.loc[is_matched, "logmass"] = np.array(
cosmos2020_cat["loglpMassmed"])[idx_cosmos2020[is_matched]]
dpz.loc[is_matched, "mass_lo"] = np.array(
cosmos2020_cat["b_loglpMassmed"])[idx_cosmos2020[is_matched]]
dpz.loc[is_matched, "mass_hi"] = np.array(
cosmos2020_cat["B_loglpMassmed"])[idx_cosmos2020[is_matched]]
dpz.loc[is_matched, "quality_flag"] = np.array(
cosmos2020_cat["FlagCOMBINED"])[idx_cosmos2020[is_matched]]
mass_confidence_interval = dpz["mass_hi"] - dpz["mass_lo"]
dpz["has_ground_truth"] = (
(dpz["quality_flag"] == 0) & dpz["logmass"].notna()
& (mass_confidence_interval < 0.5) & (dpz["logmass"] > 6))
print(f"DP2 galaxies with a good-quality stellar mass label: {dpz['has_ground_truth'].sum()}")
print(f"DP2 galaxies with no stellar mass label: {(~dpz['has_ground_truth']).sum()}")
DP2 galaxies with a good-quality stellar mass label: 40325 DP2 galaxies with no stellar mass label: 28832
5. Convert to physical units and build features¶
Convert the Sersic effective radius and apparent magnitude to physical units (kpc, absolute magnitude) using the FlexZBoost redshift, following the same approach as 303.4 and 303.5. Build the same ellipticity measure used there too. Do this for every galaxy, not just the labeled ones.
Warning: As in 303.4 and 303.5,
sersic_reff_major/sersic_reff_minorin theObjecttable are too small by a factor of $2\ln(2) \approx 1.386$; the cell below corrects for this before computingreff_kpc(see the DP2 known issues documentation).
sersic_reff_correction = 2 * np.log(2)
dpz["sersic_reff_major"] = dpz["sersic_reff_major"] * sersic_reff_correction
dpz["sersic_reff_minor"] = dpz["sersic_reff_minor"] * sersic_reff_correction
kpc_per_arcsec = cosmo.kpc_proper_per_arcmin(dpz["zphot"].values).to(u.kpc / u.arcsec).value
dpz["reff_kpc"] = dpz["sersic_reff_major"] * kpc_per_arcsec
distance_modulus = cosmo.distmod(dpz["zphot"].values).value
dpz["abs_mag_i"] = dpz["i_cModelMag"] - distance_modulus
reff_major = dpz["sersic_reff_major"]
reff_minor = dpz["sersic_reff_minor"]
dpz["ellipticity"] = (reff_major - reff_minor) / (reff_major + reff_minor)
base_cols = ["g_minus_r", "r_minus_i", "abs_mag_i", "zphot"]
structural_cols = ["sersic_index", "reff_kpc", "ellipticity"]
dpz = dpz.replace([np.inf, -np.inf], np.nan)
labeled = dpz[dpz["has_ground_truth"]].dropna(
subset=base_cols + structural_cols + ["logmass"]).reset_index(drop=True)
print(f"Labeled galaxies available for training and testing: {len(labeled)}")
Labeled galaxies available for training and testing: 40325
6. Prepare the training and test sets¶
Split the labeled sample into training and test sets before fitting anything, so that no information from the test set leaks into model selection.
train_idx, test_idx = train_test_split(labeled.index.values, test_size=0.2, random_state=1)
y_train = labeled.loc[train_idx, "logmass"].values
y_test = labeled.loc[test_idx, "logmass"].values
print(f"Training samples: {len(train_idx)}")
print(f"Test samples: {len(test_idx)}")
Training samples: 32260 Test samples: 8065
7. Fit a baseline model using color, magnitude, and redshift¶
Fit a RandomForestRegressor using the two colors, the absolute i-band magnitude, and the FlexZBoost redshift. Evaluate with the root-mean-square error (RMSE) in dex.
X_train_base = labeled.loc[train_idx, base_cols].values
X_test_base = labeled.loc[test_idx, base_cols].values
model_base = RandomForestRegressor(n_estimators=200, random_state=1)
model_base.fit(X_train_base, y_train)
y_pred_base = model_base.predict(X_test_base)
rmse_base = np.sqrt(mean_squared_error(y_test, y_pred_base))
print(f"Color + magnitude + redshift - RMSE: {rmse_base: .4f} dex")
Color + magnitude + redshift - RMSE: 0.2508 dex
8. Does adding structural information improve the prediction?¶
Fit a second RandomForestRegressor, with additional structural information provided by the Sersic index, effective radius, and ellipticity, and compare directly.
all_cols = base_cols + structural_cols
X_train_all = labeled.loc[train_idx, all_cols].values
X_test_all = labeled.loc[test_idx, all_cols].values
model_all = RandomForestRegressor(n_estimators=200, random_state=1)
model_all.fit(X_train_all, y_train)
y_pred_all = model_all.predict(X_test_all)
rmse_all = np.sqrt(mean_squared_error(y_test, y_pred_all))
print(f"Color + magnitude + redshift: RMSE: {rmse_base: .4f} dex")
print(f"Color + magnitude + redshift + structural: RMSE: {rmse_all: .4f} dex")
Color + magnitude + redshift: RMSE: 0.2508 dex Color + magnitude + redshift + structural: RMSE: 0.2401 dex
The structural measurements give a small ($\sim 6$ per cent) improvement in the RMSE over the previous result.
Look at the feature importances to see which measurements the model relies on.
importances = pd.Series(model_all.feature_importances_, index=all_cols).sort_values()
plt.figure(figsize=(5, 4), layout="constrained")
plt.barh(importances.index, importances.values, color="k")
plt.xlabel("feature importance")
plt.grid(True, alpha=0.3)
Figure: Random forest feature importances for the model including structural measurements.
Now look at the predicted-versus-true stellar mass of both models.
fig, axes = plt.subplots(1, 2, figsize=(10, 4.5), sharex=True, sharey=True, layout="constrained")
titles = ["color + magnitude + redshift", "+ structural"]
for ax, y_pred, title in zip(axes, [y_pred_base, y_pred_all], titles):
ax.scatter(y_test, y_pred, s=8, alpha=0.4, color="k")
lims = [labeled["logmass"].min(), labeled["logmass"].max()]
ax.plot(lims, lims, color="C1", linewidth=2)
ax.set_xlabel("true log stellar mass (COSMOS2020)")
ax.set_title(title)
ax.grid(True, alpha=0.3)
axes[0].set_ylabel("predicted log stellar mass");
Figure: Predicted versus true log stellar mass on the test set, for the model using color, magnitude, and redshift alone (left) and with structural measurements added (right).
The + structural model shows visibly less scatter around the one-to-one line than color + magnitude + redshift alone, consistent with the lower RMSE measured above.
9. Apply the model to the full field¶
Apply the better of the two models -- color + magnitude + redshift + structural (model_all) -- to every DP2 galaxy in the field.
As a sanity check, compare the predicted stellar mass distribution for the unlabeled galaxies against the true stellar mass distribution of the labeled sample the model was trained on.
unlabeled = dpz[~dpz["has_ground_truth"]].dropna(subset=all_cols).reset_index(drop=True)
X_unlabeled = unlabeled[all_cols].values
unlabeled["logmass_pred"] = model_all.predict(X_unlabeled)
print(f"Predicted a stellar mass for {len(unlabeled)} DP2 galaxies with no COSMOS2020 mass label")
plt.figure(figsize=(5, 4), layout="constrained")
plt.hist(labeled["logmass"], bins=30, density=True, histtype="step", linewidth=2,
label="training sample (true)")
plt.hist(unlabeled["logmass_pred"], bins=30, density=True, histtype="step", linewidth=2,
label="unlabeled sample (predicted)")
plt.xlabel("log stellar mass")
plt.ylabel("normalized number of galaxies")
plt.legend()
plt.grid(True, alpha=0.3)
Predicted a stellar mass for 28832 DP2 galaxies with no COSMOS2020 mass label
Figure: Normalized log stellar mass distribution for the training sample (true values) and the unlabeled full-field sample (model predictions), as a sanity check that the predicted distribution is consistent with the labeled sample the model was trained on.
Summary¶
This notebook trains a random forest regressor to estimate galaxy stellar mass from DP2 photometry, color, and structural measurements, using COSMOS2020 SED-fit stellar masses as ground truth and DP2's own FlexZBoost photometric redshift throughout, including for the full-field application. Adding structural measurements to color, magnitude, and redshift gives a modest but real reduction in RMSE, and the model's predicted stellar mass distribution for the full, unlabeled field is consistent with the distribution of the labeled training sample.