Episode 10: Into scikit-learn
Cut a recording into trials with Epochs, fit a scikit-learn classifier on them offline with Sklearn, and deploy it through the call a running pipeline makes.
A classifier is fitted on recorded trials and then runs on live epochs. Sklearn wraps one scikit-learn estimator for both halves: fit_offline() takes a block of trials, step() takes one epoch. This episode writes its own two-class recording, so it needs no hardware and no download. scikit-learn is not a g.Pype dependency: pip install scikit-learn first.
Four channels of Gaussian noise, shifted by a fixed pattern during a “1” trial’s window and by its negative during a “2” trial’s, alternating, twenty trials each. The last channel is a trigger: zero except a single-sample spike of 1.0 or 2.0 at each trial’s onset. The file is plain HDF5 that g.Pype did not write, so it carries only what its two attributes say: the rate, and the roles. An HDF5Reader derives the markers from the trigger channel by role.
26RATE = 250.0
27SIGNAL_CHANNELS = 4
28EPOCH_SECONDS = 0.4
29EPOCH_SAMPLES = round(EPOCH_SECONDS * RATE)
30#: Seconds between one trial's onset and the next, comfortably more
31#: than EPOCH_SECONDS, so trials never overlap.
32TRIAL_SPACING_SECONDS = 1.0
33TRIALS_PER_CLASS = 20
34#: Each class's per-channel mean shift during its own epoch window,
35#: well separated against unit noise, so there is something to learn.
36PATTERN = np.array([3.0, -2.0, 1.5, -1.0])
54 rng = np.random.default_rng(seed)
55 spacing = round(TRIAL_SPACING_SECONDS * RATE)
56 n_trials = TRIALS_PER_CLASS * 2
57 total_samples = n_trials * spacing + spacing
58
59 signal = rng.normal(
60 scale=1.0, size=(total_samples, SIGNAL_CHANNELS)
61 ).astype(np.float64)
62 trigger = np.zeros((total_samples, 1))
63
64 for trial in range(n_trials):
65 onset = (trial + 1) * spacing - spacing // 2
66 label = "1" if trial % 2 == 0 else "2"
67 sign = 1.0 if label == "1" else -1.0
68 window = slice(onset, onset + EPOCH_SAMPLES)
69 signal[window, :] += sign * PATTERN
70 trigger[onset, 0] = float(label)
71
72 data = np.column_stack([signal, trigger])
73 roles = ["signal"] * SIGNAL_CHANNELS + ["trigger"]
74 with h5py.File(path, "w") as handle:
75 dataset = handle.create_dataset("data", data=data.T)
76 dataset.attrs["sampling_rate"] = RATE
77 dataset.attrs["channel_roles"] = np.array(roles, dtype=object)
A batch run reads the file, a ChannelSelector keeps the signal channels by role, since the trigger channel would hand the classifier its own label as a feature, and Epochs cuts one epoch per marker of the condition, from tmin to tmax seconds around it, the end excluded, stacked into a (time, channel, trial) block the Collector hands back. The window runs from 0.1 s before the marker to 0.3 s after: the window a live Trigger with time_pre=0.1 and time_post=0.3 cuts, and the two have to agree sample for sample, since a window one sample off misaligns every feature. The file has no time row, so the reader is told so.
91 with gp.Pipeline() as p:
92 reader = gp.HDF5Reader(
93 file_name=path, mode="batch", has_time_row=False
94 )
95 # The trigger channel already did its job, HDF5Reader derived
96 # markers from it at load time, and must not also reach the
97 # classifier as a feature: it would encode the label directly
98 signal_only = gp.ChannelSelector(roles=Constants.ChannelRoles.SIGNAL)
99 # 0.1 s before the marker to 0.3 s after: the window a live
100 # Trigger(time_pre=0.1, time_post=0.3) cuts, sample for sample
101 epochs = gp.Epochs(condition=condition,
102 tmin=-0.1, tmax=EPOCH_SECONDS - 0.1)
103 collector = gp.Collector()
104 p.connect(reader, signal_only)
105 p.connect(signal_only, epochs)
106 p.connect(epochs, collector)
107 return p.run()
Epochs takes one condition per run, and a batch pipeline merges no inputs, so the two conditions are cut in two runs and joined along the trial axis in numpy. result.trials carries a sample and a label per trial, which is the training data’s answer key.
117 result_1 = cut_condition(RECORDING, "1")
118 result_2 = cut_condition(RECORDING, "2")
119 block = np.concatenate([result_1.data, result_2.data], axis=2)
120 trials = [tuple(t) for t in result_1.trials] + [
121 tuple(t) for t in result_2.trials
122 ]
123 print(
124 f"Cut {block.shape[2]} trials of {block.shape[0]} samples, "
125 f"{block.shape[1]} channels each."
126 )
A plain scikit-learn sanity check first, before any g.Pype node is involved: each trial flattened to one feature row, a linear discriminant, five-fold cross-validation. With 400 features and 36 trials a plain discriminant is ill-posed, so this is shrinkage LDA, solver="lsqr" with shrinkage="auto", the standard remedy when features outnumber trials. Chance on two balanced classes is 0.5, and with 40 trials a score below about 0.65 is still within chance’s reach.
129 x = block.transpose(2, 0, 1).reshape(block.shape[2], -1)
130 y = [label for _, label in trials]
131 # 36 trials against 400 features: shrinkage is what makes a linear
132 # discriminant well-posed with more features than trials
133 lda = LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto")
134 scores = cross_val_score(lda, x, y, cv=5)
135 print(
136 f"Plain sklearn 5-fold accuracy: {scores.mean():.2f} "
137 f"(chance is 0.50)"
138 )
The last two trials of each class are held out first; fitting on them would make the deployed accuracy below meaningless. Sklearn wraps the estimator, and fit_offline() takes the block and a context naming the trials and the sampling rate.
143 holdout = 2
144 train_block = np.concatenate(
145 [
146 result_1.data[:, :, :-holdout],
147 result_2.data[:, :, :-holdout],
148 ],
149 axis=2,
150 )
151 train_trials = [tuple(t) for t in result_1.trials[:-holdout]] + [
152 tuple(t) for t in result_2.trials[:-holdout]
153 ]
154 test_epochs = [
155 (result_1.data[:, :, trial], "1") for trial in range(-holdout, 0)
156 ] + [(result_2.data[:, :, trial], "2") for trial in range(-holdout, 0)]
157
158 clf = gp.Sklearn(
159 LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto"),
160 name="clf",
161 )
162 clf.fit_offline(
163 train_block,
164 {
165 Constants.Keys.TRIALS: train_trials,
166 Constants.Keys.SAMPLING_RATE: RATE,
167 },
168 )
169 print(
170 f"gp.Sklearn fitted on {train_block.shape[2]} trials, held out "
171 f"{len(test_epochs)} for deployment."
172 )
step() is the method a realtime pipeline calls once per epoch, downstream of a Trigger that cuts the same 0.1 s before to 0.3 s after. Here it is called directly on each held-out trial. The prediction is the class’s position in the estimator’s classes_, kept in the node’s fitted state.
177 classes = clf.state["classes_"]
178 correct = 0
179 for frame, true_label in test_epochs:
180 prediction = clf.step({Constants.Defaults.PORT_IN: frame})
181 index = int(prediction[Constants.Defaults.PORT_OUT][0, 0])
182 predicted_label = classes[index]
183 correct += predicted_label == true_label
184 print(f" true {true_label!r}, predicted {predicted_label!r}")
185 print(
186 f"Deployed accuracy on held-out trials: {correct}/{len(test_epochs)}"
187 )
Run the script:
Cut 40 trials of 100 samples, 4 channels each.
Plain sklearn 5-fold accuracy: ... (chance is 0.50)
gp.Sklearn fitted on 36 trials, held out 4 for deployment.
true '1', predicted ...
true '1', predicted ...
true '2', predicted ...
true '2', predicted ...
Deployed accuracy on held-out trials: .../4
The counts follow from the constants at the top: twenty trials a class, 0.4 s at 250 Hz, two held out per class. The accuracies are what the fixed seed gives, and the pattern is set well apart from the noise, so expect them high.
Proceed to Episode 11, where a whole run is recorded at launch and replayed with nothing plugged in.
Nodes in this episode: HDF5Reader, ChannelSelector, Epochs, Collector, Sklearn
File s4e10_into_scikit_learn.py – View file on GitHub
1"""Season 4, Episode 10: a scikit-learn classifier, fit offline, deployed.
2
3Writes its own two-class recording, a plain HDF5 file, so it needs no
4hardware and no download. gp.Epochs cuts one condition per batch run,
5and the two are joined in numpy between runs, because a batch pipeline
6merges no inputs. That is the shape of training data fit_offline()
7exists for. The fitted gp.Sklearn is then deployed through step(), the
8call a realtime pipeline makes once per epoch, on trials it never saw.
9Requires scikit-learn: pip install scikit-learn
10"""
11
12import os
13import tempfile
14
15import h5py
16import numpy as np
17from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
18from sklearn.model_selection import cross_val_score
19
20import gpype as gp
21from gpype.common.constants import Constants
22
23#: The recording this example writes and then reads back.
24RECORDING = os.path.join(tempfile.gettempdir(), "s4e10.h5")
25
26RATE = 250.0
27SIGNAL_CHANNELS = 4
28EPOCH_SECONDS = 0.4
29EPOCH_SAMPLES = round(EPOCH_SECONDS * RATE)
30#: Seconds between one trial's onset and the next, comfortably more
31#: than EPOCH_SECONDS, so trials never overlap.
32TRIAL_SPACING_SECONDS = 1.0
33TRIALS_PER_CLASS = 20
34#: Each class's per-channel mean shift during its own epoch window,
35#: well separated against unit noise, so there is something to learn.
36PATTERN = np.array([3.0, -2.0, 1.5, -1.0])
37
38
39def write_recording(path: str = RECORDING, seed: int = 0) -> None:
40 """Write a two-class synthetic recording as a plain HDF5 file.
41
42 The signal channels carry Gaussian noise, shifted by +PATTERN during
43 a "1"-trial's window and by -PATTERN during a "2"-trial's,
44 alternating. The last channel is a trigger: zero except a
45 single-sample spike of 1.0 or 2.0 at each trial's onset, which
46 HDF5Reader turns back into markers by role, with no markers key
47 needed in the file at all.
48
49 Args:
50 path: File to write.
51 seed: For the noise generator, so the recording, and the
52 accuracy this example reports, are reproducible.
53 """
54 rng = np.random.default_rng(seed)
55 spacing = round(TRIAL_SPACING_SECONDS * RATE)
56 n_trials = TRIALS_PER_CLASS * 2
57 total_samples = n_trials * spacing + spacing
58
59 signal = rng.normal(
60 scale=1.0, size=(total_samples, SIGNAL_CHANNELS)
61 ).astype(np.float64)
62 trigger = np.zeros((total_samples, 1))
63
64 for trial in range(n_trials):
65 onset = (trial + 1) * spacing - spacing // 2
66 label = "1" if trial % 2 == 0 else "2"
67 sign = 1.0 if label == "1" else -1.0
68 window = slice(onset, onset + EPOCH_SAMPLES)
69 signal[window, :] += sign * PATTERN
70 trigger[onset, 0] = float(label)
71
72 data = np.column_stack([signal, trigger])
73 roles = ["signal"] * SIGNAL_CHANNELS + ["trigger"]
74 with h5py.File(path, "w") as handle:
75 dataset = handle.create_dataset("data", data=data.T)
76 dataset.attrs["sampling_rate"] = RATE
77 dataset.attrs["channel_roles"] = np.array(roles, dtype=object)
78
79
80def cut_condition(path: str, condition: str) -> gp.Result:
81 """One condition's trials, as a (time, channel, trial) Result.
82
83 Args:
84 path: The recording to read.
85 condition: The trigger label to cut epochs around.
86
87 Returns:
88 The Collector's Result: SIGNAL_CHANNELS channels, one trial per
89 occurrence of *condition*.
90 """
91 with gp.Pipeline() as p:
92 reader = gp.HDF5Reader(
93 file_name=path, mode="batch", has_time_row=False
94 )
95 # The trigger channel already did its job, HDF5Reader derived
96 # markers from it at load time, and must not also reach the
97 # classifier as a feature: it would encode the label directly
98 signal_only = gp.ChannelSelector(roles=Constants.ChannelRoles.SIGNAL)
99 # 0.1 s before the marker to 0.3 s after: the window a live
100 # Trigger(time_pre=0.1, time_post=0.3) cuts, sample for sample
101 epochs = gp.Epochs(condition=condition,
102 tmin=-0.1, tmax=EPOCH_SECONDS - 0.1)
103 collector = gp.Collector()
104 p.connect(reader, signal_only)
105 p.connect(signal_only, epochs)
106 p.connect(epochs, collector)
107 return p.run()
108
109
110if __name__ == "__main__":
111
112 write_recording()
113
114 # 1. Cut each condition separately and merge the two in numpy: the
115 # merge happens between runs, which is why fit_offline() takes a
116 # block rather than reading from a pipeline
117 result_1 = cut_condition(RECORDING, "1")
118 result_2 = cut_condition(RECORDING, "2")
119 block = np.concatenate([result_1.data, result_2.data], axis=2)
120 trials = [tuple(t) for t in result_1.trials] + [
121 tuple(t) for t in result_2.trials
122 ]
123 print(
124 f"Cut {block.shape[2]} trials of {block.shape[0]} samples, "
125 f"{block.shape[1]} channels each."
126 )
127
128 # 2. A plain sklearn sanity check first: is this separable at all?
129 x = block.transpose(2, 0, 1).reshape(block.shape[2], -1)
130 y = [label for _, label in trials]
131 # 36 trials against 400 features: shrinkage is what makes a linear
132 # discriminant well-posed with more features than trials
133 lda = LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto")
134 scores = cross_val_score(lda, x, y, cv=5)
135 print(
136 f"Plain sklearn 5-fold accuracy: {scores.mean():.2f} "
137 f"(chance is 0.50)"
138 )
139
140 # 3. gp.Sklearn, fit offline, holding out the last two trials of
141 # each class first: the deployed accuracy below has to be
142 # measured on trials the estimator never saw
143 holdout = 2
144 train_block = np.concatenate(
145 [
146 result_1.data[:, :, :-holdout],
147 result_2.data[:, :, :-holdout],
148 ],
149 axis=2,
150 )
151 train_trials = [tuple(t) for t in result_1.trials[:-holdout]] + [
152 tuple(t) for t in result_2.trials[:-holdout]
153 ]
154 test_epochs = [
155 (result_1.data[:, :, trial], "1") for trial in range(-holdout, 0)
156 ] + [(result_2.data[:, :, trial], "2") for trial in range(-holdout, 0)]
157
158 clf = gp.Sklearn(
159 LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto"),
160 name="clf",
161 )
162 clf.fit_offline(
163 train_block,
164 {
165 Constants.Keys.TRIALS: train_trials,
166 Constants.Keys.SAMPLING_RATE: RATE,
167 },
168 )
169 print(
170 f"gp.Sklearn fitted on {train_block.shape[2]} trials, held out "
171 f"{len(test_epochs)} for deployment."
172 )
173
174 # 4. Deploy: one prediction per epoch, through step(), the method a
175 # realtime pipeline calls downstream of a Trigger, one epoch at
176 # a time
177 classes = clf.state["classes_"]
178 correct = 0
179 for frame, true_label in test_epochs:
180 prediction = clf.step({Constants.Defaults.PORT_IN: frame})
181 index = int(prediction[Constants.Defaults.PORT_OUT][0, 0])
182 predicted_label = classes[index]
183 correct += predicted_label == true_label
184 print(f" true {true_label!r}, predicted {predicted_label!r}")
185 print(
186 f"Deployed accuracy on held-out trials: {correct}/{len(test_epochs)}"
187 )