Categories
Python

Convert Neural Network Inputs to Time Series

A Typical and simple neural network inputs would consist of 2 dimensions :

  1. Sample dimension
  2. Feature dimension

To clarify their meaning, The length of Sample dimension of the given input indicates how many data items are we going to input, while the length of Feature dimension indicates how many data features does each data item contain. When we train, for each data item, there is a corresponding target that needs to be learned.

For example in the following neural network input there are 3 data items, containing 2 features each. so the dimensions are 3X2.

				
					inputs=np.array([
[1,2],
[1,2],
[0,1]
])
				
			

To transform it to time series we simply need to convert it to these 3 dimensions:

  1. Sample dimension
  2. Timestamp dimension
  3. Feature dimension

We can do it using the following utility:

				
					def window(seq, n=2, fill=False, fill_value=None):
    it = iter(seq)
    if fill:
        win = deque((next(it, fill_value) for _ in range(0, n)), maxlen=n)
    else:
        try:
            win = deque((next(it) for _ in range(0, n)), maxlen=n)
        except:
            return
    yield win
    for e in it:
        win.append(e)
        yield win

def to_time_series(inputs, targets, timestamps_count):
        return np.array([list(i) for i in window(inputs, timestamps_count)]), targets[timestamps_count:]
				
			

What it does is adding the timestamp dimension that we need to convert the old simple data to timeseries with the given timestamps count. It will also cut the first block of targets in accordance to how many timestamps we require, since we consider the first data item, which contains <timestamps> samples now,  to correspond to the first target item and so on.

Usage of the utility is as follows:

				
					timeseries, targets = to_time_series(inputs, targets, timestamps)
				
			

Did my post help you? share it with me here and share it with your friends and colleagues everywhere 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *