当前位置:   article > 正文

基于多头注意力机制LSTM股价预测模型_lstm attention股票预测

lstm attention股票预测

1、多头注意力机制层的构建

  1. class MultiHeadAttention(tf.keras.layers.Layer):
  2. def __init__(self, num_heads, d_model):
  3. super(MultiHeadAttention, self).__init__()
  4. self.num_heads = num_heads
  5. self.d_model = d_model
  6. assert d_model % self.num_heads == 0
  7. self.depth = d_model // self.num_heads
  8. self.wq = tf.keras.layers.Dense(d_model)
  9. self.wk = tf.keras.layers.Dense(d_model)
  10. self.wv = tf.keras.layers.Dense(d_model)
  11. self.dense = tf.keras.layers.Dense(d_model)
  12. def split_heads(self, x, batch_size):
  13. """Split the last dimension into (num_heads, depth).
  14. Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)
  15. """
  16. x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
  17. return tf.transpose(x, perm=[0, 2, 1, 3])
  18. def scaled_dot_product_attention(self, q, k, v, mask):
  19. """Calculate the attention weights.
  20. q, k, v must have matching leading dimensions.
  21. k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
  22. The mask has different shapes depending on its type(padding or look ahead)
  23. but it must be broadcastable for addition.
  24. Args:
  25. q: query shape == (..., seq_len_q, depth)
  26. k: key shape == (..., seq_len_k, depth)
  27. v: value shape == (..., seq_len_v, depth_v)
  28. mask: Float tensor with shape broadcastable
  29. to (..., seq_len_q, seq_len_k). Defaults to None.
  30. Returns:
  31. output, attention_weights
  32. """
  33. matmul_qk = tf.matmul(q, k, transpose_b=True) # (..., seq_len_q, seq_len_k)
  34. # scale matmul_q
  35. # scale matmul_qk
  36. dk = tf.cast(tf.shape(k)[-1], tf.float32)
  37. scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
  38. # add the mask to the scaled tensor.
  39. if mask is not None:
  40. scaled_attention_logits += (mask * -1e9)
  41. # softmax is normalized on the last axis (seq_len_k) so that the scores
  42. # add up to 1.
  43. attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, seq_len_k)
  44. output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v)
  45. return output, attention_weights
  46. def call(self, v, k, q, mask):
  47. batch_size = tf.shape(q)[0]
  48. q = self.wq(q) # (batch_size, seq_len, d_model)
  49. k = self.wk(k) # (batch_size, seq_len, d_model)
  50. v = self.wv(v) # (batch_size, seq_len, d_
  51. # split heads
  52. q = self.split_heads(q, batch_size) # (batch_size, num_heads, seq_len_q, depth)
  53. k = self.split_heads(k, batch_size) # (batch_size, num_heads, seq_len_k, depth)
  54. v = self.split_heads(v, batch_size) # (batch_size, num_heads, seq_len_v, depth)
  55. # scaled dot product attention
  56. scaled_attention, attention_weights = self.scaled_dot_product_attention(q, k, v, mask)
  57. # concatenation of heads
  58. scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) # (batch_size, seq_len_q, num_heads, depth)
  59. concat_attention = tf.reshape(scaled_attention,
  60. (batch_size, -1, self.d_model)) # (batch_size, seq_len_q, d_model)
  61. # final linear layer
  62. output = self.dense(concat_attention) # (batch_size, seq_len_q, d_model)
  63. return output

2、构建股价预测模型

  1. # Stock price prediction model
  2. class StockPricePredictionModel(tf.keras.Model):
  3. def __init__(self, num_heads, d_model, num_lstm_units):
  4. super(StockPricePredictionModel, self).__init__()
  5. self.num_heads = num_heads
  6. self.f_model = d_model
  7. self.num_lstm_units = num_lstm_units
  8. self.multi_head_attention = MultiHeadAttention(self.num_heads, self.d_model)
  9. self.lstm = tf.keras.layers.LSTM(self.num_lstm_units, return_sequences=True)
  10. self.dense = tf.keras.layers.Dense(1)
  11. def call(self, inputs, mask):
  12. attention_output = self.multi_head_attention(inputs, input, input, mask)
  13. lstm_output = self.lstm(attention_output)
  14. prediction = self.dense(lstm_output)
  15. return prediction
  16. model = StockPricePredictionModel(num_heads=9, d_model=256, num_lstm_units=128)

3、模型训练与结果

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/237465
推荐阅读
相关标签
  

闽ICP备14008679号