summaryrefslogtreecommitdiff
path: root/analysis/knn.R
blob: 71771f11ff3e5dd60de5ca92778bf2cd7936a408 (plain)
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
library("tidyverse")
library("class")

## Simulation Parameters:
## simkey         {baseline,extended,hint,hintandextended}
## wireless       {lora,nbiot}
## wakeupfor      {60s,180s}
## seed           [1,200]
## node           on[0,12]
## isSender       {0,1}
## dataSize       {1MB}

## Metrics:
## energy         [0,+inf)
## nDataRcv       [0,+inf)

nseed=200
nwakeupfor=2
nwireless=2
nsimkey=4
nsimulations=nseed*nwakeupfor*nwireless*nsimkey # Must be 3200

## Load data
data=read_csv("../CCGRID2022.csv")%>%distinct() # Note that in the data experiment wireless=="lora",seed==1,wakeupfor==60,simkey=="baseline" is present 2 times in the CSV file
tmp_data_coverage=data%>%group_by(simkey,wireless,wakeupfor,seed)%>%mutate(coverage=sum(nDataRcv))%>%ungroup()%>%filter(isSender==1)%>%select(simkey,wireless,wakeupfor,seed,coverage)
data_seed_isSender=data%>%group_by(simkey,wireless,wakeupfor,seed,isSender)%>%summarize(energy_mean=mean(energy))%>%
    left_join(tmp_data_coverage,by=c("simkey","wireless","wakeupfor","seed"))%>%
    mutate(efficiency=energy_mean/coverage)%>%
    ungroup()
data_seed=data%>%group_by(simkey,wireless,wakeupfor,seed)%>%summarize(energy=sum(energy),coverage=sum(nDataRcv))%>%
    mutate(efficiency=energy/coverage)%>%
    ungroup()


## Prepare data for knn
set.seed(1) # Reproducibility
data_seed=data_seed%>%select(-efficiency,-seed)%>%mutate(wireless=as.numeric(as.factor(data_seed$wireless)))

## Train
train_set=data_seed%>%sample_frac(0.8)     # 80% of the data
test_set=data_seed%>%anti_join(train_set)  # 20% of the data
classifier=knn(train=train_set%>%select(-simkey),test=test_set%>%select(-simkey),cl=train_set$simkey,k=10)

## Analysis
cont_table=table(classifier,test_set$simkey)
accuracy=round((sum(diag(cont_table)/sum(rowSums(cont_table))))*100)
prop_table=round(prop.table(cont_table),digits=2)
print(prop_table)
print(paste0("Overall KNN accuracy ",accuracy,"%"))