将宏的结果存储到表中

如何解决将宏的结果存储到表中

我在 R 中找到了一个我想要迭代不同值的过程。

原始过程如下所示(完全在基 R 中运行):

# A minimalistic Echo State Networks demo with Mackey-Glass (delay 17) data 
# in "plain" R.
# by Mantas Lukosevicius 2012-2018
# http://mantas.info

myfile <- read.table(url("https://mantas.info/wp/wp-content/uploads/simple_esn/MackeyGlass_t17.txt"))

# load the data
trainLen = 2000
testLen = 2000
initLen = 100
data = as.matrix(myfile)

# plot some of it
while( dev.cur() != 1 ) dev.off() # close all previous plots
dev.new()
plot(data[1:1000],type='l')
title(main='A sample of data')

# generate the ESN reservoir
inSize = outSize = 1
resSize = 1000
a = 0.3 # leaking rate

set.seed(42)
Win = matrix(runif(resSize*(1+inSize),-0.5,0.5),resSize)
W = matrix(runif(resSize*resSize,resSize)

# normalizing and setting spectral radius
cat('Computing spectral radius...')
rhoW = abs(eigen(W,only.values=TRUE)$values[1])
print('done.')
W = W * 1.25 / rhoW

# allocated memory for the design (collected states) matrix
X = matrix(0,1+inSize+resSize,trainLen-initLen)
# set the corresponding target matrix directly
Yt = matrix(data[(initLen+2):(trainLen+1)],1)

# run the reservoir with the data and collect X
x = rep(0,resSize)
for (t in 1:trainLen){
    u = data[t]
    x = (1-a)*x + a*tanh( Win %*% rbind(1,u) + W %*% x )
    if (t > initLen)
        X[,t-initLen] = rbind(1,u,x)
}

# train the output
reg = 1e-8  # regularization coefficient
X_T = t(X)
Wout = Yt %*% X_T %*% solve( X %*% X_T + reg*diag(1+inSize+resSize) )

# run the trained ESN in a generative mode. no need to initialize here,# because x is initialized with training data and we continue from there.
Y = matrix(0,outSize,testLen)
u = data[trainLen+1]
for (t in 1:testLen){
    x = (1-a)*x + a*tanh( Win %*% rbind(1,u) + W %*% x )
    y = Wout %*% rbind(1,x)
    Y[,t] = y
    # generative mode:
    u = y
    # this would be a predictive mode:
    #u = data[trainLen+t+1] 
}

# compute MSE for the first errorLen time steps
errorLen = 500
mse = ( sum( (data[(trainLen+2):(trainLen+errorLen+1)] - Y[1,1:errorLen])^2 )
    / errorLen )
print( paste( 'MSE = ',mse ) )

# plot some signals
dev.new() 
plot( data[(trainLen+1):(trainLen+testLen+1)],type='l',col='green' )
lines( c(Y),col='blue' )
title(main=expression(paste('Target and generated signals ',bold(y)(italic(n)),' starting at ',italic(n)==0 )))
legend('bottomleft',legend=c('Target signal','Free-running predicted signal'),col=c('green','blue'),lty=1,bty='n' )

dev.new()
matplot( t(X[(1:20),(1:200)]),type='l' )
title(main=expression(paste('Some reservoir activations ',bold(x)(italic(n)))))

dev.new()
barplot( Wout )
title(main=expression(paste('Output weights ',bold(W)^{out})))

我想为参数“resSize”和“a”的不同值运行此过程。经过一些研究和大量的反复试验,我能够弄清楚如何为“resSize”的 3 个不同值和“a”的 3 个不同值循环上述过程 - 总共 9 个值。见下文:

myfile <- read.table(url("https://mantas.info/wp/wp-content/uploads/simple_esn/MackeyGlass_t17.txt"))

# load the data
trainLen = 2000
testLen = 2000
initLen = 100
data = as.matrix(myfile)

# plot some of it
while( dev.cur() != 1 ) dev.off() # close all previous plots
dev.new()
plot(data[1:1000],type='l')
title(main='A sample of data')

# LOOP generate the ESN reservoir,different reservoir sizes and leakage rates
inSize = outSize = 1
for (resSize in c(100,500,1000)) {
    for (a in c(0.3,0.5,0.7))     {
    ### resSize = 1000
    ### a = 0.3 # leaking rate

    set.seed(42)
    Win = matrix(runif(resSize*(1+inSize),resSize)
    W = matrix(runif(resSize*resSize,resSize)

    # normalizing and setting spectral radius
    cat('Computing spectral radius...')
    rhoW = abs(eigen(W,only.values=TRUE)$values[1])
    print('done.')
    W = W * 1.25 / rhoW

    # allocated memory for the design (collected states) matrix
    X = matrix(0,trainLen-initLen)
    # set the corresponding target matrix directly
    Yt = matrix(data[(initLen+2):(trainLen+1)],1)

    # run the reservoir with the data and collect X
    x = rep(0,resSize)
      for (t in 1:trainLen){
      u = data[t]
      x = (1-a)*x + a*tanh( Win %*% rbind(1,u) + W %*% x )
      if (t > initLen)
          X[,x)
      }

      # train the output
      reg = 1e-8  # regularization coefficient
      X_T = t(X)
      Wout = Yt %*% X_T %*% solve( X %*% X_T + reg*diag(1+inSize+resSize) )

      # run the trained ESN in a generative mode. no need to initialize here,# because x is initialized with training data and we continue from there.
      Y = matrix(0,testLen)
      u = data[trainLen+1]
      for (t in 1:testLen) {
      x = (1-a)*x + a*tanh( Win %*% rbind(1,u) + W %*% x )
      y = Wout %*% rbind(1,x)
      Y[,t] = y
      # generative mode:
      u = y
      # this would be a predictive mode:
      #u = data[trainLen+t+1]
      }

  # compute MSE for the first errorLen time steps
  errorLen = 500
  mse = ( sum( (data[(trainLen+2):(trainLen+errorLen+1)] - Y[1,1:errorLen])^2 )
/ errorLen )
  print( paste( 'Reservoir Size =',resSize))
  print( paste( 'Leakage Rate =',a))
  print( paste( 'MSE = ',mse ) )

  # plot some signals
  dev.new()
  plot( data[(trainLen+1):(trainLen+testLen+1)],col='green' )
  lines( c(Y),col='blue' )
  title(main=expression(paste('Target and generated signals ',italic(n)==0 )))
  legend('bottomleft',bty='n' )

  dev.new()
  matplot( t(X[(1:20),type='l' )
  title(main=expression(paste('Some reservoir activations ',bold(x)(italic(n)))))

 dev.new()
 barplot( Wout )
 title(main=expression(paste('Output weights ',bold(W)^{out})))

  }
}

这会输出 9 种不同的结果。我想弄清楚如何制作这些结果的表格(3 列“水库大小”、“泄漏率”和“MSE”)。现在,我正在将结果从 R 复制并粘贴到 Microsoft Excel 中。

有人可以告诉我一个更简单的方法吗?

谢谢

更新:G Grothendieck 提供的答案,见下文:

myfile <- read.table(url("https://mantas.info/wp/wp-content/uploads/simple_esn/MackeyGlass_t17.txt"))
mseDF <- NULL
# load the data
trainLen = 2000
testLen = 2000
initLen = 100
data = as.matrix(myfile)

# plot some of it
while( dev.cur() != 1 ) dev.off() # close all previous plots
dev.new()
plot(data[1:1000],bold(W)^{out})))

 mseDF <- rbind(mseDF,data.frame(resSize,a,mse)) }
}

解决方法

1) 使用问题中修改后的代码,在第一个for之前插入这一行来初始化mseDF

mseDF <- NULL

并在倒数第二个}之前插入这一行以向其追加一行:

mseDF <- rbind(mseDF,data.frame(resSize,a,mse))

代码完成后,mseDF 将是一个如下所示的数据框:

mseDF
##   resSize   a          mse
## 1     100 0.3 1.652439e-02
## 2     100 0.5          Inf
## 3     100 0.7 1.237748e+05
## 4     500 0.3 2.955434e-06
## 5     500 0.5 1.083321e-05
## 6     500 0.7 1.446731e-05
## 7    1000 0.3 1.820381e-06
## 8    1000 0.5 4.680945e-06
## 9    1000 0.7 1.299191e-04

或者如果您更喜欢 mse 值的 2d 表,则像这样转换 mseDF

xtabs(mse ~.,mseDF)
##        a
## resSize          0.3          0.5          0.7
##    100  1.652439e-02          Inf 1.237748e+05
##    500  2.955434e-06 1.083321e-05 1.446731e-05
##    1000 1.820381e-06 4.680945e-06 1.299191e-04

2) 另一种方法是创建一个 mseFun 函数,该函数计算每个输入的一个值的 mse,然后将其应用于网格 g 的每一行以生成数据框结果。这里我们将使用一个简单版本的 mseFun 来说明:

mseFun <- function(resSize,a) {
  a + resSize # replace this with your calculation of mse
}

g <- expand.grid(resSize = c(100,500,1000),a = c(0.3,0.5,0.7)) # 9x2
transform(g,mse = mapply(mseFun,resSize,a))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-