代码之家  ›  专栏  ›  技术社区  ›  Cranjis

深入学习如何拆分5维时间序列,并通过嵌入层传递一些维度

  •  0
  • Cranjis  · 技术社区  · 4 年前

    我有一个5维时间序列的输入:

    a = [[8,3],[2] , [4,5],[1], [9,1],[2]...] #total 100 timestamps. For each element, dims 0,1 are numerical data and dim 2 is a numerical encoding of a category. This is per sample, 3200 samples

    该类别有3个可能的值(0,1,2)

    我想构建一个NN,这样最后一个维度(类别)将通过一个输出大小为8的嵌入层,然后连接回前两个DIM(数字数据)。

    所以,这将是这样的:

    input1 = keras.layers.Input(shape=(2,)) #the numerical features
    input2 = keras.layers.Input(shape=(1,)) #the encoding of the categories. this part will be embedded to 5 dims
    x2 = Embedding(input_dim=1, output_dim = 8)(input2) #apply it to every timestamp and take only dim 3, so [2],[1], [2] 
    x = concatenate([input1,x2]) #will get 10 dims at each timepoint, still 100 timepoints
    x = LSTM(units=24)(x) #the input has 10 dims/features at each timepoint, total 100 timepoints per sample
    x = Dense(1, activation='sigmoid')(x)
    model = Model(inputs=[input1, input2] , outputs=[x]) #input1 is 1D vec of the width 2 , input2 is 1D vec with the width 1 and it is going through the embedding
    model.compile(
            loss='binary_crossentropy',
            optimizer='adam',
            metrics=['acc']
        )
    

    我该怎么做?(最好是在凯拉斯)? 我的问题是如何将嵌入应用到每个时间点? 也就是说,如果我有1000个时间点,每个时间点有3个DIM,我需要将其转换为1000个时间点,每个时间点有8个DIM(Emebeling层应该将输入2从(1000X1)转换为(1000X8)

    0 回复  |  直到 4 年前
        1
  •  4
  •   pythonic833    4 年前

    这里有几个问题。 首先,让我给你一个工作的例子,并解释如何解决你的问题。

    导入和数据生成

    import tensorflow as tf
    import numpy as np
    
    from tensorflow.keras import layers
    from tensorflow.keras.models import Model
    
    num_timesteps = 100
    max_features_values = [100, 100, 3]
    num_observations = 2
    
    input_list = [[[np.random.randint(0, v) for _ in range(num_timesteps)]
       for v in max_features_values]
        for _ in range(num_observations)]
    
    input_arr = np.array(input_list)  # shape (2, 3, 100)
    

    为了使用嵌入,我们需要将voc_大小作为输入_维度,如 LSTM documentation .

    嵌入和连接

    voc_size = len(np.unique(input_arr[:, 2, :])) + 1  # 4
    

    现在我们需要创建输入。投入应该是有规模的 [None, 2, num_timesteps] 和 [None, 1, num_timesteps] 其中第一个维度是灵活的,并且将被我们传递的观察值的数量填充。让我们使用之前计算的 voc_size .

    inp1 = layers.Input(shape=(2, num_timesteps))  # TensorShape([None, 2, 100])
    inp2 = layers.Input(shape=(1, num_timesteps))  # TensorShape([None, 1, 100])
    x2 = layers.Embedding(input_dim=voc_size, output_dim=8)(inp2)  # TensorShape([None, 1, 100, 8])
    x2_reshaped = tf.transpose(tf.squeeze(x2, axis=1), [0, 2, 1])  # TensorShape([None, 8, 100])
    

    这不容易连接,因为除了沿连接轴的标注外,所有标注都必须匹配。但不幸的是,这些形状并不匹配。因此我们重塑 x2 .我们通过移除第一维度然后转置来实现。

    现在我们可以毫无问题地连接,一切都以直截了当的方式工作:

    x = layers.concatenate([inp1, x2_reshaped], axis=1)
    x = layers.LSTM(32)(x)
    x = layers.Dense(1, activation='sigmoid')(x)
    model = Model(inputs=[inp1, inp2], outputs=[x])
    

    检查虚拟示例

    inp1_np = input_arr[:, :2, :]
    inp2_np = input_arr[:, 2:, :]
    model.predict([inp1_np, inp2_np])
    
    # Output
    # array([[0.544262 ],
    #       [0.6157502]], dtype=float32)
    

    #这会输出介于0和1之间的值,正如预期的那样。

        2
  •  4
  •   Andrew Wei    4 年前

    如果你不是在找 Embedding 这是Keras(映射到稠密向量的正整数)中通常使用的方法。您可能正在寻找某种非投影或基展开,其中3维映射(嵌入)到8维并连接结果。这可以使用核技巧或其他方法实现,但在具有非线性应用的神经网络中也会隐式实现。

    因此,您可以按照与pythonic833相似的格式执行类似的操作,因为它很好(但根据 Keras LSTM 文件要求 [batch, timesteps, feature] ):

    输入生成

    import tensorflow as tf
    import numpy as np
    
    from tensorflow.keras import layers
    from tensorflow.keras.models import Model
    
    num_timesteps = 100
    num_features = 5
    num_observations = 2
    
    input_list = [[[np.random.randint(1, 100) for _ in range(num_features)]
       for _ in range(num_timesteps)]
        for _ in range(num_observations)]
    
    input_arr = np.array(input_list)  # shape (2, 100, 5)
    

    模型构建

    然后您可以处理输入:

    input1 = layers.Input(shape=(num_timesteps, 2,))
    input2 = layers.Input(shape=(num_timesteps, 3))
    x2 = layers.Dense(8, activation='relu')(input2)
    x = layers.concatenate([input1,x2], axis=2) # This produces tensors of shape (None, 100, 10)
    x = layers.LSTM(units=24)(x)
    x = layers.Dense(1, activation='sigmoid')(x)
    model = Model(inputs=[input1, input2] , outputs=[x])
    model.compile(
        loss='binary_crossentropy',
        optimizer='adam',
        metrics=['acc']
    )
    

    后果

    inp1_np = input_arr[:, :, :2]
    inp2_np = input_arr[:, :, 2:]
    model.predict([inp1_np, inp2_np])
    

    产生

    array([[0.44117224],
           [0.23611131]], dtype=float32)
    

    关于要签出的基础扩展的其他解释:

    1. https://stats.stackexchange.com/questions/527258/embedding-data-into-a-larger-dimension-space
    2. https://www.reddit.com/r/MachineLearning/comments/2ffejw/why_dont_researchers_use_the_kernel_method_in/
    推荐文章