我有这样的数据
#Status value
TP 5.000
TP 3.000
TP 3.000
TN 10.000
TP 2.000
TP 9.000
TN 1.000
TP 9.000
TN 1.000
我们要做的是根据value
中给定的时间间隔对状态进行聚类。设该间隔为1-3, 4-6, 7-9, 10-12, etc ..
(即斌大小3)。
我们希望得到如下数组的散列:
my %hoa = (
'1-3' => [TP,TP,TP,TN,TN],
'4-6' => [TP],
'7-9' => [TP,TP],
'10-12' => [TN]);
实现这一目标的方法是什么?
Update:由于ysth,更正了7-9
的HoA。
发布于 2010-11-08 03:35:23
提取代码以确定间隔:
sub interval {
my ($val) = @_;
my $i = int( ( $val + 2 ) / 3 );
my $interval = sprintf( '%d-%d', $i * 3 -2, $i * 3 );
return $interval;
}
my %hoa;
while ( my $line = <> ) {
next if $line =~ /^#/;
my ($status, $value) = split ' ', $line;
push @{ $hoa{ interval($value) } }, $status;
}
use Data::Dumper;
print Dumper \%hoa;
( 7-9有两个TPs,而不是你显示的一个)。
发布于 2010-11-08 06:57:33
ysth的回答也是我的第一件事,我认为他有正确的方法。
我只想留下一个建议:您可以使用聚类算法以一种未来证明的方式(例如,当您的数据变得多维时)为您完成这一任务。例如,K-指可以正常工作,即使是你的一维数据也是如此。
例如:
use strict; use warnings;
use Algorithm::KMeans;
my $datafile = $ARGV[0] or die;
my $K = $ARGV[1] or 0;
my $mask = 'N1';
my $clusterer = Algorithm::KMeans->new(
datafile => $datafile,
mask => $mask,
K => $K,
terminal_output => 0,
);
$clusterer->read_data_from_file();
my ($clusters, $cluster_centers) = $clusterer->kmeans();
my %clusters;
while (@$clusters) {
my $cluster = shift @$clusters;
my $center = shift @$cluster_centers;
$clusters{"@$center"} = $cluster;
}
use YAML; print Dump \%clusters;
https://stackoverflow.com/questions/4120995
复制相似问题