303.4. Galaxy morphology classification#
303.4. Galaxy morphology classification¶
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 simple neural network classifier to separate early-type from late-type galaxies in DP2 Object table measurements, using an independent, publicly available morphology catalog as ground truth.
LSST data products: Object table, object_photoz (LSDB)
Packages: lsst.rsp, lsdb, astroquery, astropy.cosmology, torch, scikit-learn, numpy, pandas, matplotlib
Credit:
Originally developed by the Rubin Community Science team.
Morphological classification labels from Tasca et al. 2009, A&A, 503, 379 (VizieR catalog VII/265).
Photometric redshifts from DP2's own object_photoz catalog (see the 310-series tutorials on photometric redshifts).
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¶
Classifying galaxies by morphology -- broadly, early-type (elliptical, smooth, centrally concentrated) versus late-type (spiral/disk, extended, often star-forming) -- is routinely used in extragalactic astronomy, and remains a useful way to split samples for many science cases. The DP2 Object table provides several measurements that correlate with morphology, including the Sersic index from a multiband profile fit and second-moment shape parameters, but it does not provide a morphological classification directly.
This notebook builds a small, labeled training set by cross-matching DP2 Object measurements in the COSMOS field against an independent, publicly available morphological catalog, then trains a simple feedforward neural network to classify early-type versus late-type galaxies from DP2 catalog measurements (photometric and structural quantities, not image cutouts) alone. The network is built in PyTorch, a widely used framework for building neural networks.
The training labels come from Tasca et al. 2009, who independently classified around 10,000 galaxies in the COSMOS field into early, spiral, and irregular types using HST-ACS imaging.
Related tutorials: See also the 303-series tutorials on galaxy science, specifically the tutorial that overviews the various galaxy photometry measurements produced by the LSST pipelines, and their science use cases.
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 Tasca et al. 2009 morphology catalog in Section 4.
Import astropy.cosmology to convert angular and apparent measurements to physical units, and torch to build and train the neural network.
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
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.metrics import balanced_accuracy_score, ConfusionMatrixDisplay
from lsst.rsp import RSPDiscovery
from lsst.utils.plotting import set_rubin_plotstyle
set_rubin_plotstyle()
plt.rcParams["figure.dpi"] = 150
torch.manual_seed(1)
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 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")
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 measurements in the COSMOS field¶
Query the Object table in a 0.8 degree radius around the COSMOS field centre for a clean sample of resolved galaxies with well-measured Sersic fits. Require refExtendedness = 1 to exclude point sources (stars) from the sample before any cross-matching happens. Also apply Tasca et al. 2009's own flux limit (I(AB) <= 23) to the whole sample. Include objectId, needed to join against the photometric redshift catalog in Section 3. Select the measurements that make up the feature vector used throughout this notebook:
sersic_index: the shape parameter of the single-component Sersic profile fit, with n = 4 corresponding to a de Vaucouleurs profile (centrally concentrated, typical of early-type galaxies) and n = 1 to an exponential profile (typical of disks).sersic_reff_major,sersic_reff_minor: the semi-major and semi-minor axis effective (half-light) radii from the same Sersic fit, in arcsec. Their ratio gives the apparent ellipticity.i_cModelMag: the i-band CModel (composite de Vaucouleurs + exponential) apparent magnitude, used as the total brightness.g_cModelMag - r_cModelMag,r_cModelMag - i_cModelMag: the g-r and r-i colors, from the same CModel photometry.
query = '''SELECT objectId, coord_ra, coord_dec, sersic_index, sersic_reff_major,
sersic_reff_minor, 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', 150.1, 2.2, 0.8))=1
AND refExtendedness = 1
AND i_cModel_flag = 0
AND g_cModel_flag = 0
AND r_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
'''
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 photometric redshift catalog, and convert to rest-frame physical quantities¶
The Sersic effective radius and the apparent magnitude are both observed-frame quantities: a galaxy's angular size and apparent brightness depend on its distance. DP2's photometric redshifts are found in a separate, LSDB-formatted catalog, object_photoz, not in the Object table itself (see the 310-series tutorials on photometric redshifts for a dedicated introduction). 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 -- with fzboost_z_err68_low and fzboost_z_err68_high giving its 68% confidence interval.
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", "fzboost_z_err68_low",
"fzboost_z_err68_high"])
pz_cat_cone = pz_cat.cone_search(
ra=field_centre.ra.deg, dec=field_centre.dec.deg, radius_arcsec=0.8 * 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 good-quality redshift: a narrow 68% confidence interval relative to (1 + z).
dpz = dpz.rename(columns={
"fzboost_z_best_object_photoz": "zphot", "fzboost_z_err68_low_object_photoz": "z_lo",
"fzboost_z_err68_high_object_photoz": "z_hi", "objectId_object": "objectId",
"sersic_index_object": "sersic_index", "sersic_reff_major_object": "sersic_reff_major",
"sersic_reff_minor_object": "sersic_reff_minor", "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", "z_lo", "z_hi", "sersic_index", "sersic_reff_major",
"sersic_reff_minor", "i_cModelMag", "g_minus_r", "r_minus_i",
"coord_ra", "coord_dec"]
dpz[numeric_cols] = dpz[numeric_cols].astype("float64")
has_good_z = (dpz["zphot"] > 0.01) & dpz["z_lo"].notna() & dpz["z_hi"].notna()
z_confidence_interval = (dpz["z_hi"] - dpz["z_lo"]) / (1 + dpz["zphot"])
dpz = dpz[has_good_z & (z_confidence_interval < 0.1)].reset_index(drop=True)
print(f"DP2 galaxies with a good-quality FlexZBoost photometric redshift: {len(dpz)}")
DP2 galaxies with a good-quality FlexZBoost photometric redshift: 63469
Convert the Sersic effective radius (arcsec) to a physical effective radius (kpc) using the angular diameter distance, and the apparent i-band magnitude to an absolute magnitude using the distance modulus, both evaluated at each galaxy's photometric redshift. Assume a flat $\Lambda$CDM cosmology (Planck Collaboration 2018).
Warning:
sersic_reff_majorandsersic_reff_minorin theObjecttable are too small by a factor of $2\ln(2) \approx 1.386$; the cell below corrects for this before computingreff_kpcandellipticity(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)
feature_cols = ["sersic_index", "reff_kpc", "ellipticity", "abs_mag_i", "g_minus_r", "r_minus_i"]
4. Cross-match against the Tasca et al. 2009 morphology catalog¶
Fetch the morphological catalog from VizieR and match it against the rest-frame DP2 sample by sky position, following the same astroquery.vizier / astropy.coordinates.SkyCoord.match_to_catalog_sky pattern as the 303-series tutorial on color selections, which cross-matches against a spectroscopic redshift catalog to validate a color selection. Information on the catalog and its contents can be found in Tasca et al. 2009. The catalog ID to search in VizieR is VII/265. Mph1 is the primary classification: 1 = early-type, 2 = spiral, 3 = irregular, 0 = unclassified. Combine spirals and irregulars into a single late-type class, giving a binary label, and drop unclassified sources.
Also require the photometric redshift to be below 0.5, a cut that keeps only the better-resolved galaxies from the Tasca et al. 2009 sample.
tasca_cat = query_vizier(["**"], "VII/265", field_centre, radius=0.8 * u.deg)
assert len(tasca_cat) > 0, "Tasca et al. 2009 VizieR query returned no rows"
print(f"Retrieved {len(tasca_cat)} Tasca et al. 2009 morphology classifications")
Retrieved 231673 Tasca et al. 2009 morphology classifications
Match the retrieved Tasca et al. 2009 catalog against the rest-frame DP2 sample by sky position, combine spiral and irregular types into a single late-type class, and drop unclassified sources.
coord_tasca = SkyCoord(
ra=np.array(tasca_cat["RAJ2000"]), dec=np.array(tasca_cat["DEJ2000"]), unit="deg")
coord_dpz = SkyCoord(ra=dpz["coord_ra"].values, dec=dpz["coord_dec"].values, unit="deg")
idx_dpz, separation, _ = coord_tasca.match_to_catalog_sky(coord_dpz)
is_matched = np.array(separation < 1.0 * u.arcsec)
df = dpz.iloc[idx_dpz[is_matched]].reset_index(drop=True)
df["mph1"] = np.array(tasca_cat["Mph1"])[is_matched]
df = df[(df["mph1"] > 0) & (df["zphot"] < 0.5)].reset_index(drop=True)
df["is_early_type"] = (df["mph1"] == 1).astype(int)
print(f"Final cross-matched sample: {len(df)} galaxies")
print(df["is_early_type"].value_counts().rename({0: "late-type", 1: "early-type"}))
Final cross-matched sample: 19328 galaxies is_early_type late-type 14419 early-type 4909 Name: count, dtype: int64
5. Explore the data¶
This gives six features in total, covering three independent measurement routes: a Sersic profile fit (index, physical effective radius, and the ellipticity derived from it), total brightness (absolute i-band magnitude), and color (g-r, r-i). The effective radius and magnitude are now in physical units. Look at how early- and late-type galaxies separate in a few 2D projections of this feature space before building any model.
fig, axes = plt.subplots(2, 2, figsize=(8, 8), layout="constrained")
axes = axes.flatten()
panels = [
("abs_mag_i", "reff_kpc", "absolute i-band magnitude", "effective radius [kpc]"),
("sersic_index", "ellipticity", "Sersic index", "ellipticity"),
("abs_mag_i", "g_minus_r", "absolute i-band magnitude", "g - r [mag]"),
("g_minus_r", "r_minus_i", "g - r [mag]", "r - i [mag]"),
]
for label, name, marker in [(0, "late-type", "o"), (1, "early-type", "^")]:
sel = df["is_early_type"] == label
for ax, (xcol, ycol, xlabel, ylabel) in zip(axes, panels):
ax.scatter(df.loc[sel, xcol], df.loc[sel, ycol],
s=8, alpha=0.4, marker=marker, label=name)
for ax, (xcol, ycol, xlabel, ylabel) in zip(axes, panels):
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_xlim(df[xcol].quantile(0.001), df[xcol].quantile(0.999))
ax.set_ylim(df[ycol].quantile(0.001), df[ycol].quantile(0.999))
ax.grid(True, alpha=0.3)
handles, labels = axes[0].get_legend_handles_labels()
fig.legend(handles, labels, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 1.05))
<matplotlib.legend.Legend at 0x79f97c0d81a0>
Figure: Feature-space projections of the cross-matched sample, colored by Tasca et al. 2009 classification. Early-type galaxies are more compact, more centrally concentrated, and redder than late-type galaxies at fixed luminosity.
6. Prepare the training and test sets¶
Split the cross-matched sample into training and test sets before doing anything else, so that no information from the test set leaks into training.
rng = np.random.RandomState(1)
shuffled_idx = rng.permutation(len(df))
split = int(0.8 * len(df))
train_idx, test_idx = shuffled_idx[:split], shuffled_idx[split:]
X_train_raw = df.loc[train_idx, feature_cols].values.astype(np.float32)
y_train = df.loc[train_idx, "is_early_type"].values.astype(np.float32).reshape(-1, 1)
X_test_raw = df.loc[test_idx, feature_cols].values.astype(np.float32)
y_test = df.loc[test_idx, "is_early_type"].values.astype(np.float32).reshape(-1, 1)
print(f"Training samples: {len(X_train_raw)}")
print(f"Test samples: {len(X_test_raw)}")
Training samples: 15462 Test samples: 3866
6.1. Standardise the features¶
Neural networks train much more effectively when input features are on a similar scale. Standardise each feature using the mean and standard deviation of the training set only — using test-set statistics here would leak information about the test data into preprocessing.
train_mean = X_train_raw.mean(axis=0)
train_std = X_train_raw.std(axis=0)
X_train = torch.tensor((X_train_raw - train_mean) / train_std)
X_test = torch.tensor((X_test_raw - train_mean) / train_std)
y_train_t = torch.tensor(y_train)
y_test_t = torch.tensor(y_test)
7. Build and train the network¶
A neuron computes a weighted sum of its inputs plus a bias, then applies an activation function. Stacking neurons into layers, and layers into a network, lets the model learn non-linear combinations of the input features. SimpleNetwork below builds a fully-connected network of any shape, applying a sigmoid activation after every hidden layer. The final layer is left as a raw score (a "logit"), which is converted to a probability during training and evaluation.
The network learns by gradient descent: for each training example, it computes a prediction, compares it to the true label with a loss function, then adjusts every weight a small step in the direction that reduces the loss (backpropagation, handled automatically by PyTorch).
class SimpleNetwork(nn.Module):
"""
A flexible fully-connected neural network.
Parameters
==========
layer_sizes : list of int
The number of neurons in each layer, including input and output.
e.g. [6, 8, 4, 1]: 6 inputs, two hidden layers of 8 and 4 neurons, 1 output
"""
def __init__(self, layer_sizes):
"""Build the linear layers, with a fixed random seed for reproducibility."""
super().__init__()
torch.manual_seed(1)
layers = []
for layer_idx in range(len(layer_sizes) - 1):
layers.append(nn.Linear(layer_sizes[layer_idx], layer_sizes[layer_idx + 1]))
self.layers = nn.ModuleList(layers)
def forward(self, x):
"""Apply a sigmoid activation after every hidden layer, leaving the
final layer as a raw logit."""
for layer in self.layers[:-1]:
x = torch.sigmoid(layer(x))
return self.layers[-1](x)
Instantiate the network with two hidden layers of 8 and 4 neurons. These sizes are not tuned; they follow a common rule of thumb for a small tabular network like this one -- start a little larger than the number of inputs (6) to give the network room to form new combinations of the features, then taper down toward the single output. Train it, recording the train and test loss at each checkpoint.
Rather than fixing the number of epochs by hand, use early stopping: train for up to max_epochs, but keep a copy of the model's weights whenever the test loss reaches a new minimum, and stop once it has failed to improve for patience consecutive checks. This avoids both undertraining and the overfitting that comes from training well past the point where test loss stops improving.
Note that early-type galaxies are a minority of the sample. This class imbalance needs to be accounted for during training, or the network can minimise its loss by simply always predicting "late-type" without learning anything. The loss function, loss_fn, is defined with pos_weight to account for the class imbalance by increasing the penalty for misclassifying early-type galaxies.
model = SimpleNetwork([len(feature_cols), 8, 4, 1])
n_late, n_early = (y_train_t == 0).sum(), (y_train_t == 1).sum()
pos_weight = n_late / n_early
loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
optimiser = optim.Adam(model.parameters(), lr=0.001)
max_epochs = 10000
patience = 10
best_test_loss = float("inf")
best_state = None
epochs_without_improvement = 0
train_losses = []
test_losses = []
for epoch in range(max_epochs):
model.train()
y_pred = model(X_train)
loss = loss_fn(y_pred, y_train_t)
loss.backward()
optimiser.step()
optimiser.zero_grad()
if epoch % 25 == 0:
model.eval()
with torch.no_grad():
test_loss = loss_fn(model(X_test), y_test_t).item()
train_losses.append(loss.item())
test_losses.append(test_loss)
if test_loss < best_test_loss:
best_test_loss = test_loss
best_state = {
param_name: param_value.clone()
for param_name, param_value in model.state_dict().items()}
epochs_without_improvement = 0
else:
epochs_without_improvement += 1
if epochs_without_improvement >= patience:
print(f"Stopped at epoch {epoch}: no improvement in test loss "
f"for {patience * 25} epochs")
break
model.load_state_dict(best_state)
print("Training complete")
print(f"Final train loss: {train_losses[-1]: .4f}")
print(f"Best test loss: {best_test_loss: .4f}")
Stopped at epoch 7600: no improvement in test loss for 250 epochs Training complete Final train loss: 0.3372 Best test loss: 0.3073
Plot the recorded train and test loss to see how training progressed and where early stopping triggered.
plt.figure(figsize=(4, 4), layout="constrained")
plt.plot(train_losses, label="Train loss", color="k", linewidth=2)
plt.plot(test_losses, label="Test loss", color="grey", linewidth=2, linestyle="--")
plt.xlabel("step (every 25 epochs)")
plt.ylabel("weighted BCE loss")
plt.legend()
plt.grid(True, alpha=0.3)
Figure: Training and test loss during network training, recorded every 25 epochs. Early stopping halts training once the test loss stops improving, avoiding overfitting past that point.
8. Evaluate the classifier¶
Compare the trained network's test-set accuracy against a naive baseline that always predicts the majority class (late-type). Because the classes are imbalanced, raw accuracy can be a misleading metric: a model that is genuinely discriminating between the two classes can still score at or below a naive baseline on raw accuracy, since every false positive on the rare class costs as much as a correct majority-class prediction. Balanced accuracy -- the average of the recall on each class -- is a fairer summary, and the confusion matrix shows directly whether the network is actually distinguishing early- from late-type galaxies.
model.eval()
with torch.no_grad():
test_probs = torch.sigmoid(model(X_test))
test_preds = (test_probs >= 0.5).float()
accuracy = (test_preds == y_test_t).float().mean().item()
baseline = 1 - y_test_t.mean().item()
balanced_accuracy = balanced_accuracy_score(y_test_t.numpy(), test_preds.numpy())
print(f"Test accuracy: {accuracy * 100: .1f}%")
print(f"Naive baseline accuracy (always late-type): {baseline * 100: .1f}%")
print(f"Balanced test accuracy: {balanced_accuracy * 100: .1f}%")
fig, ax = plt.subplots(figsize=(4.5, 4), layout="constrained")
ConfusionMatrixDisplay.from_predictions(
y_test_t.numpy(), test_preds.numpy(),
display_labels=["late-type", "early-type"],
cmap="cividis", colorbar=False, ax=ax)
ax.set_title("Test-set confusion matrix")
Test accuracy: 91.7% Naive baseline accuracy (always late-type): 74.2% Balanced test accuracy: 92.1%
Text(0.5, 1.0, 'Test-set confusion matrix')
Figure: Test-set confusion matrix for the trained classifier.
9. Apply the classifier to unseen data¶
Apply the trained network to galaxies with no Tasca et al. 2009 classification using the same features and the same standardisation (mean and standard deviation) computed from the training set.
Restrict this to the same z < 0.5 range the network was trained on. Applying it to the full redshift range of this field would be extrapolating well beyond the training domain.
used_coords = set(zip(df["coord_ra"], df["coord_dec"]))
unseen_mask = np.array([
(ra, dec) not in used_coords
for ra, dec in zip(dpz["coord_ra"], dpz["coord_dec"])])
unseen_df = dpz[unseen_mask & (dpz["zphot"] < 0.5)].reset_index(drop=True)
X_unseen_raw = unseen_df[feature_cols].values.astype(np.float32)
X_unseen = torch.tensor((X_unseen_raw - train_mean) / train_std)
model.eval()
with torch.no_grad():
unseen_probs = torch.sigmoid(model(X_unseen)).numpy().flatten()
unseen_df["early_type_prob"] = unseen_probs
unseen_df["predicted_early_type"] = (unseen_probs >= 0.5).astype(int)
print(f"Applied the classifier to {len(unseen_df)} z < 0.5 galaxies "
"with no Tasca et al. 2009 classification")
print(unseen_df["predicted_early_type"].value_counts().rename({0: "late-type", 1: "early-type"}))
Applied the classifier to 5660 z < 0.5 galaxies with no Tasca et al. 2009 classification predicted_early_type late-type 3946 early-type 1714 Name: count, dtype: int64
As a sanity check, the predicted classes should separate in color space in the same way the labeled training sample did in Section 5.
fig, ax = plt.subplots(figsize=(5, 4), layout="constrained")
for label, name, marker in [(0, "predicted late-type", "o"), (1, "predicted early-type", "^")]:
sel = unseen_df["predicted_early_type"] == label
ax.scatter(unseen_df.loc[sel, "g_minus_r"], unseen_df.loc[sel, "r_minus_i"],
s=8, alpha=0.4, marker=marker, label=name)
ax.set_xlabel("g - r [mag]")
ax.set_ylabel("r - i [mag]")
ax.legend()
ax.grid(True, alpha=0.3)
Figure: Color-color distribution of the unseen sample, colored by the classifier's predicted class. The same color separation seen in the labeled training sample (Section 5) is recovered.
Summary¶
This notebook trains a small neural network to classify DP2 galaxies as early- or late-type from six Sersic, size, and color features, using Tasca et al. 2009 morphological labels for supervision. The trained classifier recovers the same color separation seen in the labeled training set when applied to an unseen sample, and generalizes to the full field without requiring a morphological label for every galaxy. The two companion notebooks in this series tackle related problems without that external label: 303.5 clusters the same features without supervision, and 303.6 regresses a continuous physical quantity, stellar mass, instead of a discrete class.