stMind

about Tech, Computer vision and Machine learning

perl de 集合知プログラミング(5.5)

今までソースコードの中にデータセットを直接書いていましたが、データセットのファイルを別に用意して読み込むように変更しました。

データセット

用意したのは、以下のようなJSONフォーマットのファイルです。
ciritics.json

{
    "Lisa Rose" :  {
	"Lady in the Water" : 2.5, 
	"Snakes on a Plane" : 3.5, 
	"Just My Luck" : 3.0, 
	"Superman Returns" : 3.5, 
	"You, Me and Dupree" : 2.5,
	"The Night Listener" : 3.0
    },
    "Gene Seymour" :  {
	"Lady in the Water" : 3.0, 
	"Snakes on a Plane" : 3.5, 
	"Just My Luck" : 1.5, 
	"Superman Returns" : 5.0, 
	"The Night Listener" : 3.0,
	"You, Me and Dupree" : 3.5
    },
    "Michael Phillips" :  {
	"Lady in the Water" : 2.5, 
	"Snakes on a Plane" : 3.0, 
	"Superman Returns" : 3.5, 
	"The Night Listener" : 4.0
    },
    "Claudia Puig" :  {
	"Snakes on a Plane" : 3.5, 
	"Just My Luck" : 3.0, 
	"The Night Listener" : 4.5,
	"Superman Returns" : 4.0, 
	"You, Me and Dupree" : 2.5
    },
    "Mick LaSalle" :  {
	"Lady in the Water" : 3.0, 
	"Snakes on a Plane" : 4.0,  
	"Just My Luck" : 2.0, 
	"Superman Returns" : 3.0, 
	"The Night Listener" : 3.0, 
	"You, Me and Dupree" : 2.0
    },
    "Jack Matthews" :  {
	"Lady in the Water" : 3.0, 
	"Snakes on a Plane" : 4.0, 
	"The Night Listener" : 3.0, 
	"Superman Returns" : 5.0, 
	"You, Me and Dupree" : 3.5
    },
    "Toby" :  {
	"Snakes on a Plane" : 4.5, 
	"Superman Returns" : 4.0, 
	"You, Me and Dupree" : 1.0
    }
}

データセットの読み込みと実行

これを読み込んでJSONからperlのデータ形式に変換して使用します。

my $json_file = $ARGV[0] || 'critics.json';
my $critics = conv_json2perl($json_file);
my %movies = transformPrefs(\%$critics);

conv_json2perlで実際のデコードを実行します。

# JSON形式をperlデータに変換
sub conv_json2perl {
    my $json_file = shift;
    
    # ファイルのオープン
    my $json_text;
    open(my $fh, "<", $json_file) or die "$!";
    {
	# ファイル全体を読み込む
	local $/ = undef;
	$json_text = <$fh>;
    }
    close $fh;

    # decode_json
    my $perl_data = decode_json($json_text);

    # ハッシュのリファレンスを返す
    return $perl_data;    
}

あとは、前回と同様に実行すれば類似する映画を推薦することができます。
ソースコードはgistに置いてあります。
gist: 489178 - GitHub

次は2.6節

「deliciousのリンクを推薦するシステムを作る」です。やっちゃうぞー。