PLS regression example#

In this example, we perform a PLS regression to predict the moisture of corn samples from their NIR spectra.

Import the package

import spectrochempy as scp

Load the corn NIR dataset#

The data is available from the Eigenvector archive:

try:
    ds_list = scp.read("http://www.eigenvector.com/data/Corn/corn.mat", merge=False)
except FileNotFoundError:
    ds_list = None
    print("Eigenvector corn dataset not reachable; skipping the remote PLS example.")
else:
    ds_list_names = [f"{i} : {ds.name}({ds.shape})" for i, ds in enumerate(ds_list)]
    print(ds_list_names)
['0 : m5nbs((3, 700))', '1 : mp5nbs((4, 700))', '2 : mp6nbs((4, 700))', '3 : propvals((80, 4))', '4 : m5spec((80, 700))', '5 : mp5spec((80, 700))', '6 : mp6spec((80, 700))']
if ds_list is not None:
    # %%
    # Inspect the spectra
    # ^^^^^^^^^^^^^^^^^^^^
    # The 5th dataset ``m5spec`` contains NIR spectra from 80 corn samples
    # recorded on the same instrument. The ``corn.mat`` archive does not
    # record whether the intensities are stored as reflectance or as
    # ``log(1/R)`` absorbance, so the series is labeled with the neutral title
    # "NIR spectra" and no intensity unit is imposed:
    X = ds_list[4]
    X.title = "NIR spectra"
    X.x.title = "Wavelength"
    X.x.units = "nm"
    _ = X.plot(cmap=None)

    # %%
    # The properties to predict are in the ``propval`` dataset:
    Y = ds_list[3]
    _ = Y.T.plot(cmap=None, legend=Y.x.labels)

    # %%
    # Predict moisture content
    # ^^^^^^^^^^^^^^^^^^^^^^^^
    y = Y[:, "Moisture"]

    # %%
    # Split into training and test sets
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    # Use the first 57 samples (out of 80) for calibration and the rest for
    # validation:
    X_train = X[:57]
    X_test = X[57:]
    y_train = y[:57]
    y_test = y[57:]

    # %%
    # Fit the PLS model
    # ^^^^^^^^^^^^^^^^^^
    pls = scp.PLSRegression(n_components=5)
    _ = pls.fit(X_train, y_train)

    # %%
    # Validate with a parity plot
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ax = pls.plot_parity(label="calibration", s=150)
    _ = pls.plot_parity(
        y_test,
        pls.predict(X_test),
        ax=ax,
        s=150,
        c="red",
        label="validation",
        clear=False,
    )
    _ = ax.legend(loc="lower right")
  • plot pls
  • plot pls
  • plot pls

Uncomment the following line to display all figures when running the script directly with Python.

# scp.show()

Total running time of the script: (0 minutes 0.847 seconds)