使用r重复脚本

时间:2018-12-12 21:59:39

标签: r loops

我有以下脚本

Posdef <- function (n, ev = runif(n, 0, 10)) 
    {
    Z <- matrix(ncol=n, rnorm(n^2))
        decomp <- qr(Z)
        Q <- qr.Q(decomp) 
        R <- qr.R(decomp)
        d <- diag(R)
        ph <- d / abs(d)
        O <- Q %*% diag(ph)
        Z <- t(O) %*% diag(ev) %*% O
        return(Z)
    }

Sigma <- Posdef(n = 11)
mu <-  runif(11,0,10) 
data <- as.data.frame(mvrnorm(n=1000, mu, Sigma))
data[data <  0] <-  0 #setting a floor#
data[data >  10] <-  10 #setting a ceiling#
names(data) = c('criteria_1', 'criteria_2', 'criteria_3', 'criteria_4', 'criteria_5', 
            'criteria_6', 'criteria_7', 'criteria_8', 'criteria_9', 'criteria_10',
            'outcome')
data$outcome <- ifelse(data$outcome > 5, 1, 0)

data <- data[, sapply(data, is.numeric)]
maxValue <- as.numeric(apply (data, 2, max))
minValue <- as.numeric(apply (data, 2, min))

data_scaled <- as.data.frame(scale(data, center = minValue, 
scale = maxValue-minValue))

ind <- sample (1:nrow(data_scaled), 600)
train <- data_scaled[ind,]
test <- data_scaled[-ind,]

model <- glm (formula = 
    outcome ~ criteria_1 + criteria_2 + criteria_3 + criteria_4 + criteria_5 +
            criteria_6 + criteria_7 + criteria_8 + criteria_9 + criteria_10, 
    family = "binomial", 
    data = train)

summary (model)
predicted_model <- predict(model, test)

neural_model <- neuralnet(formula = 
    outcome ~ criteria_1 + criteria_2 + criteria_3 + criteria_4 + criteria_5 +
            criteria_6 + criteria_7 + criteria_8 + criteria_9 + criteria_10,
    hidden = c(2,2) ,
    threshold = 0.01, 
    stepmax = 1e+07,
    startweights = NULL,
    rep = 1,
    learningrate = NULL,
    algorithm = "rprop+",
    linear.output=FALSE, 
    data= train)

plot (neural_model)

results <- compute (neural_model, test[1:10])
results <- results$net.result*(max(data$outcome)-
min(data$outcome))+ min(data$outcome)
Values <- (test$outcome)*(max(data$outcome)- 
min(data$outcome)) + min(data$outcome)
MSE_nueral_model <- sum((results - Values)^2)/nrow(test)
MSE_model <- sum((predicted_model - test$outcome)^2)/nrow(test)

print(MSE_model - MSE_nueral_model)

R1 <- (MSE_model - MSE_nueral_model)

此脚本的目的是生成一些任意的多元分布,然后比较两种方法。在这种情况下,它是神经网络和逻辑回归。最终结果是均方差的差异。

现在,创建循环的问题一直是生成1000个观察值。

我能够在没有脚本的数据模拟部分的情况下创建一个循环,将其放入循环中似乎会使事情陷入困境。我尝试创建一个填充有NA的列向量,但最终得到的只是返回一个值,而不是循环的每次迭代的MSE减少所填充的长度为n的向量。

任何帮助将不胜感激。

0 个答案:

没有答案