Rでロト6を当てたい(番外編)
前々回の冒頭の書籍には共連れ分析も記載されていたのでarulesパッケージを使って一緒によく出る組み合わせを探してみる。
arulesパッケージについては以下の記事が詳しくて参考になる。
R {arules} によるアソシエーション分析をちょっと詳しく <1> - StatsFragments
行非正規化
現在のデータ構造はLong-format形式となっているため、ItemMatrix形式に変換する
> library(tidyr) > nums.mat <- nums %>% + # aprioriはfactorかbooleanにする必要があるのでboolean型のvalue列を追加する + mutate(value = TRUE) %>% + # 欠損部分はFALSEで埋めてItemMatrix形式に変換 + spread(key=num, value=value, fill=FALSE) %>% + # 回の列を削除 + select(-time) >
aprioriによるrule抽出
ruleの抽出はapriori()で行なう。デフォルトのパラメータではruleが検出できなかったので緩めの設定に変更。
> # rule抽出 > library(arules) > rules <- apriori(nums.mat, parameter=list(support=0.02, confidence=0.1, minlen=2, maxlen=2, ext=TRUE)) Parameter specification: confidence minval smax arem aval originalSupport support minlen maxlen target ext 0.1 0.1 1 none FALSE TRUE 0.02 2 2 rules TRUE Algorithmic control: filter tree heap memopt load sort verbose 0.1 TRUE TRUE FALSE TRUE 2 TRUE apriori - find association rules with the apriori algorithm version 4.21 (2004.05.09) (c) 1996-2004 Christian Borgelt set item appearances ...[0 item(s)] done [0.00s]. set transactions ...[43 item(s), 978 transaction(s)] done [0.00s]. sorting and recoding items ... [43 item(s)] done [0.00s]. creating transaction tree ... done [0.00s]. checking subsets of size 1 2 done [0.00s]. writing ... [350 rule(s)] done [0.00s]. creating S4 object ... done [0.00s]. > print(rules) set of 350 rules >
ruleの確認
抽出されたruleの確認はinspect()で行なう。
> # rule確認 > rules %>% + sort(by="lift") %>% + head(n=10) %>% + inspect() lhs rhs support confidence lhs.support lift 1 {5} => {39} 0.03067485 0.2205882 0.1390593 1.508638 2 {39} => {5} 0.03067485 0.2097902 0.1462168 1.508638 3 {26} => {43} 0.02658487 0.1940299 0.1370143 1.416128 4 {43} => {26} 0.02658487 0.1940299 0.1370143 1.416128 5 {25} => {22} 0.02862986 0.2014388 0.1421268 1.387375 6 {22} => {25} 0.02862986 0.1971831 0.1451943 1.387375 7 {13} => {22} 0.02862986 0.2014388 0.1421268 1.387375 8 {22} => {13} 0.02862986 0.1971831 0.1451943 1.387375 9 {33} => {21} 0.02556237 0.1923077 0.1329243 1.382919 10 {21} => {33} 0.02556237 0.1838235 0.1390593 1.382919 >
978回のうち、5と39が選ばれたのは30回なのでsupport(5)は30 / 978 = 0.0306
> length(which(nums.mat$`5` & nums.mat$`39`)) [1] 30 >
978回のうち、5が選ばれた回数は136回なのでconfidence(5 → 39)は30 / 136 = 0.2205
> length(which(nums.mat$`5`)) [1] 136 >
978回のうち、39が選ばれた回数は143回なのでsupport(39)は143 / 978 = 0.1462
> length(which(nums.mat$`39`)) [1] 143 >
よってliftは confidence(5 → 39) / support(39) = 1.5086。
liftが1以上であれば有向なルールだけどSupportが0.03くらいだと滅多に発生しないので当てにはならなさそう。
- hot1に上記の数字が入ってると数字選びの参考になるかも