{'fraction_non_alphanumeric': 0.029165743879793524, 'fraction_numerical': 0.009506124465493449, 'mean_word_length': 5.249334610880443, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 5, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Contrastive Predictive Coding for Human Activity Recognition

Feature extraction is crucial for human activity recognition (HAR) using body-worn movement sensors. Recently, learned representations have been used successfully, offering promising alternatives to manually engineered features. Our work focuses on effective use of small amounts of labeled data and the opportunistic exploitation of unlabeled data that are straightforward to collect in mobile and ubiquitous computing scenarios. We hypothesize and demonstrate that explicitly considering the temporality of sensor data at representation level plays an important role for effective HAR in challenging scenarios. We introduce the Contrastive Predictive Coding (CPC) framework to human activity recognition, which captures the long-term temporal structure of sensor data streams. Through a range of experimental evaluations on real-life recognition tasks, we demonstrate its effectiveness for improved HAR. CPC-based pre-training is self-supervised, and the resulting learned representations can be integrated into standard activity chains. It leads to significantly improved recognition performance when only small amounts of labeled training data are available, thereby demonstrating the practical value of our approach.

Previous works such as [31,63,69] have demonstrated how unlabeled data can be utilized to learn useful representations for wide ranging tasks, including identifying kitchen activities [11], activity tracking in car manufacturing [71], classifying every day activities such as walking or running [4,10,51,66], and medical scenarios involving identifying freeze of gait in patients suffering from Parkinson's disease [57]. In many such applications, the presence of complex and often sparsely occurring movement patterns coupled with limited annotation makes it especially hard for deriving effective recognition systems. The promising results delivered in these works without the use of labels have resulted in a general direction of integrating unsupervised learning as-is into conventional activity recognition chains (ARC) [8] in the feature extraction step. In this work, we follow this general direction of utilizing (potentially large amounts of) unlabeled data for effective representation learning and subsequently construct activity recognizers from the representations learned.
Recent work towards such unsupervised pre-training has gone beyond the early introduction using Restricted Boltzmann Machines (RBMs) [63], involving (variants of) autoencoders [31,74], and self-supervision [32,69]. While they result in effective representations, most of these approaches do not specifically target a characteristic inherent to body-worn sensor data -temporality. Wearable sensor data resemble time-series and we hypothesize that incorporating temporal characteristics directly at the representation learning level results in more discriminative features and more effective modeling, thereby leading to better recognition accuracy for HAR scenarios with limited availability of labeled training data -as they are typical for mobile and ubiquitous computing scenarios.
Previous work on masked reconstruction [32] has attempted to address temporality at feature level in a self-supervised learning scenario by regressing to the zeroed sensor data at randomly chosen timesteps. This incorporates local temporal characteristics into a pretext task that forces the recognition network to predict missing values based on immediate past and future data. It was shown that the resulting sensor data representations are beneficial for modeling activities, which provides evidence for our aforementioned hypothesis of temporality at feature level playing a key role for effective modeling in HAR under challenging constraints.
In this paper we present a framework that rigorously follows the paradigm of modeling temporality at representation level. We propose to utilize Contrastive Predictive Coding (CPC) [58] for unsupervised representation learning of windowed body-worn sensor data. The key insight behind this approach is that predicting just the next future timestep involves exploiting the local smoothness of the signal, whereas predicting multiple subsequent timesteps requires inferring the global structure of time-series data. This results in representations that encode the high-level information between temporally separated parts of the time-series signal [58], thereby leading to improved downstream recognition performance. Sliding windows of movement data are passed through a non-linear encoder to map the data into a latent space, where an autoregressive network such as gated recurrent units (GRUs) is subsequently utilized to provide the context representation. Using this context, multiple subsequent future timesteps from the encoder are predicted and noise contrastive estimation (NCE) [28] is utilized to train the model. Pre-trained weights are subsequently used in the Activity Recognition Chain at the feature extraction step. We apply our framework for learned representations of activities on four benchmark datasets and demonstrate improved recognition performance. In summary, our contributions are as follows: • We introduce Contrastive Predictive Coding as an effective self-supervised pre-training scheme for HAR.
• Through a series of experiments, we analyze the network architecture choices and optimal training settings.
• We demonstrate economic use of available annotations by fine-tuning pre-trained models with limited labeled data, resulting in significant improvements over end-to-end training on the available annotations.

RELATED WORK ON REPRESENTATIONS OF SENSOR DATA IN HUMAN ACTIVITY RECOGNITION
In our work, we focus on learning effective representations for movement data recorded from body-worn sensing platforms through unsupervised pre-training. This follows the general direction of reducing reliance on annotated This manuscript is under review. Please write to harishkashyap@gatech.edu for up-to-date information.
data, by utilizing approaches that perform learning on unlabeled data. As such, relevant prior works involve the following: (i) feature learning for activity recognition in general; (ii) self-supervised learning in general, i.e., not limited to the mobile and ubiquitous computing domain; and (iii) self-supervised learning for HAR. The activity recognition chain (ARC) [8] details a five step pipeline for human activity recognition. We are interested in the fourth step in the process -feature extraction -which focuses on the computation of representative features. Earlier works utilized hand crafted features for activity recognition [23]. Recently, however, end-to-end training has been increasingly adopted for HAR since it offers integrated representation learning capabilities. There is not yet a consensus on the gold standard feature representation for HAR using wearables [31]. However, they can broadly be broken down into three categories: (i) Statistical features, e.g., mean and standard deviation of raw data [38]; (ii) Distribution-based representations, including those based on empirical cumulative distribution functions of the raw data [30]; and (iii) Learned features, that directly utilize the data itself to derive representations, involving supervised or unsupervised learning and dimensionality reduction techniques [31,59,63].

Feature Engineering
More traditional approaches aim at finding compact representations for the sensor data. A wealth of heuristics, both in the time and frequency domain, have been developed towards extracting such representations [23]. The distribution-based representations, involving the quantiles of the (inverted) empirical cumulative density function of sensor windows present the state-of-the-art for conventional feature extraction [30]. Improvements to this representation technique include adding structure [43] and specializing window lengths for human activity recognition [46]. One type of learned features includes dimensionality reduction techniques such as the principal component analysis, which has been utilized as a feature for activity recognition [63].

Feature Learning
Methods for feature learning aim at optimizing dedicated objective functions in order to learn useful representations from raw sensor data. Supervised learning requires annotated datasets and does not explicitly differentiate between the representation learning and classification steps of the ARC. As such, feature extraction (learning) is performed implicitly by the particular model that is being trained. Convolutional networks have been utilized to classify multi-variate sensor data [29,79,81]. Leveraging the temporal correlations in wearable sensor data at modeling level, (variants of) recurrent neural networks (RNNs) have been applied previously [27,29,80]. Guan et al. [27] setup ensemble training with recurrent networks in order to improve classification performance. Continuous attention mechanisms over both the sensory and time channels have been applied in [80] in order to learn both the 'important' timesteps as well as channels in windows of data. A combination of both convolutional and recurrent networks is utilized by Ordonez et al. [59] where 2D convolutional features are fed to a long short-term memory [36] network to perform activity recognition. Subsequent work on this architecture to improve performance includes temporal attention [55]. More recently, Transformer [75] encoder networks have been utilized for activity recognition [32,50]. They model sequential information via the use of self-attention mechanisms and utilize only dense layers. As they dispense of both convolutions and recurrence, they are more parallelizable and require less time to train [75]. Overall, supervised learning remains the de facto approach towards activity recognition in recent years and also comprises the state-of-the-art.
Prior work into unsupervised learning has involved RBMs [63] and variants of autoencoder models [31,74]. In [31] the authors investigate the role of representations in activity recognition, by evaluating different features on a common classification backend. Varamin et al. [74] define HAR as a set prediction problems within the autoencoder setup. A more recent development includes the use of self-supervised learning for unsupervised This manuscript is under review. Please write to harishkashyap@gatech.edu for up-to-date information.  [31], these self-supervised learning approaches form our unsupervised baselines.

Self-Supervised Learning
Self-supervised learning involves defining a 'pretext' task from the data itself, that provides supervisory signals beneficial for downstream tasks. Numerous such tasks have been designed for both computer vision and natural language processing problems. For example, colorization [86] involves a model that is trained to colorize grayscale images. Predicting image rotations [25] allows the model to learn concepts of the objects in the images, such as their location, pose and type. This approach is shown to be beneficial towards a series of downstream tasks including classification and object recognition. Other approaches such as in-painting [61] mask portions of the image, and predicting relative positions of patches [19] have also been shown to perform well for representation learning. Self-supervision involving spatio-temporality has been effectively applied for learning representations for videos. Identifying the odd or unrelated video sub-sequence [22], sequence verification of temporal order [53], and learning the arrow of time [78] have been used as pretext tasks.
In the case of natural language processing, context-based self-supervised learning has been applied to obtain word and sentence level embeddings for approaches such as Word2Vec [52], GloVe [62] and universal sentence encoder [9]. Most recently, transformer-based [75] approaches such as GPT [65] and BERT [18] have been developed. BERT involves predicting masked tokens from surrounding context followed by predicting the next sentence. GPT similarly learns useful representations by pre-training a language model and then discriminatively fine-tuning on each specific task.
A more related field to activity recognition from wearable sensing involves speech and audio processing. In [77], Wang et al. perform self-supervision by reconstructing randomly masked out groups of timesteps as well as frequencies on log mel filterbank energies by using bidirectional recurrent encoders. In a similar vein, Liu et al. [47] utilize reconstruction of time, channel and magnitude altered inputs for self-supervision (see also [48,88].) Autoregressive predictive coding has also been explored for speech self-supervision in [15,17] and [16]. Another major family of self-supervised learning approaches involves contrastive learning. The intuition behind contrastive learning is to compare semantically similar (positive) and dissimilar (negative) pairs of data points, and to encourage the distance between similar pairs to be close while the distance between dissimilar pairs is encouraged to be more orthogonal [13]. This framework has resulted in excellent representation learning performance across domains such as computer vision [12,33,35], natural language [49], speech recognition [6,58] and time-series data [39]. For example, Schneider et al. [6] utilize a contrastive loss on raw speech signals from a large unlabeled corpus to improve speech recognition performance on smaller labeled datasets. Contrastive Predictive Coding (CPC) [58], which is the focus of this work, performs contrastive learning over multiple future timestep predictions.

Self-Supervised Learning for HAR
Self-supervision for activity recognition from wearables has been explored from a multi-task learning context. In [69], eight data transformations were applied separately to the input data. These transformations were applied randomly, i.e. with 50% probability, and the task consisted of identifying if each transformation was applied or not in a multi-task setting. The architecture involved a transformation prediction network (TPN) consisting of 1D convolutional layers common to all tasks along with task specific fully connected layers. The learned TPN weights were used for representation learning, transfer learning and semi-supervised learning with limited labeled data. Multi-task self-supervised learning [69] utilizes accelerometer signals while our work is agnostic to sensor modalities. Therefore, it is applicable to a wider range of scenarios and environments.

Data Recording
Preprocessing Segmentation Feature extraction Classification Labeled sensor data g enc g ar Frozen weights Fine-tuning x t+2 x t+3 x t+4 g ar g ar g ar g ar g ar c t z t z t+1 z t+2 z t+3 z t+4 g enc g enc g enc g enc g enc g enc g enc g enc g enc Predictions Self-supervised pre-training  A more recent work involves the use of Transformer [75] encoders to reconstruct randomly masked timesteps in windows of sensor data [32]. Here, sensor data at 10% of randomly chosen timesteps is masked, or set to zero. The transformer encoder layers are subsequently trained to reconstruct only the missing data and learned weights are used for activity recognition, transfer learning and fine-tuning with limited labeled data. While [32] utilizes both accelerometer and gyroscope data, it delivers mixed results relative to DeepConvLSTM [59] when fine-tuning the pre-trained weights using limited labeled data. In comparison, our work results in consistent improvement in performance on all benchmark datasets over DeepConvLSTM and thereby reduces reliance on the quantity of labeled data required for training systems.

SELF-SUPERVISED PRE-TRAINING WITH CONTRASTIVE PREDICTIVE CODING
In this paper, we introduce the Contrastive Predictive Coding (CPC) framework to human activity recognition from wearables. Fig. 1 outlines the overall workflow, which includes: (i) pre-training (part 1 in Fig. 1), where unlabeled data are utilized to obtain useful representations (i.e., learn encoder weights) via the pretext task; and, (ii) fine-tuning, which involves performing activity recognition on the learned representations using a classifier (part 2 in Fig. 1). During pre-training, the sliding window approach is applied to large quantities of unlabeled data to segment it into overlapping windows. They are utilized as input for self-supervised pre-training, which learns useful unsupervised representations. Once the pre-training is complete, weights from both and are frozen and used for feature extraction (part 2 in Fig. 1). This corresponds to the feature extraction step in the ARC (part 3 in Fig. 1).
The frozen learned weights are utilized with the backend classifier network (see Sec. 3.2), a three-layer multilayer perceptron (MLP), in order to classify windows of labeled data into activities. This corresponds to the classification step in the ARC. The learned weights from CPC are frozen and only the classifier is optimized on (potentially smaller amounts of) labeled datasets. The resulting performance directly indicates the quality of the learned representations.
In what follows, we first detail our Contrastive Predictive Coding framework as it is applied to HAR, and then describe the backend classifier network used to evaluate the unsupervised representations.

Contrastive Predictive Coding
Contrastive predictive coding (CPC) involves predicting future timesteps in the latent space using autoregressive modeling. The intuition behind such a task is to extract high-level information from the signal while discarding the more local noises [58]. Predicting one future timestep is an established approach in signal processing [5,21] and exploits the local smoothness of signals. However, as the model is forced to predict farther into the future, it needs to infer more global structure [58]. This results in the incorporation of long-term temporal characteristics into the representation learning itself. We hypothesize that this process is beneficial towards learning effective representations.
The architecture for CPC is detailed in part 1 of Fig. 1. As detailed in [58], a non-linear encoder is utilized to map a window of sensor data to a sequence of latent representations given by = ( ). Subsequently, an autoregressive model is used to summarize all ≤ into a latent space, providing a context latent representation = ( ≤ ). Instead of predicting the future samples + directly using a generative model, a density ratio which preserves the mutual information between + and is modeled as follows: The density ratio is unnormalized and a simple log-bilinear model is used for scoring: A linear transformation is used to predict the timesteps, with a separate being used for each step. Using the density ratio ( + , ) and inferring + using an encoder relieves the network from modeling the high dimensional distribution and instead allows for sampling ( ) or ( | ) directly using Noise Contrastive Estimation (NCE). We utilize the InfoNCE loss detailed in [58] to update the network parameters: Here, one positive sample from ( + | ) and − 1 negative samples from the 'proposal' distribution ( + ) are utilized for optimizing the loss. The pre-training using Eq. 3 involves classifying the positive sample correctly from a combined set of one positive and − 1 negative samples. After the pre-training is complete, we utilize and weights to extract the representations. From an implementation standpoint, given a window of timesteps and future step predictions, we pass the entire window through the encoder. We choose a random timestep ∈ [0, − ] and predict subsequent timesteps. Sensor data present between 0 and are utilized as input to the autoregressive network , which This manuscript is under review. Please write to harishkashyap@gatech.edu for up-to-date information. results in the context representation . For each future timestep prediction, the negatives comprise of same timestep from all other windows in the batch.

Backend Classifier Network
In Sec. 3.1, we detailed the contrastive predictive coding framework, which constitutes the Feature Extraction step in the ARC. The subsequent step in the chain -Classification -involves the evaluation of the representations learned via self-supervision. The classification backend consists of a 3 layer feedforward network with the first two layers comprising of 256 and 128 units respectively. The last layer constitutes the softmax layer, the size of which equals the number of classes in the dataset. Between the layers, we apply batch normalization [40], the ReLU activation function [56] and dropout [70] with p=0.2. This network is identical to the classifier used in Haresamudram et al. [32], thereby making the results obtained directly comparable.

HUMAN ACTIVITY RECOGNITION BASED ON CONTRASTIVE PREDICTIVE CODING
In the previous section we have introduced our representation learning framework for movement data based on contrastive predictive coding. This pre-training step is integrated into an overarching human activity recognition framework, that is based on the standard Activity Recognition Chain (ARC) [8]. Addressing our general goal of deriving effective HAR systems from limited amounts of annotated training data, as it is a regular challenge in mobile and ubiquitous computing settings, we conducted extensive experimental evaluations to explore the overall effectiveness of our proposed representation learning approach.
In what follows we provide a detailed explanation of our experimental evaluation, which includes descriptions of: i) Application scenarios that our work focuses on; ii) Implementation details; iii) Evaluation metrics used for quantitative evaluation; and iv) Overall experimental procedure. Results of our experiments and discussion thereof are presented in Sec. 5.

Application Scenarios
In our work, we focus on studying self-supervised pre-training primarily for locomotion style activities such as walking, running, and sitting, as these broadly represent a significant portion of activities performed daily and are of significant interest for the mobile and ubiquitous computing community [1]. The effectiveness of our CPC-based pre-training is evaluated on four representative benchmark datasets, which mainly contain data recorded from smartphones (see Tab. 1 for an overview). In particular, recording movement data from smartphones has the advantage of being unobtrusive, inexpensive, and available to large portions of the population. This also allows for easier in-the-wild data collection. The chosen datasets cover diverse participants, environments of study, and data collection protocols for body-worn sensors including accelerometers and gyroscopes and as such are representative for the targeted application scenarios. They were also studied in previous works on self-supervised learning in human activity recognition [32,69]. Additionally, we include the USC-HAD dataset into our explorations, as an example for an activity recognition scenario using body-worn sensing platforms that are not smartphones.
Unless specified differently, dataset splits for training, validation and testing are performed based on participant IDs. 20% of the participants are randomly chosen to form the test dataset. Of the remaining data, 20% are randomly chosen once again to form the validation set, while the rest are utilized for training. Detailed descriptions of the datasets are given below.
4.1.1 Mobiact. Movement data from inertial measurement units were collected using a Samsung Galaxy S3 smartphone placed freely in a trouser pocket. The dataset covers eleven activities of daily living and four types of falls [10]. We used v2 of the dataset and subset data that cover only daily living activities, resulting in a total  [51] consists of 24 participants of different ages, gender, weight and height. The dataset was collected to propose a representation learning model that offers flexible and negotiable privacy-preserving sensor data transmission. The data were collected using an iPhone 6s and comprises accelerometer, gyroscope and attitude information. The activities covered include walking, jogging, going up and down the stairs, sitting and standing.

UCI-HAR.
The UCI-HAR dataset [4] contains data collected from 30 participants using a waist-mounted Samsung Galaxy S2 smartphone. The subjects performed six activities including standing, sitting, walking, lying down, walking downstairs and upstairs (the transition classes are not included). We use raw data from both the accelerometer and gyroscope in our study (also called the HAPT dataset 1 ).

USC-HAD.
The USC-HAD dataset [85] was collected on the MotionNode sensing platform and consists of data from 14 subjects. Twelve activities were recorded, including walking-forward, left, right, upstairs, and downstairs-, running forward, jumping, sitting, standing, sleeping, and riding the elevator up and down. Following the protocol from Haresamudram et al. [31], participants 1 − 10 form the training set, while participants 11 and 12 form the validation set, and participants 13 and 14 comprise the test set.

Implementation Details
We implemented our framework using PyTorch [60]. Source code will be shared when the paper is published. In what follows we provide details of parameter choices for the overall processing framework, which shall allow the reader to replicate our experiments.

Data Preparation.
We use raw accelerometer and gyroscope data from the benchmark datasets detailed in Sec. 4.1. As deep networks can effectively learn abstract representations from raw data itself, we perform no further filtering / denoising on the datasets [45]. The datasets have different sampling rates and we downsample them to 30Hz in order to maintain uniformity. Further, we also normalize the individual channels of the train dataset split to zero mean and unit variance. These means and variances are subsequently applied to the validation and test splits. Similar to prior works, sliding window based segmentation is applied to obtain windows of 1s with 50% overlap between subsequent windows [27,29,32]. For the network, we primarily evaluate a 1D Convolutional Encoder, containing three blocks with 1D convolutional layers of 32, 64 and 128 channels respectively with a kernel size of 3. Each block consists of a 1D convolutional layer with reflect padding, followed by the ReLU activation function and dropout with p=0.2. For the autoregressive network , we utilize a two-layer gated recurrent units (GRU) network [14] containing 256 units and dropout with p=0.2. The prediction networks, , are linear layers with 128 units.

Performance Metric
The test set mean F1-score is utilized as the primary metric to evaluate performance. The datasets used in this study show substantial class imbalance and thus experiments require evaluation metrics that are less affected negatively by such biased class distributions [64]. The mean F1-score is given by: where | | corresponds to the number of classes while and are the precision and recall for each class.

Experimental Procedure
As the main focus of this work is on deriving effective HAR representations without relying on labels, we study the self-supervised pre-training from two perspectives: (1) First, we compute the activity recognition performance, which describes the quality of the representations learned during pre-training. It indicates the raw ability of the representations to be discriminative towards the activities under study. (2) Then, we extend this evaluation to scenarios with limited availability of annotated data and compare performance of the learned weights to end-to-end training. This considers practical situations where very limited labeling is possible from users after the deployment of recognition systems.
Put together, these evaluations provide a rounded understanding of the effectiveness of the self-supervised pre-training and its performance for representation learning.

Activity Recognition
We perform CPC-based self-supervised pre-training and integrate the learned weights as a feature extractor in the activity recognition chain. In order to evaluate these learned representations, we compute their performance on the classifier network (Sec. 3.2). The performance obtained by CPC is contrasted primarily against previous unsupervised approaches including multi-task self-supervised learning [69], convolutional autoencoders [31], and masked reconstruction [32]. For reference, we also compare the performance relative to the supervised baseline-DeepConvLSTM [59]-and a network with the same architecture as CPC, albeit trained end-to-end from scratch. Once the model was pre-trained using CPC, the learned weights (from both and ) were Table 2. We compare the representation learning performance of the proposed approach against both supervised learning and to state-of-the-art unsupervised learning baselines. Performance for the approaches with † have been taken from [32]. CPC (end-to-end) refers to the setup wherein the same network architecture as CPC (1D Conv Encoder) is utilized. However, all weights of the network are initialized randomly and trained end-to-end from scratch using labeled data. Results marked in green correspond to the best performing models including both supervised and unsupervised learning approaches. For easy comparison, results in bold include the best performing unsupervised learning techniques. frozen and used with the classifier network. Labeled data was utilized to train the classifier network using cross entropy loss and the test set mean F1-score was detailed in Tab. 2.

Approach
We first compare the performance of the CPC-based pre-training to state-of-the-art unsupervised learning approaches. We note that all unsupervised learning approaches are evaluated on the same classifier network (Sec. 3.2), which is optimized during model training for activity recognition. On Mobiact, Motionsense and USC-HAD, CPC-based pre-training outperforms all state-of-the-art unsupervised approaches. For UCI-HAR, the performance is comparable to masked reconstruction. This clearly demonstrates the effectiveness of the pre-training thereby fulfilling one of the goals of the paper -which is to develop effective unsupervised pre-training approaches. It also validates our hypothesis that explicitly incorporating temporality at the representation level itself is beneficial towards learning useful representations.
Relative to DeepConvLSTM, i.e., the supervised baseline, the proposed approach shows increased performance by approximately 4% on Motionsense and over 7% on USC-HAD. On UCI-HAR and Mobiact, the performance is comparable to the 1D Conv Encoder-based CPC model (last row). Relative to end-to-end training on a network with the same architecture as CPC, using the pre-training results in improved performance for Motionsense, which obtains the highest F1-score across both supervised and unsupervised learning approaches. In contrast, CPC-based pre-training performs comparably on UCI-HAR, while it shows reduced results for both USC-HAD and Mobiact with the difference being around 3% at worst. This strong performance showcases the quality of the weights learned as they outperform end-to-end training on some of the datasets, even when the number of trainable parameters are only a fraction (as only the final classifier parameters are updated).

Semi-Supervised Learning on Limited Labeled Data
Here we consider a very important scenario where only a small portion of the collected data is labeled. This is a practical and rather common situation in mobile and ubiquitous computing scenarios as real-world deployment may allow for acquiring only a small labeled dataset from the users with minimal interruptions. This scenario is important because data collection is typically straightforward yet annotation is often challenging.
As in Sec. 5.1, we first pre-train the network using the CPC task and utilize the weights learned on both the encoder and autoregressive network for feature extraction. The classifier network is initialized randomly and trained from scratch whereas the learned weights are frozen. For each dataset, we utilize the entire dataset (unlabeled) for pre-training. During the fine-tuning stage, we randomly sample labeled samples per class where ∈ {1, 2, 5, 10, 25, 50, 100} and train the classifier from scratch. We perform five runs and plot the test set This manuscript is under review. Please write to harishkashyap@gatech.edu for up-to-date information.  Semi-supervised learning on limited labeled data. The network is first pre-trained in an unsupervised manner using CPC, and the learned weights are frozen. The backend classifier is initialized randomly and trained from scratch using {1, 2, 5, 10, 25, 50, 100} randomly sampled labelled frames. We perform five runs and report the test set mean f1-score. The curve in orange corresponds to CPC where the weights are learned while the blue line refers to the scenario with the randomly initialized feature extractor. The supervised baseline, DeepConvLSTM, is depicted in green. We observe significant improvements over DeepConvLSTM on all datasets. mean F1-score in Fig. 2 for the 1D Conv encoder models detailed in Tab. 2. The performance of the CPC-based pre-training technique is contrasted against the DeepConvLSTM network, which is the supervised learning baseline. In order to make the contribution of the learned weights clearer, we also compute the performance when the feature extractor is initialized randomly and frozen during fine-tuning.
On Mobiact, which contains the largest number of participants, we immediately notice the improvement in performance even when only one labeled sample per class is available for fine-tuning. Relative to DeepConvLSTM, This manuscript is under review. Please write to harishkashyap@gatech.edu for up-to-date information.
the performance of the proposed method is consistently higher by over 5% throughout. The difference is even clearer over the random initialized feature extractor, as the pre-training results in an improvement of over 15% when more than ten samples are available per class.
In the case of Motionsense, DeepConvLSTM outperforms CPC when there is only one labeled samples per class. Beyond that, CPC shows increased performance, resulting in a maximum improvement of approx. 10% when 50 labeled samples are available. The learned weights result in sustained improvements of around 15% over the random weights when more than ten labeled samples per class are available.
For UCI-HAR, CPC results show increased performance over DeepConvLSTM even when just one labeled sample per class is available. The difference peaks at over 10% when we have access to ten samples per class. Similarly, CPC shows improved performance even when there is only one sample per class for USC-HAD. As more labeled data is available, the performance of CPC rises further over DeepConvLSTM. There is also a consistent difference in performance over using a randomly initialized feature extractor.
The consistently improved performance over end-to-end training with DeepConvLSTM makes a compelling indicator that incorporating temporal characteristics into representation learning results in improved representations. We also note that the largest unlabeled dataset, Mobiact, demonstrates the most significant improvement in performance over random weights due to the self-supervised pre-training. Thus, using an even larger unlabeled dataset might further improve the quality of the representations learned using self-supervision. Additionally, the confidence interval for the proposed technique, CPC, is generally narrower than DeepConvLSTM for all datasets. This indicates that the pre-training makes the activity recognition performance more robust to variability in the input windows.

DISCUSSION
The main hypothesis of our work is that explicitly targeting the temporal characteristics of movement data for representation learning is beneficial towards learning discriminative features for human activity recognition using body-worn sensors. We accomplish this by predicting multiple future timesteps using contrastive learning. Such a pre-training scheme fits directly into the traditional activity recognition chains at the feature extraction step, allowing for easy integration into activity recognition workflows. In what follows, we first analyze contrastive predictive coding as it is applied to HAR and derive insights on the performance of the pre-training. Then we look at the practical implications of our work on existing and future applications in mobile and ubiquitous computing and outline the research agenda related to representation learning for human activity recognition.

Analyzing Contrastive Predictive Coding
Contrastive predictive coding involves correctly identifying the positive sample from distractors for future timesteps. In this section, we design experiments to better understand the pre-training process. We begin by studying the encoder ( ) and evaluate different choices, including feedforward, convolutional and recurrent networks and analyze how difficult the pretext task training is, and how it affects downstream activity recognition. Subsequently, we also analyze the number of steps to predict during the pre-training. Finally, we examine if all the weights learned during self-supervision are useful, by selectively utilizing only portions of the learned weights. These experiments help us to build better self-supervised models.
6.1.1 Choice of encoder. The encoder is used to map samples from the input data into a latent space on which future predictions are made. Therefore, the architecture of has impact on the pre-training as well as the subsequent activity recognition. We study three categories of networks for and report the downstream activity recognition performance in Fig. 3 Fig. 3. Studying the effect of using different networks for CPC pre-training: we utilize three categories of encoder networks including fully connected layers, 1D convolutional layers with kernel sizes ∈ {3, 5, 7, 9}, and recurrent layers for pre-training. The learned and weights are frozen and used to extract representations for classifying activities. We observe that the fully connected encoder or the 1D convolutional encoders with smaller kernel sizes (i.e. 3 or 5) demonstrate the highest activity recognition performance.  For each type of encoder, we utilize the same training settings as used in Tab. 2 for the 1D Conv Encoder. Fig. 3 shows that the choice of the encoder network has a significant impact on the activity recognition performance. For the 1D Conv. encoders, we see that having shorter kernel sizes (i.e., 3 or 5) is generally more preferable to longer filter lengths such as 7 or 9. The convolution operation over the input data results in overlaps over the future timesteps to be predicted. Correctly predicting the first few future timesteps, which potentially fall under the overlap, thereby becomes trivial. This results in reduced activity recognition performance as the pretext task becomes ineffective. It also explains how the activity recognition performance reduces as the kernel size is increased.
Larger overlaps on the future timesteps mean that the overlapped steps are easier to predict, reducing the discriminative ability of the representations learned. This can be clearly seen in Fig. 4 where the 1D Conv. Encoder with a kernel size of 9 has a considerably higher average accuracy of predicting the positive sample relative to using the encoder with a kernel size of 3. It indicates that the pretext task is easier to solve. Correspondingly, the downstream activity recognition performance for kernel size 9 is around 13% lower than the F1-score for kernel size 3. This effect is more prominent for the recurrent encoders as the input data is parsed step-by-step and the output at any given timestep is dependent on previous data. Thus, the pretext task becomes trivial to solve, resulting in a reduction of around 42% compared to the 1D Conv. Encoder with kernel size 3.
The fully connected (FC) encoder represents the other extreme where there is no overlap across the window of data. The average accuracy of predicting the future timesteps is lower relative to the 1D Conv. Encoder with kernel size 3. This results in reduction of nearly 2% for activity recognition. From Fig. 4 and Fig. 3 we can see that the difficulty of solving the pretext task has significant impact on the activity recognition performance. If the task is trivial (as in the case of using large kernel sizes or recurrent encoders), the downstream recognition task also suffers correspondingly. Therefore, the encoder architecture must be carefully considered before being utilized for pre-training, as rendering the pretext task trivial results in poor representations.

Number of Future
Steps to Predict. CPC learns effective representations by predicting multiple future timesteps, rather than just the next timestep. This allows the model to learn features that incorporate long term temporal characteristics. It also leads us to the question: How many future timesteps need to be predicted to learn useful representations? For the CPC-based pre-trained models in Tab. 2, we study the activity recognition performance for increasing values of ∈ {2, 4, 8, 12, 16}, and report the test mean F1-scores.
As can be seen in Fig. 5, increasing the number of predicted timesteps generally results in improved activity recognition. For Mobiact, Motionsense and UCI-HAR, the performance peaks when =12. Beyond that, the performance starts reducing again. The trend is similar for USC-HAD, with the peak occurring at =8. Thus, predicting approximately 400ms into the future results in the best performance for Mobiact, Motionsense and UCI-HAR, whereas USC-HAD requires predicting around 270ms into the future.
As discussed in Sec. 3.1, the input to the autoregressive network is the sensor data between timesteps 0 and . With increasing , the input to becomes shorter thereby making it more difficult to learn the context representation which can reliably predict many subsequent future timesteps. We hypothesize that this results in the reduction in performance after obtaining the peak. Looking at the 1D Conv. Encoder with kernel size=3 in Fig. 4, we can also observe that predicting multiple timesteps into the future is considerably more challenging than predicting the immediate future. The farther into the future we predict, the lower the mutual information between what the model already knows (i.e., the context representation) and the target, making it more difficult to correctly predict the positive sample. The accuracy of prediction drops almost exponentially indicating the difficulty of predicting far into the future. However, Fig. 5 also shows that predicting the immediate future (i.e., = 2 in Fig. 5) results in poorer representations as the model only learns short term noises. Therefore, predicting multiple future timesteps is vital towards extracting the long-term temporal signal which exists in the sensor data windows.

Mobiact
Motionsense  we utilize the 1D convolution encoder with a kernel size=3 as and vary ∈ {2, 4, 8, 12, 16} for pre-training. Subsequently, the learned and weights are frozen and used as a feature extractor for activity recognition. We observe that predicting multiple future timesteps ( ≥ 8) is more advantageous than predicting the near future, i.e. ∈ {2, 4}. 6.1.3 Which Pre-Trained Weights Should be Used? During activity recognition, the learned weights from both and were frozen and utilized with the classifier network (Fig. 1). This brings up the question: Which learned weights are useful for activity recognition? To answer this, we progressively utilize learned weights from fewer encoder layers during the classification and report the resulting test mean F1-score in Fig. 6.
The default configuration involves freezing learned weights from both and , as done for Tab. 2. This corresponds to ≤3 + in Fig. 6. ≤3 utilizes frozen learned weights from all three encoder layers, while the autoregressive network is initialized randomly and trained with the classifier. On a similar vein, ≤2 uses frozen learned weights from the first two encoder layers while the third layer and the autoregressive network are both trained with the classifier.
From Fig. 6 we can see that utilizing the default configuration results in the best activity recognition performance for Motionsense and USC-HAD. For these datasets, using learned ≤3 + weights outperforms fully supervised training (purple bars in Fig. 6).
For Mobiact, the default configuration does not result in performance exceeding fully supervised training. However, using the learned ≤2 weights results in a mean F1-score of 85.22%, which is an improvement over Learned weights used g enc1 g enc 2 g enc 3 g enc 3 + g ar Fully supervised Fig. 6. Studying which learned weights are useful for activity recognition: using learned weights from the CPC model with 1D convolutional encoder and kernel size=3, we progressively utilize learned weights from fewer layers for activity recognition. The rest of the layers are initialized randomly and optimized during activity recognition. For example, using both and weights is denoted by ≤3 + while using only the first two encoder layer learned weights is shown as ≤2 (the rest of the network including the third encoder layer and are not frozen). We observe that using a subset of the learned weights can lead to improvement over using all learned weights. fully supervised training. Similarly for UCI-HAR, the best performance is obtained when using the learned ≤2 weights. We observe a mean f1-score of 82.58%, which is higher than the best unsupervised representation learned by masked reconstruction (Tab. 2) and comparable to DeepConvLSTM, which exceeds all other approaches. Thus, we can conclude that using a subset of the weights learned via self-supervision could result in improved performance, often comparable to or better than supervised learning baselines such as DeepConvLSTM.
As mentioned in [58], either (the output of ) or (the output of ) can be utilized as the representation. If extra context from the past is useful for classification, then can be used; else may be more effective. We hypothesize that certain transition-style activities covered in Mobiact, such as stand to sit, sit to stand, car step-in and car step-out require the extra context provided by the learned weights at the encoder level, rather than the context representation ( ), which may not be sufficiently encoding previous timesteps to be accurately classified. The confusion matrix in Fig. 7 illustrates this interpretation. For the transition-style activities in particular, using . For transition-style activities such as stand to sit, sit to stand, car step-in and car step-out, we see that the extra context provided by ≤2 results in improved performance over ≤3 + .
the learned weights from only the first two encoder layers, i.e., ≤2 results in considerable improvements over using ≤3 + . 6.1.4 Summary and Guidelines. Studying factors which affect CPC such as the choice of encoder, number of future step predictions and the usability of learned weights at various levels of the network, allow us to develop a set of insights for applying CPC to other mobile and ubiquitous computing scenarios as well: (1) The encoder architecture has significant impact on the quality of the representations learned via CPC.
Overlap over the prediction targets results in poorer representations, and thus, care must be taken to avoid setting up trivial prediction tasks. (2) Predicting multiple future timesteps results in improved representations over predicting only the immediate future. Such a prediction scheme encodes global structure present in the time-series body-worn sensor data, which is beneficial towards learning richer representations. (3) A subset of the learned weights could result in improved performance relative to using all learned weights.
The representation used depends on the activities under study, as certain activities might require longer context to be accurately recognized. Thus, using learned weights from both the encoder and autoregressive networks maybe sub-optimal than using some parts of those weights.

Practical Value of CPC for Human Activity Recognition Tasks
6.2.1 Incorporating Temporality at Representation Level results in Improved Recognition Performance. The primary hypothesis of this work is that incorporating temporal characteristics into the representation learning process results in effective representation learning for time-series data. We note that previous unsupervised learning approaches involving Restricted Boltzmann Machines [63] and convolutional autoencoders [31] were trained using signal reconstruction. The more recent multi-task self-supervised learning utilizes binary predictions of randomly applying binary signal transformations in order to learn representations. These approaches however, do not specifically utilize the temporal characteristics of the data. Masked reconstruction [32] leverages local temporal dependencies by reconstructing zeroed out timesteps from immediate local context. From Tab. 2 we observe that masked reconstruction, using just local low-level information, results in improvements in performance on three out of four of the benchmark datasets over the approaches that do not seek to incorporate any level of temporal information. This demonstrates the importance of using temporal information into the representation learning process itself. Taking this insight further, we proposed to utilize Contrastive Predictive Coding, which learns to infer global structure in the time-series data, beyond just local low-level information and noise, by predicting multiple future timesteps. From our results in Tab. 2 we obtain strong evidence that such a process results in rich representations that more effectively capture the time-series nature of the body-worn sensor data.
6.2.2 CPC is Flexible and Generic. The CPC framework can be considered generic from three standpoints: Target prediction setup: The temporal order of prediction is not significant and the pretext task can also be setup to predict the past timesteps or even randomly masked portions of the data (similar to masked reconstruction). However, care needs to be taken while choosing the encoder, the target predictions as well as the negative samples in order to avoid setting up a trivial task. Architecture: The architecture of CPC also allows for replacing the , , and networks with suitable alternatives. In this work we utilized standard architectures for simplicity. For example, in Sec. 6.1.1 we discussed various encoder networks and their effects. The autoregressive network used in this work is a 2-layer GRU. However, more powerful techniques for processing sequential information such as Transformers [75] or convolution layers could further improve the representation performance. Finally. the future timestep predictions are made by , which in our setup consists of linear layers. They only observe the context representation in order to make the prediction. As explored in [68], alternates to this setup include 1-layer Transformer encoders and recurrent networks. How negatives are sampled: In this work, the negatives for the contrastive loss are sampled from different windows present in the same batch of data. However, if we had prior knowledge of the downstream task, the negative sampling could be performed in such a way to incentivize relevant features for that particular task. For example, if the downstream task was person identification, we could sample negatives from the rest of the participants for each positive sample. The resulting features are likely to be discriminative towards participants rather than activities.
6.2.3 Self-Supervised Pre-Training Reduces Reliance on Large Amounts of Annotated Data. The lack of large-scale annotated body-worn sensor datasets for human activity recognition limits the application of complex supervised recognition systems. At the same time, the more straightforward data collection process allows for the potential collection of large amounts of unlabeled data. In this work, we demonstrated how pre-training on unlabeled data results in performance exceeding fully supervised training when limited labeled data is available. This allows for leveraging massive movement datasets such as the UK Biobank [20] to learn general movement representations, that can subsequently be fine-tuned for target tasks using labeled data. Such an approach can have serious impact in practical scenarios where very limited data can be collected from users after the deployment of recognition systems, for user adaptation or personalization purposes. By first pre-training on unlabeled data, these limited labels can be economically used to derive accurate recognition.

Research Agenda: Representation Learning for Human Activity Recognition
The focus of this work is towards utilizing unlabeled movement sensor datasets to perform representation learning. It is motivated by the limited size and the lack of variety in current annotated datasets. Instead, we can leverage massive movement datasets such as the UK Biobank [20] to first learn generic representations that can be fine-tuned on task specific labeled data. However, specific applications of mobile and ubiquitous computing might require sensor placements which are different than the available source dataset. Therefore, a big challenge to address is the development of approaches that can still learn representations that can be effectively fine-tuned on data collected from sensors placed on different locations on the body. This will allow for improved performance in niche scenarios requiring unique sensor placements. Recent approaches addressing the lack of annotated datasets involve extraction of virtual movement data from modalities such as mocap [37,72] and videos [44], which contain a large number of participants and diverse set of actions and environments. Such techniques have the advantage of being capable of extracting large quantities of virtual movement data at arbitrary positions on the body. However, due to the artifacts introduced during the extraction process, the performance of recognizers trained on this data tend to be lower than those trained on real IMU data. Thus, developing effective representation learning approaches that can deal with the domain shift could be beneficial towards improved recognition.

CONCLUSION
Feature extraction plays a crucial role in human activity recognition (HAR) using body-worn movement sensors. Accordingly, the community has invested a lot of effort into developing new ways to extract meaningful representations from streams of sensor data that, ultimately, will lead to improved downstream recognition performance. Hand-crafted (engineered) features have long dominated the field, yet with the success of deep learning methods in the wider scientific community, the focus of the HAR community has shifted to learning effective representations directly from sensor data. End-to-end learning can only be employed with some limitations given the typically severe restrictions on the amount of labelled sample data that is available for training HAR models from scratch. As such, substantial effort has been devoted to explicit representation learning thereby not necessarily relying on large quantities of labeled sample data but rather making more economic and hence effective use of smaller labeled training sets, and especially aiming at exploiting unlabeled data, which are straightforward to collect in mobile and ubiquitous computing settings.
The approach presented in this paper follows the paradigm of explicitly learning data representations, which are then integrated as features into the standard activity recognition chain [8]. The key idea for the presented approach is to focus directly on temporality in the data in order to learn feature representations that lead to improved activity recognition performance especially for challenging scenarios with limited labeled training data. To this end, we have introduced the concept of Contrastive Predictive Coding (CPC) into human activity recognition using body-worn movement sensors. CPC was demonstrated to be effective in, for example, audio analysis scenarios and we have adopted the technique and refined it towards the constraints and requirements of HAR. CPC learns features through a combination of encoder networks that not only target representing individual sample but rather focus on predicting samples in the temporal vicinity and as such explicitly aiming at modeling temporality. We have hypothesized that this temporality is crucial not only at modeling level but especially at representation level. The pre-trained models are then integrated into the activity recognition chain, serving as effective feature extractors.
In our extensive experimental evaluation we have demonstrated the effectiveness of the proposed approach for improved human activity recognition under realistic, challenging requirements. On a range of benchmark scenarios we have shown that CPC-learned features lead to recognition models that outperform all previous approaches to unsupervised representation learning. Furthermore, we have demonstrated that the CPC-based models are on par with supervised learning approaches. Yet, such end-to-end methods are not suitable for real-world application scenarios with limited annotated training sets. We have shown how CPC-based models can overcome these issues by demonstrating that recognition results are significantly better for small, labeled sampled sets when compared to the state-of-the-art in end-to-end learning.
These results are encouraging because they indicate that it is possible to utilize unlabeled data for deriving effective sensor data representations that in turn will lead to more effective recognition systems. Collecting even vast amounts of unlabelled sensor data can be considered straightforward given the ubiquity of mobile sensing platforms such as smartphones or other body-worn sensors. The work presented here adds to the general agenda of deriving robust and effective recognition systems for challenging assessment scenarios as they are common in applications of mobile and ubiquitous computing.