【发布时间】:2016-10-20 05:04:53
【问题描述】:
这就是我正在尝试使用 AWK 语言做的事情。我主要是第 2 步有问题。我展示了一个示例数据集,但原始数据集包含 100 个字段和 2000 条记录。
算法
1) 初始化精度 = 0
2) 对于每条记录 r
Find the closest other record, o, in the dataset using distance formula
要找到 r0 的最近邻居,我需要将 r0 与 r1 与 r9 进行比较,然后进行如下数学运算:square(abs(r0.c1 - r1.c1)) + square(abs(r0.c2 - r1.c2)) + ...+square(abs(r0.c5 - r1.c5)) 并存储这些距离。
3) 距离最小的一个,比较它的 c6 值。如果 c6 值相等,则精度增加 1。
对所有记录重复该过程后。
4) 最后,得到 1nn 的准确率百分比 (准确度/total_records)* 100;
样本数据集
c1 c2 c3 c4 c5 c6 --> Columns
r0 0.19 0.33 0.02 0.90 0.12 0.17 --> row1 & row7 nearest neighbour in c1
r1 0.34 0.47 0.29 0.32 0.20 1.00 and same values in c6(0.3) so ++accuracy
r2 0.37 0.72 0.34 0.60 0.29 0.15
r3 0.43 0.39 0.40 0.39 0.32 0.27
r4 0.27 0.41 0.08 0.19 0.10 0.18
r5 0.48 0.27 0.68 0.23 0.41 0.25
r6 0.52 0.68 0.40 0.75 0.75 0.35
r7 0.55 0.59 0.61 0.56 0.74 0.76
r8 0.04 0.14 0.03 0.24 0.27 0.37
r9 0.39 0.07 0.07 0.08 0.08 0.89
代码
BEGIN {
#initialize accuracy and total_records
accuracy = 0;
total_records = 10;
}
NR==FNR { # Loop through each record and store it in an array
for (i=1; i<=NF; i++)
{
records[i]=$i;
}
next
}
{ # Re-Loop through the file and compare each record from the array with each record in a file
for(i=1; i <= length(records); i++)
{
for (j=1; j<=NF; j++)
{ # here I need to get the difference of each field of the record[i] with each all the records, square them and sum it up.
distance[j] = (records[i] - $j)^2;
}
#Once I have all the distance, I can simply compare the values of field_6 for the record with least distance.
if(min(distance[j]))
{
if(records[$6] == $6)
{
++accuracy;
}
}
}
END{
percentage = 100 * (accuracy/total_records);
print percentage;
}
【问题讨论】:
-
你的意思是,fields[i] = print $i;并将所有字段存储在一个数组中?尽管字段是独立的,但是一旦找到最近的行,我将需要找到将在字段 [6] 中的 class_value。如果我分别对每个字段进行排序,我就会混淆数据。你能解释一下如何实现你的想法吗?
-
您在描述中加入了 cmets,所以现在通过您的编辑,实际问题是什么? IE。第 2 步有什么困难?
-
我不知道如何为两条记录的每个字段应用公式(包括平方和求和)。这一点是错误的 ->> distance[j] = (records[i] - $j);
标签: bash shell awk text-processing gawk