-
Notifications
You must be signed in to change notification settings - Fork 0
/
4.R
53 lines (40 loc) · 1.3 KB
/
4.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
calcR <- function(trainMatr, x) {
apply(trainMatr, 1, function(row) sqrt(sum(( row - x )^2)))
}
calcD <- function(r, sigma = 1) {
exp(-(r/sigma)^2)
}
calcY <- function(d, y) sum(d*y)/sum(d)
grnn <- function(trainWithResults, x, windowSize, sigma = 0.01) {
train <- trainWithResults[,1:windowSize]
y_train <- trainWithResults[,windowSize+1]
r <- calcR(train, x)
d <- calcD(r, sigma)
y <- calcY(d, y_train)
y
}
generateTimeSeries <- function(f = "sin", end = 3 , step = 0.1) {
x <- seq(0, end, by=step)
if(f == "sin") y <- sin(2*pi*x)
if(f == "cos") y <- cos(2*pi*x)
y
}
windowSize <- 3
timeSeries <- generateTimeSeries()
input_data <- as.data.frame(t(timeSeries[0:windowSize+1]))
for(i in seq(2, length(timeSeries) - windowSize, 1) ) {
input_data[nrow(input_data)+1,] <- timeSeries[i:(i+windowSize)]
}
firstPredictIndex <- 20
train <- input_data[1:firstPredictIndex-1,]
test <- input_data[firstPredictIndex:nrow(input_data),]
result <- train[firstPredictIndex - 1,]
for(i in seq(1, nrow(test), 1) ) {
new_input <- result[i, 2:ncol(result)]
x_next <- grnn(train, new_input, windowSize)
result[i + 1,] <- c( as.numeric( new_input ), x_next)
}
test["Predicted value"] <- result[-1,windowSize+1]
colnames(test)[windowSize + 1] <- "Value"
test
#series.size - window == number of rows in new data