TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(TensorBoard可视化)


鳗鱼有芒果
鳗鱼有芒果 2022-09-20 11:13:17 51915
分类专栏: 资讯

TF之LSTM:利用基于顺序的LSTM回归算法对DIY数据集sin曲线(蓝虚)预测cos(红实)(TensorBoard可视化)

目录

输出结果

代码设计


输出结果


代码设计

  1. import tensorflow as tf
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. BATCH_START = 0
  5. TIME_STEPS = 20
  6. BATCH_SIZE = 50
  7. INPUT_SIZE = 1
  8. OUTPUT_SIZE = 1
  9. CELL_SIZE = 10
  10. LR = 0.006
  11. BATCH_START_TEST = 0
  12. def get_batch():
  13. global BATCH_START, TIME_STEPS
  14. xs = np.arange(BATCH_START, BATCH_START+TIME_STEPS*BATCH_SIZE).reshape((BATCH_SIZE, TIME_STEPS)) / (10*np.pi)
  15. seq = np.sin(xs)
  16. res = np.cos(xs)
  17. BATCH_START += TIME_STEPS
  18. return [seq[:, :, np.newaxis], res[:, :, np.newaxis], xs]
  19. class LSTMRNN(-title class_ inherited__">object):
  20. def __init__(self, n_steps, input_size, output_size, cell_size, batch_size):
  21. self.n_steps = n_steps
  22. self.input_size = input_size
  23. self.output_size = output_size
  24. self.cell_size = cell_size
  25. self.batch_size = batch_size
  26. with tf.name_scope('inputs'):
  27. self.xs = tf.placeholder(tf.float32, [None, n_steps, input_size], name='xs')
  28. self.ys = tf.placeholder(tf.float32, [None, n_steps, output_size], name='ys')
  29. with tf.variable_scope('in_hidden'):
  30. self.add_input_layer()
  31. with tf.variable_scope('LSTM_cell'):
  32. self.add_cell()
  33. with tf.variable_scope('out_hidden'):
  34. self.add_output_layer()
  35. with tf.name_scope('cost'):
  36. self.compute_cost()
  37. with tf.name_scope('train'):
  38. self.train_op = tf.train.AdamOptimizer(LR).minimize(self.cost)
  39. def add_input_layer(self,):
  40. l_in_x = tf.reshape(self.xs, [-1, self.input_size], name='2_2D')
  41. Ws_in = self._weight_variable([self.input_size, self.cell_size])
  42. bs_in = self._bias_variable([self.cell_size,])
  43. with tf.name_scope('Wx_plus_b'):
  44. l_in_y = tf.matmul(l_in_x, Ws_in) + bs_in
  45. self.l_in_y = tf.reshape(l_in_y, [-1, self.n_steps, self.cell_size], name='2_3D')
  46. def add_cell(self):
  47. lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(self.cell_size, forget_bias=1.0, state_is_tuple=True)
  48. with tf.name_scope('initial_state'):
  49. self.cell_init_state = lstm_cell.zero_state(self.batch_size, dtype=tf.float32)
  50. self.cell_outputs, self.cell_final_state = tf.nn.dynamic_rnn(
  51. lstm_cell, self.l_in_y, initial_state=self.cell_init_state, time_major=False)
  52. def add_output_layer(self):
  53. l_out_x = tf.reshape(self.cell_outputs, [-1, self.cell_size], name='2_2D')
  54. Ws_out = self._weight_variable([self.cell_size, self.output_size])
  55. bs_out = self._bias_variable([self.output_size, ])
  56. shape = (batch * steps, output_size)
  57. with tf.name_scope('Wx_plus_b'):
  58. self.pred = tf.matmul(l_out_x, Ws_out) + bs_out
  59. def compute_cost(self):
  60. losses = tf.contrib.legacy_seq2seq.sequence_loss_by_example(
  61. [tf.reshape(self.pred, [-1], name='reshape_pred')],
  62. [tf.reshape(self.ys, [-1], name='reshape_target')],
  63. [tf.ones([self.batch_size * self.n_steps], dtype=tf.float32)],
  64. average_across_timesteps=True,
  65. softmax_loss_function=self.ms_error,
  66. name='losses'
  67. )
  68. with tf.name_scope('average_cost'):
  69. self.cost = tf.div(
  70. tf.reduce_sum(losses, name='losses_sum'),
  71. self.batch_size,
  72. name='average_cost')
  73. tf.summary.scalar('cost', self.cost)
  74. def ms_error(self, y_target, y_pre):
  75. return tf.square(tf.sub( y_target, y_pre))
  76. def _weight_variable(self, shape, name='weights'):
  77. initializer = tf.random_normal_initializer(mean=0., stddev=1.,)
  78. return tf.get_variable(shape=shape, initializer=initializer, name=name)
  79. def _bias_variable(self, shape, name='biases'):
  80. initializer = tf.constant_initializer(0.1)
  81. return tf.get_variable(name=name, shape=shape, initializer=initializer)
  82. if __name__ == '__main__':
  83. model = LSTMRNN(TIME_STEPS, INPUT_SIZE, OUTPUT_SIZE, CELL_SIZE, BATCH_SIZE)
  84. sess = tf.Session()
  85. merged=tf.summary.merge_all()
  86. writer=tf.summary.FileWriter("niu0127/logs0127",sess.graph)
  87. sess.run(tf.global_variables_initializer())


相关文章
TF之RNN:TensorBoard可视化之基于顺序的RNN回归案例实现蓝色正弦虚线预测红色余弦实线
 

网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。

本文链接:https://www.xckfsq.com/news/show.html?id=4236
赞同 0
评论 0 条
鳗鱼有芒果L0
粉丝 0 发表 4 + 关注 私信
上周热门
如何使用 StarRocks 管理和优化数据湖中的数据?  2941
【软件正版化】软件正版化工作要点  2860
统信UOS试玩黑神话:悟空  2819
信刻光盘安全隔离与信息交换系统  2712
镜舟科技与中启乘数科技达成战略合作,共筑数据服务新生态  1246
grub引导程序无法找到指定设备和分区  1213
华为全联接大会2024丨软通动力分论坛精彩议程抢先看!  163
点击报名 | 京东2025校招进校行程预告  162
2024海洋能源产业融合发展论坛暨博览会同期活动-海洋能源与数字化智能化论坛成功举办  160
华为纯血鸿蒙正式版9月底见!但Mate 70的内情还得接着挖...  157
本周热议
我的信创开放社区兼职赚钱历程 40
今天你签到了吗? 27
信创开放社区邀请他人注册的具体步骤如下 15
如何玩转信创开放社区—从小白进阶到专家 15
方德桌面操作系统 14
我有15积分有什么用? 13
用抖音玩法闯信创开放社区——用平台宣传企业产品服务 13
如何让你先人一步获得悬赏问题信息?(创作者必看) 12
2024中国信创产业发展大会暨中国信息科技创新与应用博览会 9
中央国家机关政府采购中心:应当将CPU、操作系统符合安全可靠测评要求纳入采购需求 8

加入交流群

请使用微信扫一扫!