Created
December 25, 2014 11:06
-
-
Save adokoy001/04d0c875be52d6778b26 to your computer and use it in GitHub Desktop.
Perl : PDLを使って偏相関係数行列を生成
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use PDL; | |
use PDL::Stats::Basic; | |
# モジュール化するまでも無いのでgistに載せます。 | |
# ランダム要素を無くすと出力がInfになったりするのでそこはご愛嬌ということで。 | |
# また、対角要素は-1になってしまいます。 | |
# 偏相関係数行列を求める関数 | |
sub partial_corr{ | |
my $data = shift; | |
my $pdl = pdl $data; | |
my $corr = corr_table($pdl->transpose); | |
my $inv = inv $corr; | |
my $d = $inv->diagonal(0,1); | |
my $i = -$inv / sqrt(outer($d,$d)); | |
return $i; | |
} | |
# 以下デモ部分 | |
# データを生成して確認 | |
my $data; | |
for(1 .. 100000){ | |
my $tmp_1 = rand(100); # データ1 | |
my $tmp_2 = rand(100); # データ2 | |
my $tmp_3 = $tmp_1 + rand(10); # データ1と相関のあるデータ3 | |
my $tmp_4 = $tmp_2 + rand(10); # データ2と相関のあるデータ4 | |
my $tmp_5 = $tmp_1 + $tmp_2 + rand(10); # データ1,2と相関のあるデータ5 | |
my $tmp_6 = $tmp_3 + $tmp_4 + rand(10); # データ3,4と相関のあるデータ6 | |
my $tmp_7 = rand(100); # どのデータとも相関の無いデータ7 | |
push(@$data,[$tmp_1,$tmp_2,$tmp_3,$tmp_4,$tmp_5,$tmp_6,$tmp_7]); | |
} | |
my $pc = partial_corr($data); | |
print $pc; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment