首页 > 解决方案 > 是否有用于使用 gramian-angular-fields-method (gaf/gasf) 将时间序列编码为图像的 R 函数?

问题描述

我想使用 gramian-angular-fields-method (GAF) 将时间序列编码为图像,目的是应用卷积神经网络 (CNN)。到目前为止,我还没有找到实现此功能的 R 函数。

对于 Python,我发现以下内容: https ://github.com/pecu/Series2GAF

我也尝试自己编写一个函数,但我不确定它是否正常工作。这是这篇文章,提出了 GAF 方法: https ://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=6&ved=2ahUKEwjS5a2PxJjiAhUPIlAKHVj4BBMQFjAFegQIABAC&url=https%3A%2F%2Fwww.aaai.org %2Focs%2Findex.php%2FWS%2FAAAIW15%2Fpaper%2FviewFile%2F10179%2F10251&usg=AOvVaw0uFl_9ZuLwCRvF_BouOxnV

这是我的代码,其中包含存储在 x 中的时间序列值的示例: x 只是一个向量,其测量值按日期排序,例如

library('tidyverse')
library('reshape2')
library('ggplot2')

x <- tibble(values = sin(-10:6))

复制本文方程 1、2 和 3 的函数:

gramian_angular_field_custom <- function(x){
  # Delete column names
  names(x) <- NULL

  # Convert to matrix
  x <- x %>% as.matrix()

  # Normalize
  x <- (x - max(x) + (x - min(x))) / (max(x) -min(x))
  x <- x %>% as.matrix()

  # Calculate phi for polar coordinates
  x <- x %>%
    as_tibble() %>%
    mutate(V1 = acos(V1)) %>%
    as.matrix() %>%
    t()

  # Create matrix by column repeat
  x <- x %>%
    t() %>%
    as_tibble() %>%
    replicate(n = length(x), .) %>%
    bind_cols()

  # Calculate sum of phi
  x <- x + as_tibble(t(x))
  x <- x %>% as_tibble()

  # Calculate cosinus
  x <- x %>% cos()

  x <- x %>% as.matrix()
  colnames(x) <- NULL

  # convert matrix to tibble in long format
  x <- x %>% 
    melt() %>% 
    as_tibble()

  return(x)
}

然后应用此函数并绘制结果图像:

x %>% 
  gramian_angular_field_custom() %>% 
  ggplot(aes(Var2, Var1)) +
  geom_raster(aes(fill = value)) +
  scale_fill_gradientn(colours = c('blue', 'green', 'yellow', 'red')) +
  theme(legend.position = "none",
        axis.title.x = element_blank(),
        axis.title.y = element_blank())

生成的图像与对角线不是轴对称的,应该是这样,还是我错了?任何关于数学的建议都可以作为实现这一点的 R 函数的提示。

非常感谢

标签: rencodingtime-series

解决方案


您可以使用 python 模块pyts和 R 包reticulate从 R 运行 python 代码。


推荐阅读