楼主: Lisrelchen
2961 10

【GitHub】TensorFlow Tutorial for Time Series Prediction [推广有奖]

  • 0关注
  • 62粉丝

VIP

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
49957 个
通用积分
79.5487
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
TensorFlow Tutorial for Time Series Prediction
  1. TensorFlow Tutorial for Time Series Prediction

  2. This tutorial is designed to easily learn TensorFlow for time series prediction. Each tutorial subject includes both code and notebook with descriptions.

  3. Tutorial Index

  4. MNIST classification using Recurrent Neural Networks (RNN)

  5. Classification for MNIST using RNN (notebook)
  6. Time series prediction using Recurrent Neural Networks (RNN)

  7. Prediction for sine wave function using Gaussian process (code / notebook)
  8. Prediction for sine wave function using RNN (code / notebook)
  9. Prediction for electricity price (code / notebook)
  10. Slide materials

  11. Slides on slideshare (TensorFlow-KR Meetup)
  12. Slides on github (KSC 2016 Tutorial)
复制代码

本帖隐藏的内容

https://github.com/tgjeon/TensorFlow-Tutorials-for-Time-Series


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Time Series Prediction Tutorial predict Tensor Series

本帖被以下文库推荐

沙发
Lisrelchen 发表于 2017-4-26 10:18:26 |只看作者 |坛友微信交流群
  1. # coding: utf-8

  2. # ## Prediction sine wave function using Gaussian Process
  3. #
  4. # An example for Gaussian process algorithm to predict sine wave function.
  5. # This example is from ["Gaussian Processes regression: basic introductory example"](http://scikit-learn.org/stable/auto_examples/gaussian_process/plot_gp_regression.html).

  6. import numpy as np
  7. from sklearn.gaussian_process import GaussianProcess
  8. from matplotlib import pyplot as pl
  9. %matplotlib inline

  10. np.random.seed(1)


  11. # The function to predict
  12. def f(x):
  13.     return x*np.sin(x)


  14. # --------------------------
  15. #  First the noiseless case
  16. # --------------------------

  17. # Obervations
  18. X = np.atleast_2d([0., 1., 2., 3., 5., 6., 7., 8., 9.5]).T
  19. y = f(X).ravel()

  20. #X = np.atleast_2d(np.linspace(0, 100, 200)).T

  21. # Mesh the input space for evaluations of the real function, the prediction and its MSE
  22. x = np.atleast_2d(np.linspace(0, 10, 1000)).T

  23. # Instanciate a Gaussian Process model
  24. gp = GaussianProcess(corr='cubic', theta0=1e-2, thetaL=1e-4, thetaU=1e-1,
  25.                      random_start=100)

  26. # Fit to data using Maximum Likelihood Estimation of the parameters
  27. gp.fit(X, y)

  28. # Make the prediction on the meshed x-axis (ask for MSE as well)
  29. y_pred, MSE = gp.predict(x, eval_MSE=True)
  30. sigma = np.sqrt(MSE)


  31. # Plot the function, the prediction and the 95% confidence interval based on the MSE
  32. fig = pl.figure()
  33. pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$')
  34. pl.plot(X, y, 'r.', markersize=10, label=u'Observations')
  35. pl.plot(x, y_pred, 'b-', label=u'Prediction')
  36. pl.fill(np.concatenate([x, x[::-1]]),
  37.         np.concatenate([y_pred - 1.9600 * sigma,
  38.                        (y_pred + 1.9600 * sigma)[::-1]]),
  39.         alpha=.5, fc='b', ec='None', label='95% confidence interval')
  40. pl.xlabel('$x$')
  41. pl.ylabel('$f(x)$')
  42. pl.ylim(-10, 20)
  43. pl.legend(loc='upper left')


  44. # now the noisy case
  45. X = np.linspace(0.1, 9.9, 20)
  46. X = np.atleast_2d(X).T

  47. # Observations and noise
  48. y = f(X).ravel()
  49. dy = 0.5 + 1.0 * np.random.random(y.shape)
  50. noise = np.random.normal(0, dy)
  51. y += noise

  52. # Mesh the input space for evaluations of the real function, the prediction and
  53. # its MSE
  54. x = np.atleast_2d(np.linspace(0, 10, 1000)).T

  55. # Instanciate a Gaussian Process model
  56. gp = GaussianProcess(corr='squared_exponential', theta0=1e-1,
  57.                      thetaL=1e-3, thetaU=1,
  58.                      nugget=(dy / y) ** 2,
  59.                      random_start=100)

  60. # Fit to data using Maximum Likelihood Estimation of the parameters
  61. gp.fit(X, y)

  62. # Make the prediction on the meshed x-axis (ask for MSE as well)
  63. y_pred, MSE = gp.predict(x, eval_MSE=True)
  64. sigma = np.sqrt(MSE)

  65. # Plot the function, the prediction and the 95% confidence interval based on
  66. # the MSE
  67. fig = pl.figure()
  68. pl.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$')
  69. pl.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label=u'Observations')
  70. pl.plot(x, y_pred, 'b-', label=u'Prediction')
  71. pl.fill(np.concatenate([x, x[::-1]]),
  72.         np.concatenate([y_pred - 1.9600 * sigma,
  73.                        (y_pred + 1.9600 * sigma)[::-1]]),
  74.         alpha=.5, fc='b', ec='None', label='95% confidence interval')
  75. pl.xlabel('$x$')
  76. pl.ylabel('$f(x)$')
  77. pl.ylim(-10, 20)
  78. pl.legend(loc='upper left')

  79. pl.show()
复制代码

使用道具

藤椅
Lisrelchen 发表于 2017-4-26 10:19:03 |只看作者 |坛友微信交流群
  1. # coding: utf-8

  2. # In[13]:

  3. # get_ipython().magic('matplotlib inline')
  4. import numpy as np
  5. from matplotlib import pyplot as plt

  6. from tensorflow.contrib import learn
  7. from sklearn.metrics import mean_squared_error, mean_absolute_error
  8. from lstm_predictor import generate_data, lstm_model


  9. # ## Libraries
  10. #
  11. # - numpy: package for scientific computing
  12. # - pandas: data structures and data analysis tools
  13. # - tensorflow: open source software library for machine intelligence
  14. # - matplotlib: 2D plotting library
  15. #
  16. #
  17. # - **learn**: Simplified interface for TensorFlow (mimicking Scikit Learn) for Deep Learning
  18. # - mse: "mean squared error" as evaluation metric
  19. # - **lstm_predictor**: our lstm class
  20. #

  21. # In[14]:

  22. LOG_DIR = './ops_logs'
  23. TIMESTEPS = 5
  24. RNN_LAYERS = [{'steps': TIMESTEPS}]
  25. DENSE_LAYERS = [10, 10]
  26. TRAINING_STEPS = 100000
  27. BATCH_SIZE = 100
  28. PRINT_STEPS = TRAINING_STEPS / 100


  29. # ## Parameter definitions
  30. #
  31. # - LOG_DIR: log file
  32. # - TIMESTEPS: RNN time steps
  33. # - RNN_LAYERS: RNN layer 정보
  34. # - DENSE_LAYERS: DNN 크기 [10, 10]: Two dense layer with 10 hidden units
  35. # - TRAINING_STEPS: 학습 스텝
  36. # - BATCH_SIZE: 배치 학습 크기
  37. # - PRINT_STEPS: 학습 과정 중간 출력 단계 (전체의 1% 해당하는 구간마다 출력)

  38. # In[15]:

  39. regressor = learn.TensorFlowEstimator(model_fn=lstm_model(TIMESTEPS, RNN_LAYERS, DENSE_LAYERS),
  40.                                       n_classes=0,
  41.                                       verbose=1,  
  42.                                       steps=TRAINING_STEPS,
  43.                                       optimizer='Adagrad',
  44.                                       learning_rate=0.03,
  45.                                       batch_size=BATCH_SIZE)


  46. # ## Create a regressor with TF Learn
  47. #
  48. # : 예측을 위한 모델 생성. TF learn 라이브러리에 제공되는 TensorFlowEstimator를 사용.
  49. #
  50. # **Parameters**:
  51. #
  52. # - model_fn: 학습 및 예측에 사용할 모델
  53. # - n_classes: label에 해당하는 클래스 수 (0: prediction, 1이상: classification) 확인필요
  54. # - verbose: 과정 출력
  55. # - steps: 학습 스텝
  56. # - optimizer: 최적화 기법 ("SGD", "Adam", "Adagrad")
  57. # - learning_rate: learning rate
  58. # - batch_size: batch size
  59. #
  60. #

  61. # In[ ]:

  62. X, y = generate_data(np.sin, np.linspace(0, 100, 10000), TIMESTEPS, seperate=False)
  63. # create a lstm instance and validation monitor

  64. validation_monitor = learn.monitors.ValidationMonitor(X['val'], y['val'],
  65.                                                       every_n_steps=PRINT_STEPS,
  66.                                                       early_stopping_rounds=1000)


  67. # ## Generate a dataset
  68. #
  69. # 1. generate_data: 학습에 사용될 데이터를 특정 함수를 이용하여 만듭니다.
  70. #  - fct: 데이터를 생성할 함수
  71. #  - x: 함수값을 관측할 위치
  72. #  - time_steps: 관측(observation)
  73. #  - seperate: check multimodal
  74. # 1. ValidationMonitor: training 이후, validation 과정을 모니터링
  75. #  - x
  76. #  - y
  77. #  - every_n_steps: 중간 출력
  78. #  - early_stopping_rounds

  79. # In[16]:

  80. regressor.fit(X['train'], y['train'], monitors=[validation_monitor], logdir=LOG_DIR)


  81. # ## Train and validation
  82. #
  83. # - fit: training data를 이용해 학습, 모니터링과 로그를 통해 기록
  84. #
  85. #

  86. # In[17]:

  87. predicted = regressor.predict(X['test'])
  88. mse = mean_squared_error(y['test'], predicted)
  89. print ("Error: %f" % mse)


  90. # ## Evaluate using test set
  91. #
  92. # Evaluate our hypothesis using test set. The mean squared error (MSE) is used for the evaluation metric.
  93. #
  94. #

  95. # In[18]:

  96. plot_predicted, = plt.plot(predicted, label='predicted')
  97. plot_test, = plt.plot(y['test'], label='test')
  98. plt.legend(handles=[plot_predicted, plot_test])



  99. # ## Plotting
  100. #
  101. # Then, plot both predicted values and original values from test set.
复制代码

使用道具

板凳
Lisrelchen 发表于 2017-4-26 10:19:36 |只看作者 |坛友微信交流群
  1. import numpy as np
  2. import pandas as pd
  3. from matplotlib import pyplot as plt

  4. from tensorflow.contrib import learn
  5. from sklearn.metrics import mean_squared_error, mean_absolute_error
  6. from lstm_predictor import generate_data, load_csvdata, lstm_model


  7. LOG_DIR = './ops_logs'
  8. TIMESTEPS = 10
  9. RNN_LAYERS = [{'steps': TIMESTEPS}]
  10. DENSE_LAYERS = [10, 10]
  11. TRAINING_STEPS = 100000
  12. BATCH_SIZE = 100
  13. PRINT_STEPS = TRAINING_STEPS / 100

  14. dateparse = lambda dates: pd.datetime.strptime(dates, '%d/%m/%Y %H:%M')
  15. rawdata = pd.read_csv("./input/ElectricityPrice/RealMarketPriceDataPT.csv",
  16.                    parse_dates={'timeline': ['date', '(UTC)']},
  17.                    index_col='timeline', date_parser=dateparse)


  18. X, y = load_csvdata(rawdata, TIMESTEPS, seperate=False)


  19. regressor = learn.TensorFlowEstimator(model_fn=lstm_model(TIMESTEPS, RNN_LAYERS, DENSE_LAYERS),
  20.                                       n_classes=0,
  21.                                       verbose=1,  
  22.                                       steps=TRAINING_STEPS,
  23.                                       optimizer='Adagrad',
  24.                                       learning_rate=0.03,
  25.                                       batch_size=BATCH_SIZE)




  26. validation_monitor = learn.monitors.ValidationMonitor(X['val'], y['val'],
  27.                                                       every_n_steps=PRINT_STEPS,
  28.                                                       early_stopping_rounds=1000)

  29. regressor.fit(X['train'], y['train'], monitors=[validation_monitor], logdir=LOG_DIR)


  30. predicted = regressor.predict(X['test'])
  31. mse = mean_absolute_error(y['test'], predicted)
  32. print ("Error: %f" % mse)

  33. plot_predicted, = plt.plot(predicted, label='predicted')
  34. plot_test, = plt.plot(y['test'], label='test')
  35. plt.legend(handles=[plot_predicted, plot_test])
复制代码

使用道具

报纸
MouJack007 发表于 2017-4-26 12:20:59 |只看作者 |坛友微信交流群
谢谢楼主分享!
已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

使用道具

地板
MouJack007 发表于 2017-4-26 12:21:20 |只看作者 |坛友微信交流群

使用道具

7
ithjesuxf 发表于 2017-4-26 23:23:45 |只看作者 |坛友微信交流群
thanks for sharing
已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

使用道具

8
fakechris 发表于 2017-5-7 13:47:32 |只看作者 |坛友微信交流群
谢谢楼主分享

使用道具

9
注销··· 发表于 2017-7-5 14:54:36 |只看作者 |坛友微信交流群
good sharing!

使用道具

10
argmax124 发表于 2017-10-18 13:19:57 |只看作者 |坛友微信交流群
感谢楼主分享

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-24 22:32