{'fraction_non_alphanumeric': 0.02960187031561576, 'fraction_numerical': 0.009351578078800798, 'mean_word_length': 4.930071355759429, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
EEG Channel Interpolation Using Deep Encoder-decoder Netwoks

Electrode"pop"artifacts originate from the spontaneous loss of connectivity between a surface and an electrode. Electroencephalography (EEG) uses a dense array of electrodes, hence"popped"segments are among the most pervasive type of artifact seen during the collection of EEG data. In many cases, the continuity of EEG data is critical for downstream applications (e.g. brain machine interface) and requires that popped segments be accurately interpolated. In this paper we frame the interpolation problem as a self-learning task using a deep encoder-decoder network. We compare our approach against contemporary interpolation methods on a publicly available EEG data set. Our approach exhibited a minimum of ~15% improvement over contemporary approaches when tested on subjects and tasks not used during model training. We demonstrate how our model's performance can be enhanced further on novel subjects and tasks using transfer learning. All code and data associated with this study is open-source to enable ease of extension and practical use. To our knowledge, this work is the first solution to the EEG interpolation problem that uses deep learning.


I. INTRODUCTION
Electroencephalography (EEG) devices have become increasingly popular in recent years and are used in a wide range of applications. Naturally, the medical applications of EEG are centered on neurological diagnosis, but EEG has proven useful for other problems in healthcare domain [1], [2]. Moreover, the use of EEG devices extends far beyond the medical domain; novel applications of EEG may be found in wide a variety of fields including advertising [3], education [4], entertainment [5], and security [6].
A fundamental challenge of EEG data is the low signal to noise ratio. Different sources contribute to this noisiness but, in general, they can be categorized as either movement artifacts or electrode artifacts. The most common, and particularly persistent, electrode artifact is the electrode "pop" [7], [8]. These artifacts result from abrupt changes in impedance, usually due to a loose electrode or bad conductivity. Furthermore, these artifacts are difficult to avoid because, even if the greatest care is taken when applying electrodes, the most minor subject movement or change in perspiration can cause the electrode to "pop".
A common solution to EEG "pops" is to interpolate the missing segments using recordings from nearby electrodes [9]. In practice, this interpolation is most commonly performed using eeglab, which contains a tool for spherical interpolation [10], [11]. Within the last few years, alternative interpolation methods reporting improved performance have been proposed: Petrichella et al. proposed a euclidean inverse distance method [12] while Courellis et al. demonstrated an interpolation approach that (while also being based on an inverse distance calculation) used geodesic lengths and electrode localization to extract more exact channel locations, thereby performing more accurate interpolation. [13]. Effective interpolation is a necessary preliminary step to any subsequent preprocessing or formal analysis of the EEG, including Independent Component Analysis (ICA). As noted by Ullsperger et al: "activity from bad channels should be removed before ICA decomposition, as it can massively deteriorate otherwise good decomposition results." [14] One shortcoming of these previous solutions is their dependence on knowledge of the precise locations of the electrodes (i.e. electrode localization / registration), which are not collected in most practical settings. Furthermore, the existing methodologies assume that the incidence and specific characteristics of the "pops" are similar across both subjects and tasks (i.e. "one-size-fits-all"). Furthermore, as far as the authors are aware, none of the studies surveyed for the purposes of this work provided publicly available software repositories to enable practical use, reproduction of their methodologies, or ease of extension.
To address the aforementioned challenges, we propose a novel electrode interpolation framework using representation learning. Our method autonomously identifies the spatiotemporal properties of EEG data measured at a set of electrodes, that predict the values of a given neighbor to those electrodes. Our model, which has been made publicly available 1 , can be used "out of the box" to more effectively interpolate EEG for any missing channel, at any time.
One important advantage of our model over existing approaches is its amenability to transfer learning: the ability to easily fine tune it using clean data from a novel subject or EEG experiment. This property of our model allows for interpolation that is tailor-made to the specific task and subject at hand, enabling the model to learn even idiosyncratic relations in new data.
To determine the usefulness of our method we evaluate the model on unseen tasks and subjects with and without further tuning. To summarize, our main contributions are: • We propose and implement a new framework for EEG channel interpolation using encoder-decoder deep rep-resentation learning. • We compare our method against contemporary algorithms for channel interpolation. • We make our code publicly available for the benefit of the community, and demonstrate how it may be tuned to novel subjects and tasks using transfer learning.

II. RELATED WORK A. Current Interpolation Solutions
The Spherical interpolation method (as implemented by eeglab) was first proposed by Perrin et al. in their 1989 work [10] and remains the most widely-used interpolation solution [10], [11], [15], [12]. More recent work describes improved interpolation methods by, for instance, using ellipsoid geodesic lengths [13] to better estimate the distances between electrodes. A weighted signal reconstruction scheme that favors electrodes closer to the location of the missing channel is then used to achieve higher accuracy. This however requires that the electrode positions be digitally registered so that an ellipsis can be fitted to the shape of the subject's head. That ellipsis is then used when calculating the distances between electrodes. Unfortunately, most data tends not to provide the specific channel locations.

B. Artifact Detection Using Neural Networks
EEG is a signal with spatial structure that unfolds in time. Convolutional neural networks (CNNs) are an obvious candidate for the EEG interpolation problem because they naturally capture hierarchical spatio-temporal relationships.
A few recent papers have leveraged CNNs for EEG classification [16], [17]. Previous works have also used CNNs to annotate EEG wave-forms for the presence of artifacts: Nejedly et. al. framed artifact detection as a classification problem and used CNNs to robustly annotate eye blink segments [18]. However, while the use of deep learning approaches for artifact detection has shown promising results, there is relatively less work on the use of deep learning to reconstruct artifact-ridden data segments.
To our knowledge, our work represents the first use of deep learning for signal reconstruction of EEG data. That is, our work is distinguished from prior artifact removal efforts by using neural networks as a component of a generative, rather than a discriminate, model. This distinction is especially meaningful in the context of EEG data, where merely annotating and removing noisy segments is not feasible for the many applications that require signal continuity. Generative frameworks can be used to fill in the data after it was removed, allowing researchers and practitioners alike to maintain the data sample even if one of the 20 (or more) channels had bad impedance.

A. Data Collection
The data in this study was collected from the recently published EEG During Mental Arithmetic Data Set [19]. The data consists of 24 subjects performing two tasks: a resting state task, and a mental arithmetic task. EEG data Fig. 1. The four-way split of the data into partitions. The dotted area (top left) was used to train our main algorithm. The areas with the diagonal shading were used for transfer learning. The areas with white background were used to test our algorithm. Each shaded area was used separately to tune the model for testing on the remaining 90% of the data in its own partition.
was collected as subjects performed the tasks using the 10-20 international system with the linked ears serving as a reference electrode (see Figure 2, left). The sampling rate was 500Hz. Each resting state task lasted 180 seconds while each mental arithmetic task lasted for 60 seconds; hence, the total number of samples was 90, 000 and 30, 000 for each resting state and mental arithmetic task respectively.
We segmented the data into 16ms (8 samples) epochs. Hence, following segmentation, each subject had 11, 250 and 3, 750 epochs for the resting state task and mental arithmetic task respectively.

B. Data Partitioning
In Figure 1, we illustrate how the data was partitioned for the training and evaluation of our method. Training data from the resting state task was used for model development while data from the mental arithmetic task was held out for intra-task evaluation. We further partitioned data from both tasks into training subjects (67% of subjects) and evaluation subjects (33%). This resulted in the following four partitions of the data, which we will refer to later when discussing our results:"Seen Task, Seen Subjects" (n=16 subjects),"Seen Task, Unseen Subjects" (n=8), "Unseen Task, Seen Subjects" (n=16), and "Unseen Task, Unseen Subjects" (n=8).
The "unseen" data sets contain some deviation from the data the model was trained on, and are thus a good test for the generalizability of the method. Because we are utilizing transfer learning 10% of the data for all unseen sets was heldout for tuning, to test the impact of this additional context on the model's performance.
In general, the fundamental difference between the two tasks is crucial to our evaluation. Researchers will often not have enough data to train neural networks "from scratch", not to mention training a neural network often requires exploration of a hyper-parameter space that may consume significant temporal (and financial) resources. This is espe- Fig. 2. A diagram of our deep learning framework. The EEG data is first segmented into 16ms epochs (in this example the pop happened at channel C3), each segment is then mapped to a 5x5 matrix that roughly reflects the spatial locations of the EEG electrodes (e.g. F7 is located in position 1,1 of the matrix). The electrodes at the sagittal and median planes were duplicated and the tensor was padded with the linked ear channel data to create a 8 × 8 matrix. We segmented the 500Hz data into 16ms windows, yielding a final 8 × 8 × 8 input data tensor. This data serves as the input to an encoder-decoder model. Finally, the output is transformed back into a signal.
cially true for deep learning frameworks that have strong tendencies to over fit and produce remarkable results for a specific data set while failing to generalize to other contexts. With this in mind, it is important that our models achieve good results on both unseen tasks and subjects to enable their continued development and utility within the greater research community. We therefore structured our data to assess its ability to generalize across tasks and subjects.

A. Pre-processing
To begin, all EEG data were Z-scored at the subject-level (i.e. converted to a zero mean, and unit variance representations). Deep networks require a large volume of training data; hence, we supplemented our training data by transforming each subject's EEG data into 10 distinct pseudosubjects. Each pseudosubject's data was an elementwise addition of the Z-scored subject's EEG data and random draws from a Gaussian distribution with (µ = 0, σ = 0.05). The pseudosubject's (already normalized) EEG data was then Zscored again following the introduction of the noise. The utility and validity of this data augmentation approach for EEG research has been demonstrated in prior work [20]. Next, a simple transformation was applied to project each sample of EEG data from a spherical channel representation onto a quantized two dimensional surface represented by a 5 × 5 matrix (Figure 2, panel 2).
Finally, EEG data was epoched into 16ms segments, with no overlap across segments 2 . This resulted in a 5 channels ×5 channels ×8 samples tensor. The electrodes at the sagittal and median planes (the central electrodes) were then duplicated and the tensor was padded with the linked ear channel data to create a 8 × 8 × 8 tensor. This manipulation of input size is common place in deep learning and is mainly the result of networks being optimized to work with input sizes that are powers of two [21]. This 8 × 8 × 8 tensor formed a single sample of input data, from the perspective of the network when training.
To create training data, we iterative occluded each of the 19 non reference electrodes (All electrodes except A1 or A2, see Figure 2). Thus each 8 × 8 × 8 tensor became the prediction target for 19 input tensors, each with one distinct occluded channel.

1) An Encoder-Decoder model for EEG Interpolation:
Inspired by research on image inpainting we deployed an encoder-decoder model for EEG interpolation. Image inpainting is a classical problem in computer vision: given a corrupted image the aim is to complete or "fill in" missing pixels. This is a similar problem to electrode interpolation.
Encoder-decoder models are the combinations of two networks that are trained simultaneously: the encoder first learns a lower dimensional embedding of the data, and the decoder attempts to recover the original data from the embedding. Encoder-decoder networks are a popular tool in image inpainting [22], [23], [24], so much so that this technique is now leveraged for image compression as selective removal of pixels might greatly enhance compression ratios [25].
We determined the optimal topological configuration of our encoder-decoder network via a random search of the network hyper-parameter space [26]. The tested topologies varied in the number of convolution layers, the existence of max-pooling, dropout, and batch normalization layers after each convolution layer, and whether the decoder was based on transposed convolution layers or simple up-sampling with convolution. More specifically, we trained 300 distinct architectural configurations of the encoder-decoder networks, and retained the configuration that best generalized within a held out subset of the training data itself. The best network was then used after training for our transfer learning evaluation. The code to run this search in the topological space, as well as the trained winning algorithm before and after the transfer learning tuning is available online. The optimal topology is shown in Figure 3, and discussed in Subsection V-A.
2) Subject+Task Enhancement via Transfer Learning: Transfer learning experiments were carried out by taking the model trained on the original data set and tuning it on a small subset (10%) of the testing data. Realistically, it is highly likely that a small sample of clean data will be available for a researcher to use when tuning our model.
To assess performance enhancements associated with transfer learning, we held out 10% of each data partition (See Figure 1) and tuned our network for 100 epochs. These numbers were intentionally small as to showcase how even minimal training that can be easily completed on non specialized hardware and using very little data can lead to significant improvements. By tuning the model for specific subjects and tasks, we assessed the flexibility and practical extensibility of our proposed approach.

C. Methodological Baselines
For our baseline we implemented the three methods described in the Related Work section [10], [12], [13].
1) The Euclidean Baseline: Both [12], [13] suggest methods that employ an inverse distance metric where the interpolated channelŝ i is calculated using the following equation: where p is the power parameter. The variable d ij represents the distance between electrode i and electrode j. The original channel j is represented by s j . The power parameter is an integer (usually between 2 and 5) that is set using a small amount of the data; while it is usually set to be the same value across a given data-set where interpolation is happening, we optimized the power parameter separately for each baseline and data-set to maximize the performance of the baselines.
The calculation of the distance, d ij , is the main difference between the two baselines. The fist euclidean baseline (EUD) uses a simple euclidean distance formula. This distance calculation is done using the generic electrode positions in space that are always available for every cap.
2) The Geodesic Baseline: The Geodesic Length baseline (EGL) is also based on the inverse distance equation. However, instead of using euclidean distances for d ij the geodesic length is calculated. The geodesic distance is calculated using the Vincenty algorithm which was originally used in geodesy to calculate the distance between points on the surface of a spheroid. The method is iterative and not theoretically guaranteed to converge. Previous work have demonstrated that interpolation calculated using this method outperforms simple euclidean interpolation [13]. However, as previously discussed, this was tested by the original baseline works when specific electrode locations were available [13]. It should therefore be expected that results obtained for the EGL may be lower than those reported in previous studies.
3) The Spherical Splines Baseline: Finally, we also followed the eeglab MATLAB implementation of spherical splines method (SS) [10]. According to this implementation at each point in time the value of of the interpolated channel s i can be approximated using the equation: Where θ i,j is the angle between the electrode locations i and j. Instead of calculating the angle, given the positions of the electrodes in space p i = (x i , y i , z i ) it is possible to directly calculate the cosine value: cos(θ i,j ) = xi·xj xi · xj . The function g(x) is defined as the sum of the series: 2n + 1 n m (n + 1) m P n (x) Where P n is the Legendre polynomial and following [10] we set m = 4. Additionally, following the eeglab implementation we limited the infinite sum to values between 1 and 7. Finally, the coefficients C = (c 1 , c 2 , . . . , c n ) are set to be the solution for the system of equation GC + T c 0 = S with the constraint T C = 0 where G k,l = g (cos(θ k,l )), S = (s 1 , s 2 , .., s n ) and T is a vector of ones. The channel being interpolated is excluded from the calculations of G and S.

D. Model Evaluation Approach
The selected baseline approaches [13] used the averaged normalized mean square error (ANMSE) as the main evaluation measure. The normalization of the mean square error is used to prevent a specific channel's performance from skewing the results, in case of a bad reconstruction. Having Zscored the data however all channels are guaranteed to have the same mean amplitude. Therefore we do not normalize our mean square error results. Hence our final evaluation is: Where N is the number of channels (19 in our specific case). M is the number of samples. Note that the expression for mean reconstruction error (the inner average) changes for every sample. s i andŝ i are as previously defined. This measure was used both for optimizing the power parameter for the different baselines (see Section IV-C) and calculating the final results presented momentarily.

A. Model Hyper-parameter Optimization
After exploring the topological space by testing different network architectures (using the Seen task, Seen subjects data, see Figure 1), the best performing network is visualized in Figure 3. This network consisted of a simple encoder with three convolution layers and one max pooling layer, as well as four transposed convolutions in the decoder. Additionally there was a dropout and a batch normalization layer after each convolution in the encoder. The results described in this section were all achieved using this particular neural network architecture.

B. Baseline Power-parameter Optimization
For our evaluation to be extra rigorous. we optimized the power parameter for each baseline data-partition configuration separately. In Figure 4, we illustrate the results of our power parameter optimization for the baseline methods. As seen in the Figure, the optimal power parameters were comparable with those reported in previous literature (between 2 and 5) [13]. All the results that are reported in this section were for the optimized baseline on the specific data set being discussed. The spherical splines baseline has no analogous parameter we can optimize.

C. Main Result
In Table I, we compare the results of our proposed approach against the baselines for the EEG interpolation task on the test sets. The baseline methods are highly unstable, giving a high variability in performance relative to our approach.
The Encoder-decoder model consistently outperformed the baselines by at least 10%. Moreover, by utilizing transfer learning the network was able to improve it's accuracy even with minimal additional data and training time.
Interestingly, in contrast to results reported in the literature, the EGL method did not clearly outperform the EUD baseline [13]. This might be due to our data not having the precise electrode locations in contrast to previous research (see Subsection VI-B in the discussion).
Another interesting result is the pattern of improvements after transfer learning. As can be seen in the last row of Table I, the biggest improvement was for Unseen task, Seen subjects data. This hint that there was more variability between EEG data from different tasks compared to data from different subjects. Additional testing will be needed to verify this hypothesis. However, this can be seen as a compelling argument in favor of flexible models that can be tuned for the specific data the researcher is working with.
Finally, we also extracted the delta (0.54Hz), theta (48Hz), alpha (812Hz), beta (1230Hz), and gamma (30100Hz) bands and tested the models performance for each band separately. Our method significantly improved over the baselines method in all bands. This is crucial as Comparison between Encoder-decoder model and baselines using Averaged mean square error (AMSE); lower is better. Note that the transfer learning (last row) was trained using a different data set on each column. There was no transfer learning for the Seen Task, Seen Subject partition as this is the original data used to train the model. SS: spherical splines baseline EGL: geodesic length calculation; EUD: euclidean baseline. The best result is bolded and percentage of improvement over the most competitive baseline is given.  different bands have different functions (for instance, the theta band is especially responsive during observation and memorization tasks [3]). Hence for an interpolation method to be useful the reconstruction fidelity must be consistent across all frequency bands. In the interest of brevity we will not present the results for all these bands separately. The code to extract the sub-bands is also available online.

D. Performance on Exemplary Data
In Figure 5, we present an example of our method's interpolation on an exemplary portion of the data, compared against the baselines. As shown in the Figure, the reconstructions from other methods contain voltage fluctuations that do not appear in the original signal, or the one reconstructed using our method. This is evidence that our framework was able to learn the nuanced relationships between electrode measurements that are not captured by baseline approaches.

VI. DISCUSSION
Our work used a deep encoder-decoder model to tackle the problem of EEG channel interpolation. While discriminative frameworks are able to only detect and label bad data segments, our results demonstrate that a generative approach can reconstruct the missing channel with high fidelity to the original signal. The success of our method suggests that deep learning can capture complex relationships between electrodes that are not sufficiently expressed by the relatively simple inverse distance calculations that are the predominant contemporary solution.

A. On Self-supervised Learning
Data labeling is often a tenuous and resource consuming process. Unfortunately, training deep learning models often requires extensive data collection and labeling efforts. Therefore, deep learning researchers have recently began to focus on finding ways to mitigate the need for labeled data. As we showed in this study, one approach to mitigate this is to frame problems as a self-supervised learning tasks 3 . Specifically, our work is a special case of a popular selfsupervised learning task: the prediction of occluded parts of data from visible ones. By using this framing we were able to circumvent a major challenge faced by deep learning approaches regardless of the field.

B. On the Challenges of Electrode Localization
As discussed previously, prior research that compared different interpolation methods used electrode localization to extract exact channel locations for each specific subject. While generic and imprecise locations are always available, electrode localization methods attempt to alleviate the noisiness inherent to EEG by providing exact locations of EEG electrodes. This localization can be done in many ways; one expensive option is to equip EEG caps with spatial sensors, or motion capture sensors [13], [27]. Other methods that require less specialized hardware including a simple DSLR camera [28] and Kinect with an Neural Network [29]. However, despite these recent advances, electrode localization remains uncommon. For instance, no EEG data set in physionet 4 or gigadb 5 contain an EEG database with electrode localization. Therefore, and to ensure our method is applicable to the vast majority of databases, the data we used also did not include electrode localization [19]. A possible future work could incorporate location data into the deep learning framework.

C. On Baseline Approaches
It is worth noting that there are multiple other interpolation methods such as the nearest neighbors method, planar-spline technique [15]. We selected the baselines methods described in Subsection II-A as they were the most contemporary approaches on the topic. Furthermore, the performance improvement of our model are especially impressive considering that the EUD and EGL baselines were optimized to maximize their performance on each and every separate partition of the data.
The SS method requires a system of equations to be solved for each and every time point. This is not a trivial requirement as it necessities complex calculations. This demand renders the SS method ill-suited for any online interpolation, and by extension many BCI applications [5], [30], [2]. In contrast to the taxing nature of the training procedure, piping data foreword in neural network is computationally cheap. Therefore our approach could potentially satisfy a growing need for accurate interpolation from online data.

D. On Transfer Learning
Transfer learning involves training a model on a problem similar to the one being solved. This is especially useful when only scarce data is available for the problem being solved, hindering the training of the model. While transfer learning is possible for many machine learning algorithms such as Bayesian networks and Markov chains, this technique became essential to deep learning especially due to its reliance on huge amounts of training data. Transfer learning is considered to be essential for the success and ubiquity of neural networks [31]. Our work for instance would be considerably less useful if it required every researcher to train the neural network from scratch, or if the results on data-sets that the model was not trained on were considerably worse.

VII. CONCLUSION AND FUTURE WORK
With the increasing prevalence of EEG devices, there is a need for methodologies that better address common EEG artifacts. In this work, we developed a deep encoder-decoder based method to interpolate EEG segments impacted by the most common EEG artifact: the electrode "pop". We 4 https://physionet.org/about/database/#ecg 5 http://gigadb.org/search/new?keyword=eeg demonstrated that our method improved EEG reconstruction performance compared to existing approaches, and that our method generalized well to unseen tasks and subjects.
Future work will extend this method to tackle other kinds of electrode artifacts. Moreover, an end-to-end system that automatically detects artifacts and replaces the corrupted data with an interpolated reconstruction of the original might be of particular interest to the community.