CL Machine-Learning

CL Machine-Learning is high performance and large scale statistical machine learning package written in Common Lisp. It runs almost all major platforms and supports several Common Lisp implementations -- Allegro, Lispworks and Sbcl.

Table of Contents

1 Loading/Using the library

(let ((*read-default-float-format* 'double-float))
  (load "defsystem.cl")
  (load-system :machine-learning :compile t))
or (in AllegroCL)
  CL-USER(2): (setf *read-default-float-format* 'double-float)
  CL-USER(3): :ld defsystem
  CL-USER(4): (excl:load-system :machine-learning :compile t)

2 Machine-Learning Packages

2.1 Read-Data

機械学習対象データを読み込むための package

  • Class
    • dataset (基本クラス)
      • accessor:
        • dimensions : 各列の情報
    • unspecialized-dataset (データ読み込み時のクラス)
      • accessor:
        • points : 列名以外の行のデータ
    • specialized-dataset (列の型が指定されたデータ)
    • numeric-dataset (列の型を numeric で指定したデータ)
      • accessor:
        • dataset-numeric-points : 数値型( :numeric )のデータ
      • parent: specialized-dataset
    • category-dataset (列の型を category で指定したデータ)
      • accessor:
        • dataset-category-points : カテゴリ型( :category )のデータ
      • parent: specialized-dataset
    • numeric-and-category-dataset (列の型として numeric, category が混在するデータ)
      • accessor:
        • dataset-numeric-points : 数値型( :numeric )のデータ
        • dataset-category-points : カテゴリ型( :category )のデータ
      • parent: (numeric-dataset category-dataset)
  • read-data-from-file (filename &key (type :sexp) external-format csv-type-spec (csv-header-p t) (missing-value-check t) missing-values-list)
    • return: <unspecialized-dataset>
    • arguments:
      • filename : <string>
      • type : :sexp | :csv
      • external-format : <acl-external-format>
      • csv-header-p : 第一行は column 名かどうか、default は t
      • csv-type-spec : <list symbol>, CSV ファイルを読み込みするときの型変更, e.g. '(string integer double-float double-float)
      • missing-value-check : boolean, 欠損値検出をするかしないか、 default は t
      • missing-value-list : <list>, 欠損値として判断する値、指定しない場合は '(nil "" "NA")
    • comment: external-format を指定しない場合、:sexp なら :default、:csv なら :932 (ACL expression for <CRLF + 932>)
  • pick-and-specialize-data ((d unspecialized-dataset) &key (range :all) except data-types)
    • return: <numeric-dataset>, <category-dataset> or <numeric-and-category-dataset> (data-type によって自動的に変更する)
    • arguments:
      • d : <unspecialized-dataset>
      • range : :all | <list integer>, 結果に入る列の指定、0から始まる。 e.g. '(0 1 3 4)
      • except : <list integer>, :range の逆、結果に入らない列の指定、0からはじまる。 e.g. '(2)
      • data-types : 数値型かカテゴリ型か、その型のリスト e.g. '(:category :numeric :numeric)

      Note: range で指定した列の順番は読み込みに反映される。

  • divide-dataset ((specialized-d specialized-dataset) &key divide-ratio random (range :all) except)
    • return: (values of <numeric-dataset>, <category-dataset> or <numeric-and-category-dataset>)
    • arguments:
      • d : <specialized-dataset>
      • divide-ratio : <list non-negative-integer>, 行分割の比率、nil なら行分割はしない。 e.g. '(1 2 3) なら行を 1:2:3 の比率に分ける。
      • random : boolean, t なら行分割はランダムになる
      • range : :all | <list integer>, 結果に入る列の指定、0から始まる。 e.g. '(0 1 3 4)
      • except : <list integer>, :range の逆、結果に入らない列の指定、0からはじまる。 e.g. '(2)
    • 分割後の行の順番は元のデータに安定。
  • make-unspecialized-dataset (all-column-names data)
    • return: <unspecialized-dataset>
    • arguments:
      • all-column-names : <list string>
      • data : <vector vector>
  • dataset-cleaning (d &key interp-types outlier-types outlier-values)
    • return: <numeric-dataset> | <category-dataset> | <numeric-and-category-dataset>
    • arguments:
      • d : <numeric-dataset> | <category-dataset> | <numeric-and-category-dataset>
      • interp-types : <list, nil | :zero | :min | :max | :mean | :median | :mode | :spline>
      • outlier-types : <list, nil | :std-dev | :mean-dev | :user | :smirnov-grubbs | :freq>
      • outlier-values : <list, nil | outlier-type に見合った値>
    • comments: 外れ値検出と欠損値補間を行なう。まず外れ値検出を行い、そこで判定された外れ値も欠損値と見做して補間を行なう。
      • numeric
        • 補間 : ゼロ(:zero), 最小値(:min), 最大値(:max), 平均値(:mean), 中央値(:median), 3次元スプライン(:spline)
        • 外れ値検出 : 標準偏差(:std-dev), 平均偏差(:mean-dev), ユーザ指定(:user), スミルノフ・グラッブス検定(:smirnov-grubbs)
      • category
        • 補間 : 最頻値(:mode)
        • 外れ値検出 : ユーザ指定(:user), 頻度(:freq)
  • sample usage
     READ-DATA(54): (setf dataset (read-data-from-file "sample/original-airquality.sexp"))
     #<UNSPECIALIZED-DATASET>
     DIMENSIONS: ID | OZONE | SOLAR.R | WIND | TEMP | MONTH | DAY
     TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
     DATA POINTS: 153 POINTS
    
     READ-DATA(55): (setf dataset (pick-and-specialize-data
                                  dataset :range :all
                                  :data-types '(:category :numeric :numeric :numeric :numeric
                                                :category :category)))
     #<NUMERIC-AND-CATEGORY-DATASET>
     DIMENSIONS: ID | OZONE | SOLAR.R | WIND | TEMP | MONTH | DAY
     TYPES:      CATEGORY | NUMERIC | NUMERIC | NUMERIC | NUMERIC | CATEGORY | CATEGORY
     CATEGORY DATA POINTS: 153 POINTS
     NUMERIC DATA POINTS: 153 POINTS
    
     READ-DATA(56): (dataset-numeric-points dataset)
     #(#(41.0 190.0 7.4 67.0) #(36.0 118.0 8.0 72.0) #(12.0 149.0 #.EXCL:*NAN-DOUBLE* 74.0)
      #(18.0 313.0 11.5 62.0) #(#.EXCL:*NAN-DOUBLE* #.EXCL:*NAN-DOUBLE* 14.3 56.0)
      #(28.0 #.EXCL:*NAN-DOUBLE* 14.9 66.0) #(23.0 299.0 8.6 65.0)
      #(19.0 99.0 13.8 #.EXCL:*NAN-DOUBLE*) #(8.0 19.0 #.EXCL:*NAN-DOUBLE* #.EXCL:*NAN-DOUBLE*)
      #(#.EXCL:*NAN-DOUBLE* 194.0 8.6 69.0) ...)
    
     READ-DATA(57): (dataset-category-points dataset)
     #(#(1 5 1) #(2 5 2) #(3 5 3) #(4 0 0) #(5 5 5) #(6 5 6) #(7 5 7) #(8 5 8) #(9 5 9) #(10 5 10) ...)
    
     READ-DATA(43): (setf dataset 
                      (dataset-cleaning dataset 
                                        :interp-types '(nil :spline :min :max :median :mode :mode)
                                        :outlier-types '(nil :std-dev :mean-dev :smirnov-grubbs nil
                                                         :user :freq)
                                        :outlier-values '(nil 2d0 2d0 0.05d0 nil 5 nil)))
     #<NUMERIC-AND-CATEGORY-DATASET>
     DIMENSIONS: ID | OZONE | SOLAR.R | WIND | TEMP | MONTH | DAY
     TYPES:      CATEGORY | NUMERIC | NUMERIC | NUMERIC | NUMERIC | CATEGORY | CATEGORY
     CATEGORY DATA POINTS: 153 POINTS
     NUMERIC DATA POINTS: 153 POINTS
    
     READ-DATA(63): (dataset-numeric-points dataset)
     #(#(41.0 190.0 7.4 67.0) #(36.0 118.0 8.0 72.0) #(12.0 149.0 20.7 74.0) #(18.0 313.0 11.5 62.0)
      #(27.093168555852095 36.0 14.3 56.0) #(28.0 36.0 14.9 66.0) #(23.0 299.0 8.6 65.0)
      #(19.0 99.0 13.8 79.0) #(8.0 36.0 20.7 79.0) #(2.4104000463381468 194.0 8.6 69.0) ...)
    
     READ-DATA(64): (dataset-category-points dataset)
     #(#(1 8 1) #(2 8 2) #(3 8 3) #(4 8 30) #(5 8 5) #(6 8 6) #(7 8 7) #(8 8 8) #(9 8 9) #(10 8 10) ...)
    
     READ-DATA(57): (divide-dataset dataset :divide-ratio '(3 2) :except '(2 3 4))
     #<NUMERIC-AND-CATEGORY-DATASET>
     DIMENSIONS: ID | OZONE | MONTH | DAY
     TYPES:      CATEGORY | NUMERIC | CATEGORY | CATEGORY
     CATEGORY DATA POINTS: 91 POINTS
     NUMERIC DATA POINTS: 91 POINTS
     #<NUMERIC-AND-CATEGORY-DATASET>
     DIMENSIONS: ID | OZONE | MONTH | DAY
     TYPES:      CATEGORY | NUMERIC | CATEGORY | CATEGORY
     CATEGORY DATA POINTS: 62 POINTS
     NUMERIC DATA POINTS: 62 POINTS
    
    

2.2 Principal-Component-Analysis

主成分分析のための package

  • Class
    • pca-result (PCA結果)
      • accessor:
        • components 主成分、スコア (vector of datapoints)
        • contributions 重要度 (double-float simple-array)
        • loading-factors 負荷量 (matrix), 行と列の順に注意
        • pca-method :covariance | :correlation
    • pca-model (score 判定用)
      • accessor:
        • loading-factors 負荷量 (matrix), 行と列の順に注意
        • pca-method :covariance | :correlation
  • princomp (dataset &key (method :correlation))
    • return: (values pca-result pca-model)
    • arugments:
      • dataset : <numeric-dataset>
      • method : :covariance | :correlation
  • princomp-projection (dataset pca-model)
    • return: score (vector of datapoints)
    • arguments:
      • dataset : <numeric-dataset>
      • pca-model : <pca-model>, PCAで得られたモデル
  • sub-princomp (dataset &key (method :correlation) (dimension-thld 0.8d0))
    • return: (values pca-result pca-model)
    • arugments:
      • dataset : <numeric-dataset>
      • method : :covariance | :correlation
      • dimension-thld : 0 < <number> < 1 | 1 <= <integer>, threshold for deciding principal components
    • note: dimension-thld に 0 < <number> < 1 を指定した場合、累積寄与率に対する閾値を意味する。 寄与率とは各主成分の重要度(contributions)を全体の重要度の合計で割った値。 1 <= <integer> を指定した場合は主成分数をあらかじめ指定することを意味する。
  • make-face-estimator ((face-dataset numeric-and-category-dataset)
    &key id-column dimension-thld method pca-method d-fcn pca-result pca-model)
    • return: (values estimator hash)
    • arguments:
      • face-dataset : <numeric-and-category-dataset>
      • id-column : <string>, 顔ID列の名前 default は "personID"
      • dimension-thld : 0 < <number> < 1 | 1 <= <integer>, 次元数決定のための閾値
      • method : :eigenface | :subspace, 顔認識方法、固有顔法か部分空間法。
      • pca-method : :covariance | :correlation, 部分空間法の際の空間構成方法
      • d-fcn : 固有顔比較のための距離関数 default は euclid-distance
      • pca-result : <pca-result>, 固有顔法に必要
      • pca-model : <pca-model>, 固有顔法に必要
    • note: dimension-thld に 0 < <number> < 1 を指定した場合、累積寄与率に対する閾値を意味し、 1 <= <integer> を指定した場合は次元数をあらかじめ指定することを意味する。
    • reference:
  • face-estimate ((d numeric-dataset) estimator)
    • return: <numeric-and-category-dataset>
    • arguments:
      • d : <numeric-dataset>
      • estimator : <closure>, make-face-estimator の第一返り値
  • Note
    • princomp または sub-princomp において :correlation method では値が全て同じ列が存在すると結果が発散してしまうので、 pick-and-specialize-data または divide-dataset でその列を分析対象データから取り除く必要がある。
  • sample usage
    PCA(10): (setf dataset (read-data-from-file "sample/pos.sexp" :external-format #+allegro :932 #-allegro :sjis))
    PCA(11): (setf dataset (pick-and-specialize-data dataset :range '(2 3) :data-types '(:numeric :numeric)))
    PCA(12): (princomp dataset :method :correlation)
     #<PCA-RESULT @ #x20fcd88a>
     #<PCA-MODEL @ #x20fcd8c2>
    PCA(13): (princomp-projection dataset (cadr /))
     #(#(-0.18646787691278618 -0.5587877417431286)
      #(-0.2586922124306382 -0.6310120772609806)
      #(0.08929776779173992 -0.2830220970386028)
      #(-0.311219001898167 -0.6835388667285094)
      #(-0.19303372559622725 -0.5653535904265697)
      #(-0.19303372559622725 -0.5653535904265697)
      #(-0.19303372559622725 -0.5653535904265697)
      #(-1.9046466459275095 1.014942356235892)
      #(0.20748304409367965 -0.1648368207366632)
      #(0.161522103309592 -0.21079776152075083) ...)
    
    ;; learning and estimation by eigenface method and data for eyes
    PCA(40): (let ((eyes (pick-and-specialize-data
                          (read-data-from-file "sample/eyes200.sexp")
                          :except '(0)
                          :data-types (append (make-list 1 :initial-element :category)
                                              (make-list 1680 :initial-element :numeric)))))
               (multiple-value-setq (for-learn for-estimate)
                 (divide-dataset eyes :divide-ratio '(1 1) :random t)))
    
    PCA(43): (multiple-value-setq (pca-result pca-model)
                 (princomp (divide-dataset for-learn :except '(0)) :method :covariance))
    ; it takes
    ; cpu time (non-gc) 387,350 msec (00:06:27.350) user, 1,230 msec system
    ; cpu time (gc)     300 msec user, 10 msec system
    ; cpu time (total)  387,650 msec (00:06:27.650) user, 1,240 msec system
    ; real time  389,905 msec (00:06:29.905)
    ; space allocation:
    ;  34,748 cons cells, 98,980,632 other bytes, 32 static bytes
    ; environment: AllegroCL 32bit, CPU 2.4GHz
    
    PCA(65): (loop for dimension in '(1 5 10 20 30)
                 as estimator = (make-face-estimator for-learn :dimension-thld dimension :method :eigenface
                                                     :pca-result pca-result :pca-model pca-model)
                 as result = (face-estimate for-estimate estimator)
                 do (format t "hitting-ratio: ~,3F~%"
                            (/ (count-if (lambda (p) (string-equal (aref p 0) (aref p 1)))
                                         (dataset-category-points result))
                               (length (dataset-points result)))))
    Dimension : 1
    Number of self-misjudgement : 53
    hitting-ratio: 0.580
    Dimension : 5
    Number of self-misjudgement : 21
    hitting-ratio: 0.860
    Dimension : 10
    Number of self-misjudgement : 18
    hitting-ratio: 0.880
    Dimension : 20
    Number of self-misjudgement : 15
    hitting-ratio: 0.890
    Dimension : 30
    Number of self-misjudgement : 13
    hitting-ratio: 0.890
    
    

2.3 K-means

k-means クラスタリングの package

  • k-means ((k integer) (dataset numeric-dataset) &key (distance-fn distance-function) standardization (max-iteration max-iteration) (num-of-trials num-of-trials) (random-state random-state) debug)
    • return: (best-result table)
      • best-result : points, clusters, distance infomation, etc.
      • table : lookup table for normalized vecs and original vecs, might be removed later.
    • arguments:
      • k : <integer>, clusterの数
      • dataset : <numeric-dataset> | <category-dataset> | <numeric-or-category-dataset>
      • distance-fn : #'euclid-distance | #'manhattan-distance | #'cosine-distance
      • standardization : t | nil, 標準化するか
      • max-iteration : 繰り返し最大数
      • num-of-trials : 試す回数
      • random-state : (テスト用)
      • debug : (テスト用)
  • sample usage
    K-MEANS(22): (setf dataset (read-data-from-file "sample/pos.sexp" :external-format #+allegro :932 #-allegro :sjis))
    K-MEANS(23): (setf dataset (pick-and-specialize-data dataset :range '(2 3) :data-types '(:numeric :numeric)))
    K-MEANS(24): (k-means 20 dataset :distance-fn #'manhattan-distance)
     #S(PROBLEM-WORKSPACE :POINTS #(#S(POINT
                                      :ID
                                      0
                                      :POS
                                      #(1.0 129.0)
                                      :OWNER
                                      #S(CLUSTER
                                         :ID
                                         16
                                         :CENTER
                                         #(1.2455357142857142
                                           129.12321428571428)
                                         :OLD-CENTER
                                         #(1.2455357142857142
                                           129.12321428571428)
                                         :SIZE
                                         1120))
                                   ...)
                         :CLUSTERS #(#S(CLUSTER
                                        :ID
                                        0
                                        :CENTER
                                        #(1.0831024930747923 110.0)
                                        :OLD-CENTER
                                        #(1.0831024930747923 110.0)
                                        :SIZE
                                        361)
                                     ...)
                         :DISTANCE-BETWEEN-CLUSTERS #2A((1.7976931348623157e+308
                                                         124.38037357745417
                                                         174.4273053916255
                                                         151.26611354279854
                                                         13.21191276633519
                                                         111.08310249307479
                                                         238.6819189661527
                                                         294.1850209583026
                                                         2920.083102493075
                                                         35.26307380581604
                                                         ...)
                                                        ...)
                         :DISTANCE-BETWEEN-POINT-AND-OWNER #(0.36874999999999747
                                                             0.17974882260597758
                                                             11.982608695652175
                                                             0.08310249307479234
                                                             0.347715736040624
                                                             0.347715736040624
                                                             0.347715736040624
                                                             1.9458398744113148
                                                             6.437807183364839
                                                             0.9826086956521745
                                                             ...)
                         :LOWER-BOUNDS ...)
     NIL
    

2.4 Cluster-Validation

クラスタリング結果を評価する指標の package

  • Parameter
     *workspace* | 評価対象 k-means クラスタリング結果
    
  • calinski (&optional (workspace workspace))
    • return: <number> 指標値
  • hartigan (&optional (workspace workspace))
    • return: <number> 指標値
  • ball-and-hall (&optional (workspace workspace))
    • return: <number> 指標値
  • dunn-index (&key (workspace workspace)
    (distance :manhattan) (intercluster :centroid) (intracluster :centroid))
    • return: <number> 指標値
    • arguments:
      • distance: :manhattan | :euclid | :cosine
      • intercluster: :single | :complete | :average | :centroid | :average-to-centroids | :hausdorff
      • intracluster: :complete | :average | :centroid
  • davies-bouldin-index (&key (workspace workspace)
    (distance :manhattan) (intercluster :centroid) (intracluster :centroid))
    • return: <number> 指標値
    • arguments:
      • distance: :manhattan | :euclid | :cosine
      • intercluster: :single | :complete | :average | :centroid | :average-to-centroids | :hausdorff
      • intracluster: :complete | :average | :centroid
  • global-silhouette-value (&key (workspace workspace)
    (distance :manhattan))
    • return: <number> 指標値
    • arguments:
      • distance: :manhattan | :euclid | :cosine
  • sample usage
     CLUSTER-VALIDATION(72): (setf *workspace*
                              (k-means:k-means
                               5
                               (read-data:pick-and-specialize-data
                                (read-data:read-data-from-file
                                 "sample/syobu.csv" :type :csv
                                 :csv-type-spec '(string integer integer integer integer)
                                 :external-format #+allegro :932 #-allegro :sjis)
                                :except '(0) :data-types (make-list 4
                                                                    :initial-element :numeric))))
     CLUSTER-VALIDATION(73): (calinski)
     441.8562453167574
     CLUSTER-VALIDATION(74): (hartigan)
     2.5074656538807023
     CLUSTER-VALIDATION(75): (ball-and-hall)
     1127.7702976190476
     CLUSTER-VALIDATION(76): (dunn-index :distance :euclid
                                         :intercluster :hausdorff
                                         :intracluster :centroid)
     1.2576613811360222
     CLUSTER-VALIDATION(77): (davies-bouldin-index :distance :euclid
                                                   :intercluster :average
                                                   :intracluster :complete)
     1.899415427296523
     CLUSTER-VALIDATION(78): (global-silhouette-value :distance :euclid)
     0.5786560352400679
    
  • reference

2.5 Linear-Regression

線形回帰分析の package

  • mlr (numeric-dataset range)
    • return: <SIMPLE-ARRAY DOUBLE-FLOAT (*)>, intercept and coefficients of multiple regression formula,重回帰式の切片と係数からなるベクトル
    • arguments:
      • numeric-dataset : <NUMERIC-DATASET>
      • range : <list>, indexes of explanatory variables, index of objective variable,数値データの列番号を説明変数、目的変数の順に並べたリスト
  • sample usage
     LINEAR-REGRESSION(128):(setf dataset (read-data-from-file "sample/airquality.csv"
                                   :type :csv
                                   :csv-type-spec 
                                   '(integer double-float double-float double-float double-float integer integer)))
     #<UNSPECIALIZED-DATASET>
     DIMENSIONS: id | Ozone | Solar | Wind | Temp | Month | Day
     TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
     DATA POINTS: 111 POINTS
     LINEAR-REGRESSION(129):(setf airquality (pick-and-specialize-data dataset :range '(0 1 2 3 4) 
                                        :data-types '(:numeric :numeric :numeric :numeric :numeric)))
     #<NUMERIC-DATASET>
     DIMENSIONS: id | Ozone | Solar | Wind | Temp
     TYPES:      NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC
     NUMERIC DATA POINTS: 111 POINTS
     LINEAR-REGRESSION(130):(mlr airquality '(2 3 4 1))
     #(-64.34207892859138 0.05982058996849854 -3.333591305512754 1.6520929109927098)
    

2.6 Hierarchical-Clustering

階層型クラスタリングの package

  • cophenetic-matrix (distance-matrix &optional (method #'average))
    • return: (SIMPLE-ARRAY DOUBLE-FLOAT (* * )), (SIMPLE-ARRAY T (* *)), コーフェン行列ならびにマージ行列
    • arguments:
      • distance-matrix : (SIMPLE-ARRAY DOUBLE-FLOAT (* *)), データから作成した距離行列
      • method : single | complete | average | centroid | median | ward, default is average, クラスタ間距離の方法を指定、デフォルトは群平均法
  • cutree (k merge-matrix)
    • return: (SIMPLE-ARRAY T), 各データが帰属すべきクラスタ番号からなるベクトル
    • arguments:
      • k : cluster number, デンドログラムをk個に分割
      • merge-matrix : マージ行列
  • sample usage
    HC(35): (setf data (read-data-from-file "sample/seiseki.csv"
                                            :type :csv :csv-type-spec
                                            '(string double-float double-float double-float double-float double-float)))
     #<UNSPECIALIZED-DATASET>
    DIMENSIONS: name | math | science | japanese | english | history
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 7 POINTS
    HC(36): (setf seiseki (pick-and-specialize-data data :range '(1 2 3 4 5)
                                                    :data-types '(:numeric :numeric :numeric :numeric :numeric)))
     #<NUMERIC-DATASET>
    DIMENSIONS: math | science | japanese | english | history
    TYPES:      NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC
    NUMERIC DATA POINTS: 7 POINTS
    HC(37): (setf distance-matrix (distance-matrix (numeric-matrix seiseki)))
     #2A((0.0 68.65857557508748 33.77869150810907 60.13318551349163 28.478061731796284 63.37191807101944 67.88225099390856)
        (68.65857557508748 0.0 81.11103500757464 64.1404708432983 60.753600716336145 12.409673645990857 38.1051177665153)
        (33.77869150810907 81.11103500757464 0.0 52.67826876426369 21.307275752662516 75.66372975210778 87.53856293085921)
        (60.13318551349163 64.1404708432983 52.67826876426369 0.0 47.10626285325551 54.31390245600108 91.53141537199127)
        (28.478061731796284 60.753600716336145 21.307275752662516 47.10626285325551 0.0 56.382621436041795 67.72739475278819)
        (63.37191807101944 12.409673645990857 75.66372975210778 54.31390245600108 56.382621436041795 0.0 45.58508528016593)
        (67.88225099390856 38.1051177665153 87.53856293085921 91.53141537199127 67.72739475278819 45.58508528016593 0.0))
    HC(38): (multiple-value-setq (u v) (cophenetic-matrix distance-matrix #'ward))
     #2A((0.0 150.95171411164776 34.40207690904939 66.03152040007744 34.40207690904939 150.95171411164776 150.95171411164776)
        (150.95171411164776 0.0 150.95171411164776 150.95171411164776 150.95171411164776 12.409673645990857 51.65691081579053)
        (34.40207690904939 150.95171411164776 0.0 66.03152040007744 21.307275752662516 150.95171411164776 150.95171411164776)
        (66.03152040007744 150.95171411164776 66.03152040007744 0.0 66.03152040007744 150.95171411164776 150.95171411164776)
        (34.40207690904939 150.95171411164776 21.307275752662516 66.03152040007744 0.0 150.95171411164776 150.95171411164776)
        (150.95171411164776 12.409673645990857 150.95171411164776 150.95171411164776 150.95171411164776 0.0 51.65691081579053)
        (150.95171411164776 51.65691081579053 150.95171411164776 150.95171411164776 150.95171411164776 51.65691081579053 0.0))
    HC(39): (cutree 3 v)
     #(1 2 1 3 1 2 2)
    

2.7 Non-negative-Matrix-Factorization

非負行列因子分解の package

  • nmf (non-negative-matrix k &key (cost-fn 'euclidean) (iteration 100))
    • return: (SIMPLE-ARRAY DOUBLE-FLOAT (* *)), 分解で得られた2つの因子行列
    • arguments:
      • non-negative-matrix : (SIMPLE-ARRAY DOUBLE-FLOAT (* *)), 非負行列
      • k : size of dimension reduction, 次元縮約のサイズ
      • cost-fn : euclidean | kl , default is Euclidean-norm, 目的関数、デフォルトはユークリッドノルム
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
      • comments : 目的関数としてカルバック・ライブラー情報量を取ることも可能
  • sample usage
    NMF(113): (setf matrix (sample-matrix 4 4))
     #2A((5.0 33.0 13.0 29.0) (55.0 84.0 74.0 96.0) (11.0 69.0 92.0 48.0) (15.0 86.0 36.0 89.0))
    NMF(114): (multiple-value-setq (weight feature) (nmf matrix 3 :iteration 80))
     #2A((0.1706700616740593 2.8780911735531785 0.9590208453512624)
        (2.04316650967508 0.9205577182615349 2.177706505047263)
        (0.45460124650102984 0.8208500118171567 9.364639376361005)
        (0.6081182025287406 7.873531632669753 2.0094667372957074))
    NMF(115): feature
     #2A((26.64452775384442 32.373333937257556 27.1225512002247 41.13741018340651)
        (8.205335826063113e-6 7.186521221246216 0.2535892468154233 7.415674453785212)
        (7.798828607758656e-5 5.166396186586663 8.485528725251449 2.44838404009116))
    NMF(116): (m*m weight feature)
     #2A((4.54752160312147 31.163303833367888 13.496659390410713 30.71196285636883)
        (54.43938416184624 84.010613867982 74.12832291141632 96.20899698701007)
        (12.113372596853665 68.99745115344638 92.00202074988742 47.716508000514054)
        (16.203243644732968 86.65181709675957 35.541747762140545 88.3239016155684))
    NMF(117): (multiple-value-setq (weight feature) (nmf matrix 3 :cost-fn 'kl))
     #2A((0.043068086218311506 0.05615058329446132 0.16029572873360276)
        (0.21249176355212562 0.6796882407264663 0.1811889159952452)
        (0.6443337004127561 0.08444888547870807 0.2125582079281919)
        (0.10010644981680689 0.1797122905003643 0.4459571473429601))
    NMF(118): feature
     #2A((6.478155493510353 45.81284687065614 125.70077558823121 10.819729810945052)
        (78.61488727127733 66.63762341406404 62.441606842405456 96.81364930861258)
        (0.9069572352123124 159.54952971527982 26.85761756936332 154.36662088044235))
    NMF(119): (m*m weight feature)
     #2A((4.838654906189247 31.289921197802457 13.224985867116567 30.646437922074924)
        (54.974499708007016 83.93626798604987 74.01750800106926 96.0717231487415)
        (11.00581471766063 69.05979629094608 91.97517704462386 47.959213628068696)
        (15.18103066814309 87.71401452520158 35.782329087190305 87.32262530111485)) 
    
  • nmf-sc (non-negative-matrix k sparseness &key type (iteration 100))
    • スパースネス制約付きの非負行列因子分解
    • return (SIMPLE-ARRAY DOUBLE-FLOAT (* * )), 分解で得られた2つの因子行列
    • arguments:
      • non-negative-matrix : (SIMPLE-ARRAY DOUBLE-FLOAT (* * )), 非負行列
      • k : size of dimension reduction, 次元縮約のサイズ  
      • sparseness : 左または右の行列の、列または行のスパースネスを設定
      • type : left | right , スパースネス制約を、右または左どちらの因子行列に付加するか設定
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
      • comments : 目的関数はユークリッドノルムを用い、左因子行列については各列ベクトルに、右因子行列については各行ベクトルに、指定したスパースネス制約を付加してNMFを行う

    実装にあたっては、論文"Non-negative Matrix Factorization with Sparseness Constraints", http://www.cs.helsinki.fi/u/phoyer/papers/pdf/NMFscweb.pdf を参考にした。

  • sample usage
    NMF(34): (setf x (sample-matrix 100 100))
    #2A((70.0 65.0 68.0 42.0 35.0 20.0 51.0 7.0 25.0 9.0 ...)
        (44.0 83.0 39.0 37.0 32.0 74.0 32.0 23.0 27.0 42.0 ...)
        (57.0 97.0 96.0 23.0 56.0 67.0 27.0 19.0 90.0 89.0 ...)
        (55.0 6.0 32.0 78.0 59.0 58.0 34.0 63.0 66.0 7.0 ...)
        (66.0 92.0 63.0 65.0 63.0 75.0 36.0 7.0 79.0 77.0 ...)
        (75.0 86.0 95.0 73.0 66.0 86.0 61.0 34.0 7.0 43.0 ...)
        (11.0 39.0 87.0 31.0 4.0 52.0 64.0 57.0 8.0 23.0 ...)
        (84.0 52.0 49.0 68.0 75.0 14.0 21.0 73.0 57.0 77.0 ...)
        (93.0 85.0 28.0 22.0 98.0 2.0 61.0 48.0 45.0 7.0 ...)
        (81.0 51.0 5.0 36.0 87.0 12.0 84.0 53.0 35.0 78.0 ...)
        ...)
    NMF(35): (multiple-value-setq (w h) (nmf-sc x 3 0.7 :type 'left))
     #2A((1.4779288903810084e-12 3698.436810921221 508.76839564873075)
        (0.06468571444133886 0.0 4.206412995699793e-12)
        (15616.472155017571 5522.3359228859135 13359.214293446286)
        (0.5537530076878738 0.0030283688683994114 0.46633231671876274)
        (7472.121463556481 0.0 8687.743649034346)
        (866.1770680973686 6831.896141533997 4459.0733598676115)
        (1.5181766737885027 0.4388556634212364 0.727139819117383)
        (0.7198025410086757 0.0047792056984690134 4.206412995699793e-12)
        (1.4779288903810084e-12 0.0 4.206412995699793e-12)
        (0.25528585009283233 0.0 4.206412995699793e-12)
        ...)
    NMF(36): h
     #2A((0.00287491870133676 0.0026133720724571797 2.950874161225484e-5 0.005125487883511961 6.757515335801653e-4
         0.0012968322406142806 0.0038001301816957284 0.002985585252159595 0.0081124151768938 0.0042303781451423035 ...)
        (0.004994350656772211 0.0025747747712995227 0.007134096369763904 0.0065746407124065084 0.0038636664279363847
         0.004880229457827016 0.00512112561086382 0.0038194228552171946 0.0050556422535574476 0.003237070939818787 ...)
        (0.0052939720030634446 0.007382671590128047 0.007556184152626243 3.931389819873203e-6 0.004546870255049726
         0.006931587163470776 2.239987792302906e-4 0.001349836871839297 1.94285681454748e-4 0.004391868346075027 ...))
    NMF(37): (sparseness (pick-up-column w 0))
    0.7
    NMF(38): (multiple-value-setq (w h) (nmf-sc x 3 0.9 :type 'right))
     #2A((8.289561664219266e-6 1.4361785459627462e-4 3.2783650074466155e-9)
        (8.963543606154278e-5 2.46840968396353e-5 2.181734037947416e-6)
        (2.9872365277908504e-5 1.412292680612174e-4 4.198406652155696e-5)
        (6.890230812495509e-13 7.954471346549545e-5 2.7910446164534665e-5)
        (1.2477626056283604e-4 4.292564917625326e-9 2.5310616226879616e-5)
        (3.619705865699883e-7 1.464351885312363e-4 7.522900946233666e-5)
        (4.19655080884389e-7 1.6289294924375495e-4 3.153712985065881e-5)
        (1.703028808790872e-8 5.8687333880722456e-5 1.2797257648598223e-4)
        (1.4373147157245112e-5 6.128539811119244e-7 9.512691095539368e-5)
        (2.029113599202957e-18 8.421240673252468e-17 1.0537112796313751e-4)
        ...)
    NMF(39): h
     #2A((0.0 0.0 559651.4985471596 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 0.006235745138837956 588285.0338912416 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0030094219837337732 0.0 336606.15256656246 0.0 0.0 0.0 0.0 0.0 6.607186514884233e-5 0.0 ...))
    NMF(40): (sparseness (pick-up-row h 0))
    0.8999999999999999
    
  • nmf-clustering (non-negative-matrix k &key (type 'row) (cost-fn 'euclidean) (iteration 100))
    • NMFを利用したクラスタリング。行ないし列に割り当てられたデータを、最大成分の特徴グループに帰属させる
    • return (SIMPLE-ARRAY T (*)), 各データが帰属すべきクラスタ番号からなるベクトル
    • arguments :
      • non-negative-matrix : (SIMPLE-ARRAY DOUBLE-FLOAT (* *)), 非負行列
      • k : size of dimension reduction, 次元縮約のサイズ(=クラスタ個数)
      • type : row | column, default is row, デフォルトでは行データに関してクラスタリングを行う
      • cost-fn : euclidean | kl, default is Euclidean-norm, 目的関数、デフォルトはユークリッドノルム
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
    • comments : k-meansと違い、クラスタサイズは一定とは限らない
  • sample usage
    NMF(136): (setf x (sample-matrix 7 10))
     #2A((90.0 89.0 21.0 40.0 30.0 21.0 44.0 24.0 1.0 51.0)
        (1.0 64.0 5.0 90.0 66.0 69.0 89.0 29.0 95.0 80.0)
        (52.0 11.0 87.0 30.0 26.0 56.0 27.0 74.0 16.0 3.0)
        (90.0 10.0 92.0 16.0 54.0 75.0 48.0 22.0 73.0 71.0)
        (66.0 20.0 88.0 89.0 6.0 10.0 62.0 99.0 79.0 45.0)
        (3.0 71.0 31.0 74.0 99.0 76.0 93.0 19.0 31.0 61.0)
        (52.0 40.0 11.0 47.0 90.0 11.0 80.0 88.0 45.0 30.0))
    NMF(137): (nmf-clustering x 5)
     #(4 1 3 3 2 1 4)
    NMF(138): (nmf-clustering x 5 :type 'column)
     #(2 0 2 0 0 0 0 1 0 0)
    
  • rho-k (non-negative-matrix k &key (type 'row) (cost-fn 'euclidean) (iteration 100) (repeat 100))
    • NMFクラスタリング結果の安定度を測る指標。1.0に近いほど安定しているとみなせる
    • return DOUBLE-FLOAT
    • arguments:
      • non-negative-matrix : (SIMPLE-ARRAY DOUBLE-FLOAT (* *)), 非負行列
      • k : size of dimension reduction, 次元縮約のサイズ(=クラスタ個数)
      • type : row | column, default is row, デフォルトでは行データに関してクラスタリング安定度を求める
      • cost-fn : euclidean | kl, default is Euclidean-norm, 目的関数、デフォルトはユークリッドノルム
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
      • repeat : default is 100, NMFクラスタリングを行う回数、デフォルトでは100回
    • comments: NMFクラスタリングを反復して行い平均を取り、最後に群平均法による階層型クラスタリングを経由するので計算には時間がかかる

    実装にあたっては、論文"Metagenes and molecular pattern discovery using matrix factorization", http://www.pnas.org/content/101/12/4164 を参考にした

  • sample usage
    NMF(203): (setf matrix (set-data "sample/sports-corpus-data"))
     #2A((0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 0.0 0.0 0.0 0.0 0.0 3.0 0.0 0.0 0.0 ...)
        (0.0 7.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 2.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        (0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
        ...)
    NMF(204): (rho-k matrix 2)
    0.9875001365947708
    NMF(205): (rho-k matrix 2 :cost-fn 'kl)
    0.9742824880455003
    
  • nmf-analysis (non-negative-matrix k &key (cost-fn 'euclidean) (iteration 100) (type 'row) (results 10))
    • NMFによる特徴抽出結果を表示する
    • return nil
    • arguments:
      • non-negative-matrix : (SIMPLE-ARRAY DOUBLE-FLOAT (* *)), 非負行列
      • k : size of dimension reduction, 次元縮約のサイズ(=抽出される特徴の数)
      • cost-fn : euclidean | kl, default is Euclidean-norm, 目的関数、デフォルトはユークリッドノルム
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
      • type : row | column, default is row, デフォルトでは行データに関して特徴抽出を行う
      • results : 特徴成分の大きいデータをこのパラメタの数だけ表示、デフォルトは上位10件を表示
  • sample usage
    NMF(25): (setf x (sample-matrix 100 200))
     #2A((92.0 5.0 77.0 47.0 91.0 25.0 93.0 63.0 48.0 30.0 ...)
        (10.0 2.0 48.0 73.0 90.0 35.0 4.0 19.0 78.0 29.0 ...)
        (38.0 7.0 44.0 61.0 98.0 92.0 11.0 31.0 97.0 80.0 ...)
        (12.0 45.0 53.0 69.0 92.0 95.0 50.0 57.0 57.0 52.0 ...)
        (89.0 33.0 45.0 54.0 43.0 62.0 4.0 92.0 19.0 93.0 ...)
        (38.0 84.0 75.0 71.0 16.0 74.0 34.0 41.0 59.0 83.0 ...)
        (7.0 59.0 45.0 95.0 47.0 55.0 21.0 82.0 55.0 74.0 ...)
        (57.0 41.0 43.0 65.0 56.0 51.0 26.0 26.0 84.0 21.0 ...)
        (44.0 68.0 22.0 83.0 75.0 63.0 98.0 74.0 18.0 79.0 ...)
        (78.0 21.0 71.0 8.0 53.0 88.0 35.0 23.0 20.0 18.0 ...)
        ...)
    NMF(26): (nmf-analysis x 3 :type 'column :results 5)
    
    Feature 0
    81   46.75849601655378
    103   45.955361786327046
    140   43.68666852948713
    64   43.51457629469007
    152   42.932921747549514
    
    Feature 1
    186   11.79404092624892
    138   11.19240951742515
    42   10.716884646306237
    150   9.93408007033108
    98   9.827683668745964
    
    Feature 2
    145   8.53136727031378
    128   7.427871404203731
    131   7.399743366645699
    162   7.207875670792123
    98   7.097879611292094
    NIL
    
  • nmf-corpus-analysis (corpus-data-file-name k &key (cost-fn 'euclidean) (iteration 100) (results 10))
    • NMFによるコーパスの特徴抽出結果を表示する
    • return nil
    • arguments:
      • corpus-data-file-name : コーパスから作成した索引語の出現頻度データのファイル名
      • k : size of dimension reduction, 次元縮約のサイズ(=抽出される特徴の数)
      • cost-fn : euclidean | kl, default is Euclidean-norm, 目的関数、デフォルトはユークリッドノルム
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
      • results : 特徴成分の大きい索引語及び文書をこのパラメタの数だけ表示、デフォルトは上位10件を表示
    • comments : 索引語の出現頻度データの形式は、1行目は索引語名、1列目を文書名としている
  • sample usage
    NMF(28): (nmf-corpus-analysis "sample/sports-corpus-data" 4 :results 5)
    
    Feature 0
    マラソン    0.07221234705139196
    大阪    0.048907356128417456
    世界    0.046937004997150256
    練習    0.03656428697461747
    日本    0.03196115942493634
    
    Feature 1
    キャンプ    0.06669809921902364
    監督    0.06319183784218135
    宮崎    0.0603534199166669
    投手    0.0467484630832916
    野村    0.04307898597844882
    
    Feature 2
    アイスホッケー    0.12314369586804824
    群馬    0.11734247660369697
    国体    0.09758358466775546
    フィギュア    0.07967494922812343
    少年    0.06966151926393403
    
    Feature 3
    決勝    0.17775648082813153
    男子    0.1415161591768607
    成年    0.13896964605781512
    準決勝    0.10669825925511302
    少年    0.10114921378575456
    
    Feature 0
    00267800     3.139507891258316
    00261590     2.9042791235836773
    00267780     2.824946337171344
    00267810     2.687575441447076
    00267690     1.9435136609462225
    
    Feature 1
    00260660     2.1652786748662334
    00264500     2.042034597541854
    00261710     1.9204912229777378
    00260650     1.8473613697451237
    00261770     1.6826072449181502
    
    Feature 2
    00264550     2.2258764175760613
    00265130     2.1413384537343356
    00264810     2.1063727120265354
    00265250     1.8808112202308758
    00265790     1.8551204404326642
    
    Feature 3
    00264340     1.5903555678649122
    00265320     1.5595692470136513
    00264850     1.5262814236429483
    00265600     1.482087788101349
    00265420     1.4449599333480858
    NIL
    
  • c3 m-cluster-number (corpus-data-file-name)
    • C3 M法(cover-coefficient-based concept clustering methodology)に基づいて、コーパスの最適と思われるクラスタ数を求める
    • return DOUBLE-FLOAT
    • arguments:
      • corpus-data-file-name : コーパスから作成した索引語の出現頻度データのファイル名
    • comments : 実装にあたっては、岸田和明、「文書クラスタリングの技法:文献レビュー」, http://wwwsoc.nii.ac.jp/mslis/pdf/LIS49033.pdf を参考にした
  • sample usage
    NMF(87): (c^3m-cluster-number "sample/sports-corpus-data")
    20.974904271175472
    NMF(88): (c^3m-cluster-number "sample/politics-corpus-data")
    15.290476048493785
    
  • nmf-search (non-negative-matrix row-or-column-number &key type (cost-fn 'euclidean) (iteration 100) (results 10))
    • NMFを利用して、クエリと関連・類似したデータを見つけだす
    • return nil
    • arguments:
      • non-negative-matrix : (SIMPLE-ARRAY DOUBLE-FLOAT (* * )), 非負行列
      • row-or-column-number : 行または列番号
      • type row | column : クエリが行データか列データかを指定
      • cost-fn : euclidean | kl, default is Euclidean-norm, 目的関数、デフォルトはユークリッドノルム
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
      • results : 特徴成分の大きい行または列データをこのパラメタの数だけ表示、デフォルトは上位10件を表示
    • comments : 距離や類似度ではなく、特徴数1で非負行列因子分解することで関連・類似データを求めている
  • sample usage
    NMF(96): (setf x (sample-matrix 100 200))
     #2A((62.0 91.0 13.0 64.0 59.0 64.0 92.0 48.0 33.0 31.0 ...)
        (0.0 81.0 61.0 38.0 4.0 14.0 97.0 83.0 92.0 20.0 ...)
        (98.0 74.0 45.0 77.0 87.0 67.0 61.0 25.0 89.0 62.0 ...)
        (14.0 3.0 67.0 16.0 41.0 17.0 90.0 13.0 18.0 2.0 ...)
        (47.0 33.0 81.0 14.0 37.0 46.0 61.0 41.0 74.0 92.0 ...)
        (40.0 1.0 93.0 1.0 22.0 95.0 46.0 77.0 68.0 43.0 ...)
        (27.0 38.0 30.0 8.0 91.0 8.0 51.0 22.0 67.0 3.0 ...)
        (50.0 36.0 13.0 73.0 26.0 32.0 13.0 74.0 96.0 28.0 ...)
        (43.0 21.0 27.0 36.0 29.0 39.0 93.0 53.0 12.0 74.0 ...)
        (10.0 78.0 25.0 92.0 83.0 52.0 47.0 20.0 72.0 3.0 ...)
        ...)
    NMF(97): (nmf-search x 113 :type 'column)
    
    Feature 0
    113   145.19488284162378
    17   84.73937398353675
    123   83.8805446764401
    100   83.74400654487428
    183   82.11736662225094
    91   81.55075159303482
    194   81.04143723738916
    188   80.93626654118066
    97   80.77377247509784
    143   79.9072654735812
    NIL
    
  • nmf-corpus-search (corpus-file-data-name term-or-document-name &key type (iteration 100) (results 10))
    • NMFを利用して、クエリと関連・類似したコーパス内の索引語及び文書を見つけだす
    • return nil
    • arguments:
      • corpus-data-file-name : コーパスから作成した索引語の出現頻度データのファイル名
      • term-or-document-name : 索引語名または文書名
      • type : term | document,クエリが索引語名か文書名かを指定
      • iteration : default is 100, NMFアルゴリズムの反復回数、デフォルトは100回
      • results : 特徴成分の大きい索引語及び文書をこのパラメタの数だけ表示、デフォルトは上位10件を表示
    • comments : nmf-searchと同様に、距離や類似度ではなく、特徴数1で非負行列因子分解することで関連・類似データを求めている
  • sample usage
    NMF(96): (nmf-corpus-search "sample/sports-corpus-data" "西武" :type 'term :results 5)
    
    Feature 0
    西武    0.5136289748533318
    所沢    0.031111296370433392
    埼玉    0.03077730757866988
    期待    0.028991679735086512
    松坂    0.0247687314053667
    
    Feature 0
    00261790     9.17404383318168
    00266250     4.333328938007245
    00261710     1.3181090110603069
    00261730     0.09148867884277861
    00265240     0.062146341425771835
    NIL
    NMF(97): (nmf-corpus-search "sample/sports-corpus-data" "00267800" :type 'document :results 5)
    
    Feature 0
    大阪    0.21556014825397538
    マラソン    0.18511880535718545
    距離    0.11551386609160769
    練習    0.1048378562554717
    経験    0.08812313779269842
    
    Feature 0
    00267800     7.589221601169096
    00267780     1.0915481583469564
    00267810     0.932794061387184
    00261590     0.8585298782628589
    00267690     0.6222481411009909
    NIL
    NMF(98): (nmf-corpus-search "sample/politics-corpus-data" "クリントン" :type 'term :results 5)
    
    Feature 0
    クリントン    0.5041552834951207
    大統領    0.12319116718527458
    アイオワ    0.03738685338466452
    米    0.032777504270718856
    ヒラリー    0.029932395002703473
    
    Feature 0
    00240260     6.274784595077431
    00240860     5.015399391753567
    00266600     0.44472249859569957
    00240820     0.05063904550471321
    00251070     0.029699222336423015
    NIL
    

2.8 Spectral-Clustering

無向グラフを対象としたクラスタリングの package

  • spectral-clustering-mcut (m ncls &key (eigen-tolerance 100d0))
    • return1: Clustering result as a list of list of nodes
    • return2: Status code :success, :questionable, :input-error, or :fatal-error
    • arguments:
      • m : <SIMPLE-ARRAY DOUBLE-FLOAT (* *)>, similarity matrix of a graph
      • ncls : <integer>, number of cluster
      • eigen-tolerance : Acceptable error value for eigen computation
  • sample usage
     SPECTRAL-CLUSTERING(25): (load "sample/spectral-clustering-sample.cl" :external-format #+allegro :932 #-allegro :sjis)
     SPECTRAL-CLUSTERING(26): *spectral-nodevector*
     #("満足度" "差別" "林" "NPO" "生きがい" "中学" "服" "社会福祉" "市場" "ADL" ...)
     SPECTRAL-CLUSTERING(27): *spectral-w*
     #2A((1.0 0.0 0.0015822785208001733 0.0 0.0 0.0 0.0
          0.0015822785208001733 0.0 0.0015822785208001733 ...)
         (0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
         (0.0015822785208001733 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...)
         (0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0035273367539048195 0.0 0.0 ...)
         (0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 ...)
         (0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 ...)
         (0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 ...)
         (0.0015822785208001733 0.0 0.0 0.0035273367539048195 0.0 0.0 0.0
          1.0 0.0 0.0 ...)
         (0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 ...)
         (0.0015822785208001733 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 ...)
         ...)
     SPECTRAL-CLUSTERING(28): (spectral-clustering-mcut *spectral-w* 3)
    ((2 4 6 8 11 12 14 16 18 19 ...) (0 1 3 5 7 9 10 13 15 17 ...)
     (55 73 86 95 111 146 157 257 376))
     :SUCCESS
     SPECTRAL-CLUSTERING(29): (mapcar (lambda (c) (mapcar (lambda (n) (aref *spectral-nodevector* n)) c)) *)
    (("林" "生きがい" "服" "市場" "母子" "リサイクル" "腰痛" "手術" "金属" "理論" ...)
     ("満足度" "差別" "NPO" "中学" "社会福祉" "ADL" "癒し" "伊藤" "教材" "ひきこもり" ...)
     ("Method" "system" "language" "study" "education" "Web" "English"
      "japanese" "journal"))
    
  • Note
    References:
    1. 新納浩幸, 「R で学ぶクラスタ解析」, オーム社, 2007.
    2. A Min-max Cut Algorithm for Graph Partitioning and Data Clustering Chris H. Q. Ding, Xiaofeng He, Hongyuan Zha, Ming Gu, Horst D. Simon First IEEE International Conference on Data Mining (ICDM'01), 2001.

2.9 Optics

密度ベースクラスタリング OPTICS の package

  • Class
    • optics-output (クラスタリング結果)
      • accessor:
        • ordered-data : points, reachability-distance, core-distance, cluster-id
        • cluster-info : <list (cluster-id . size)>, 各クラスタID と 要素数
      • note: noise point は cluster-id として -1 が割当たる。
  • optics (input-path epsilon min-pts r-epsilon target-cols
    &key (file-type :sexp) (csv-type-spec '(string double-float double-float)) (distance :manhattan) (normalize nil) (external-format :default))
    • return: optics-output
    • arguments:
      • input-path : <string>
      • epsilon : <number> above 0, 近傍半径
      • min-pts : <integer> above 0, 最小データ数
      • r-epsilon : <number> above 0 not more than epsilon, threshold for reachability-distance
      • target-cols : <list string>, 対象データ列名 各列の型は数値(:numeric)
      • file-type : :sexp | :csv
      • csv-type-spec : <list symbol>, CSV ファイルを読み込みするときの型変更, e.g. '(string integer double-float double-float)
      • distance : :manhattan | :euclid | :cosine
      • normalize : t | nil
      • external-format : <acl-external-format>
  • sample usage
    OPTICS(10): (optics "sample/syobu.csv" 10 2 10 '("がく長" "がく幅" "花びら長" "花びら幅")
                         :file-type :csv :csv-type-spec '(string integer integer integer integer) 
                         :distance :manhattan :external-format #+allegro :932 #-allegro :sjis)
     #<OPTICS-OUTPUT>
     [ClusterID] SIZE | [-1] 6 | [1] 48 | [2] 96
    OPTICS(11): (ordered-data *)
     #(#("ID" "reachability" "core distance" "ClusterID") #(0 10.1 2.0 1)
      #(4 2.0 2.0 1) #(17 2.0 2.0 1) #(27 2.0 2.0 1) #(28 2.0 2.0 1)
      #(39 2.0 2.0 1) #(37 2.0 4.0 1) #(40 2.0 3.0 1) #(7 2.0 2.0 1) ...)
    

2.10 Association-Rule

アソシエーションルール分析の package

  • Class
    • assoc-result-dataset (分析結果)
      • accessor:
        • rules : 抽出結果 <list vector>
        • thresholds : 各閾値 (support confidence lift conviction)
        • rule-length : ルール最大長 <integer>
      • note: 抽出結果の vector は rule であり、以下の要素をもつ。
        • "premise": このルールの前提。単位ルールのlistである。
        • "conclusion": このルールの結論。単位ルールのlistである。
        • "support", "confidence", "lift", "conviction": このルールの有益性指標。
        • 単位ルール(長さ1のルール)は、「<データ列名>=<値>」というstringで表現される。
  • association-analyze (infile outfile target-variables key-variable rule-length
    &key (support 0) (confident 0) (lift 0) (conviction 0) (external-format :default) (file-type :sexp) (csv-type-spec '(string double-float)) (algorithm :lcm))
    • return: assoc-result-dataset
    • arguments:
      • infile : <string>
      • outfile : <string>
      • target-variables : <list string> 対象データ列名
      • key-variable : <string> 同一性判定キー列名
      • rule-length : <integer> beyond 2 ルールの最大長
      • support : <number> for percentage
      • confident : <number> for percentage
      • lift : <number> beyond 0
      • conviction : <number> beyond 0
      • file-type : :sexp | :csv
      • external-format : <acl-external-format>
      • csv-type-spec : <list symbol>, CSV ファイルを読み込みするときの型変更, e.g. '(string integer double-float double-float)
      • algorithm : :apriori | :da | :fp-growth | :eclat | :lcm
  • %association-analyze-apriori (unsp-dataset target-variables key-variable rule-length &key (support 0) (confident 0) (lift 0) (conviction 0))
    Association analyze with apriori algorithm.
    • return: assoc-result-dataset
    • arguments:
      • unsp-dataset: <unspecialized-dataset>
      • target-variables : (list of string) 対象データ列名
      • key-variable : <string> 同一性判定キー列名
      • rule-length : <integer> beyond 2 ルールの最大長
      • support : <number> for percentage
      • confident : <number> for percentage
      • lift : <number> beyond 0
      • conviction : <number> beyond 0
  • %association-analyze-da-ap-genrule
    Association analyze with da-ap-genrule algorithm. This is developer's idea using double-array for calculation.
    • return value and arguments are same as %association-analyze-apriori
  • %association-analyze-fp-growth
    Association analyze with frequent pattern growth algorithm
    • return value and arguments are same as %association-analyze-apriori
  • %association-analyze-eclat
    Association analyze with Eclat algorithm
    • return value and arguments are same as %association-analyze-apriori
  • %association-analyze-lcm
    Association analyze with Linear time Closed itemset Miner(LCM) algorithm
    • return value and arguments are same as %association-analyze-apriori
  • sample usage
     ASSOC(25): (association-analyze "sample/pos.sexp" "sample/result.sexp"
                                    '("商品名") "ID番号" 3 :support 2 :external-format #+allegro :932 #-allegro :sjis)
     #<ASSOC-RESULT-DATASET>
     THRESHOLDS: SUPPORT 2 | CONFIDENCE 0 | LIFT 0 | CONVICTION 0
     RULE-LENGTH: 3
     RESULT: 4532 RULES
     
     ASSOC(6): (setf dataset (read-data-from-file "sample/pos.sexp" :external-format #+allegro :932 #-allegro :sjis))
     #<HJS.LEARN.READ-DATA::UNSPECIALIZED-DATASET>
     DIMENSIONS: ID番号 | 商品名 | 数量 | 金額
     TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
     DATA POINTS: 19929 POINTS
     
     ASSOC(11): (%association-analyze-apriori dataset '("商品名") "ID番号" 3 :support 2)
     #<ASSOC-RESULT-DATASET>
     THRESHOLDS: SUPPORT 2 | CONFIDENCE 0 | LIFT 0 | CONVICTION 0
     RULE-LENGTH: 3
     RESULT: 4532 RULES
    

2.11 Decision-Tree

決定木分析のpackage

  • make-decision-tree (unspecialized-dataset objective-variable-name &key (test #'delta-gini) (epsilon 0))
    • CARTに基づく決定木を作成する
    • return: CONS, 決定木
    • arguments:
      • unspecialized-dataset : 分析対象データ
      • objective-variable-name : 目的変数名
      • test : delta-gini | delta-entropy , default is delta-gini, 分割基準関数、デフォルトではジニ係数を用いる
      • epsilon : default is 0, 決定木の事前刈り込みのためのパラメータ、デフォルトでは0
    • comments : 分割に際して、文字列データは名義尺度データとして、数値データは順序尺度データとして扱っている
    • note : 『集合知プログラミング』(Toby Segaran 著  當山仁健 鴨澤眞夫 訳 O'REILLY)を実装に際し、参考にした
  • print-decision-tree (decision-tree &optional (stream t))
    • 決定木を表示する
    • return: NIL
    • arguments:
      • decision-tree : make-decision-treeで作成した決定木
      • stream : 決定木の出力先、デフォルトはT
  • predict-decision-tree (query-vector unspecialized-dataset decision-tree)
    • 決定木による予測を行う
    • return: string, 決定木による判別予測結果
    • arguments:
      • query-vector : 説明変数からなるベクトル、目的変数に相当する場所には何が入っていてもよい
      • unspecialized-dataset : 決定木作成に用いたデータセット
      • decision-tree : 決定木
    • comments : 表示した決定木における質問(Yes/No)に答えていった最終帰結を返している
  • sample usage
    DECISION-TREE(40): (setf *syobu* (read-data-from-file "sample/syobu.csv" :type :csv 
                                                         :csv-type-spec
                                                        '(string integer integer integer integer)))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: 種類 | がく長 | がく幅 | 花びら長 | 花びら幅
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 150 POINTS
    DECISION-TREE(41): (setf *tree* (make-decision-tree *syobu* "種類"))
    (((("花びら長" . 30)
       (("花びら幅" . 18) ("花びら幅" . 23) ("花びら幅" . 20) ("花びら幅" . 19) ("花びら幅" . 25) ("花びら幅" . 24) ("花びら幅" . 21)
        ("花びら幅" . 14) ("花びら幅" . 15) ("花びら幅" . 22) ...))
      (("Virginica" . 50) ("Versicolor" . 50) ("Setosa" . 50))
      ((149 148 147 146 145 144 143 142 141 140 ...) (49 48 47 46 45 44 43 42 41 40 ...)))
     (((("花びら幅" . 18) (# # # # # # # # # # ...)) (("Versicolor" . 50) ("Virginica" . 50))
       ((70 100 101 102 103 104 105 107 108 109 ...) (50 51 52 53 54 55 56 57 58 59 ...)))
      (((# #) (# #) (# #)) ((#) (149 148 147 146 145 144 143 142 141 140 ...)) ((# # #) (# #) (# #)))
      (((# #) (# #) (# #)) ((# # #) (# # #) (# #)) ((# # #) (# #) (# #))))
     ((("Setosa" . 50)) (49 48 47 46 45 44 43 42 41 40 ...)))
    DECISION-TREE(42): (print-decision-tree *tree*)
    [30 <= 花びら長?]((Virginica . 50) (Versicolor . 50) (Setosa . 50))
       Yes->[18 <= 花びら幅?]((Versicolor . 50) (Virginica . 50))
          Yes->[49 <= 花びら長?]((Virginica . 45) (Versicolor . 1))
             Yes->((Virginica . 43))
             No->[31 <= がく幅?]((Versicolor . 1) (Virginica . 2))
                Yes->((Versicolor . 1))
                No->((Virginica . 2))
          No->[50 <= 花びら長?]((Virginica . 5) (Versicolor . 49))
             Yes->[16 <= 花びら幅?]((Versicolor . 2) (Virginica . 4))
                Yes->[53 <= 花びら長?]((Virginica . 1) (Versicolor . 2))
                   Yes->((Virginica . 1))
                   No->((Versicolor . 2))
                No->((Virginica . 3))
             No->[17 <= 花びら幅?]((Versicolor . 47) (Virginica . 1))
                Yes->((Virginica . 1))
                No->((Versicolor . 47))
       No->((Setosa . 50))
    NIL
    DECISION-TREE(43): (make-decision-tree *syobu* "種類" :epsilon 0.1);剪定の例
    (((("花びら長" . 30)
       (("花びら幅" . 18) ("花びら幅" . 23) ("花びら幅" . 20) ("花びら幅" . 19) ("花びら幅" . 25) ("花びら幅" . 24) ("花びら幅" . 21)
        ("花びら幅" . 14) ("花びら幅" . 15) ("花びら幅" . 22) ...))
      (("Virginica" . 50) ("Versicolor" . 50) ("Setosa" . 50))
      ((149 148 147 146 145 144 143 142 141 140 ...) (49 48 47 46 45 44 43 42 41 40 ...)))
     (((("花びら幅" . 18) (# # # # # # # # # # ...)) (("Versicolor" . 50) ("Virginica" . 50))
       ((70 100 101 102 103 104 105 107 108 109 ...) (50 51 52 53 54 55 56 57 58 59 ...)))
      ((("Virginica" . 45) ("Versicolor" . 1)) (70 100 101 102 103 104 105 107 108 109 ...))
      ((("Virginica" . 5) ("Versicolor" . 49)) (50 51 52 53 54 55 56 57 58 59 ...)))
     ((("Setosa" . 50)) (49 48 47 46 45 44 43 42 41 40 ...)))
    DECISION-TREE(44): (print-decision-tree *)
    [30 <= 花びら長?]((Virginica . 50) (Versicolor . 50) (Setosa . 50))
       Yes->[18 <= 花びら幅?]((Versicolor . 50) (Virginica . 50))
          Yes->((Virginica . 45) (Versicolor . 1))
          No->((Virginica . 5) (Versicolor . 49))
       No->((Setosa . 50))
    NIL
    DECISION-TREE(45): (setf *query* #("?" 53 30 33 10));左から「種類,がく長,がく幅,花びら長,花びら幅」の項目を示す質問ベクトル
    #("?" 53 30 33 10)
    DECISION-TREE(46): (predict-decision-tree *query* *syobu* *tree*)
    "Versicolor"
    
  • decision-tree-validation (unspecialized-dataset objective-variable-name decision-tree)
    • 学習用データセットで作成した決定木の判別予測性能を、テスト用データセットを用いて検証する
    • return: CONS, 検証結果
    • arguments:
      • unspecialized-dataset : テスト用データセット
      • objective-variable-name : 目的変数名
      • decision-tree : 学習用データセットで作成した決定木
    • comments : 返り値の連想リストの各要素は、左から決定木による予測、テスト用データにおける正解、件数をそれぞれ表している
  • sample usage
    DECISION-TREE(64): (setf *bc-train* (read-data-from-file "sample/bc.train.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 338 POINTS
    DECISION-TREE(65): (setf *tree* (make-decision-tree *bc-train* "Class"))
    (((("Cell.size" . 4.0)
       (("Bare.nuclei" . 4.0) ("Bare.nuclei" . 1.0) ("Bare.nuclei" . 5.0) ("Bare.nuclei" . 10.0) ("Bare.nuclei" . 2.0) ("Bare.nuclei" . 3.0) ("Bare.nuclei" . 8.0)
        ("Bare.nuclei" . 6.0) ("Bare.nuclei" . 7.0) ("Bare.nuclei" . 9.0) ...))
      (("malignant" . 117) ("benign" . 221)) ((337 334 329 323 317 305 295 292 291 285 ...) (336 335 333 332 331 330 328 327 326 325 ...)))
     (((("Bl.cromatin" . 4.0) (# # # # # # # # # # ...)) (("benign" . 7) ("malignant" . 99))
       ((2 7 10 18 19 25 28 31 34 35 ...) (0 1 20 23 26 54 74 80 119 122 ...)))
      (((# #) (# #) (# #)) ((#) (334 329 323 305 295 292 291 280 275 274 ...)) ((# # #) (# #) (# #)))
      (((# #) (# #) (# #)) ((#) (145 140 133 119 80 54 26 23)) ((# # #) (# #) (# # #))))
     (((("Bare.nuclei" . 6.0) (# # # # # # # # # # ...)) (("malignant" . 18) ("benign" . 214)) ((11 32 60 72 86 128 142 165 170 217) (3 4 5 6 8 9 12 13 14 15 ...)))
      ((("malignant" . 10)) (11 32 60 72 86 128 142 165 170 217)) (((# #) (# #) (# #)) ((#) (131 51 50 27)) ((# # #) (# # #) (# # #)))))
    DECISION-TREE(66): (setf *bc-test* (read-data-from-file "sample/bc.test.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 345 POINTS
    DECISION-TREE(67): (decision-tree-validation *bc-test* "Class" *tree*)
    ((("benign" . "malignant") . 4) (("malignant" . "malignant") . 118) (("malignant" . "benign") . 9) (("benign" . "benign") . 214))
    
  • make-regression-tree (unspecialized-dataset objective-variable-name &key (epsilon 0))
    • 回帰木を作成する
    • return: CONS, 回帰木
    • argumrnts:
      • unspecialized-dataset : 分析対象データ
      • objective-variable-name : 目的変数名
      • epsilon : default is 0, 回帰木の事前刈り込みのためのパラメータ、デフォルトでは0
    • comments : 分岐指標には分散差を用いている
  • print-regression-tree (regression-tree &optional (stream t))
    • 回帰木を表示する
    • return: NIL
    • arguments:
      • regression-tree : make-regression-treeで作成した回帰木
      • stream : 回帰木の出力先、デフォルトはT
  • predict-regression-tree (query-vector unspecialized-dataset regression-tree)
    • 回帰木による予測を行う
    • return: real, 回帰木による予測値
    • arguments:
      • query-vector : 説明変数からなるベクトル、目的変数に相当する場所には何が入っていてもよい
      • unspecialized-dataset : 回帰木作成に用いたデータセット
      • regression-tree : 回帰木
    • comments : 表示した回帰木における質問(Yes/No)に答えていった最終帰結を返している
  • sample usage
    DECISION-TREE(68): (setf *cars* (read-data-from-file "sample/cars.csv" :type :csv
                                                          :csv-type-spec '(double-float double-float)))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: speed | distance
    TYPES:      UNKNOWN | UNKNOWN
    DATA POINTS: 50 POINTS
    DECISION-TREE(69): (setf *tree* (make-regression-tree *cars* "distance" :epsilon 35))
    (((("speed" . 18.0)
       (("speed" . 25.0) ("speed" . 24.0) ("speed" . 23.0) ("speed" . 22.0) ("speed" . 20.0)
        ("speed" . 19.0) ("speed" . 17.0) ("speed" . 16.0) ("speed" . 15.0) ("speed" . 14.0) ...))
      ((85.0 . 1) (120.0 . 1) (93.0 . 1) (92.0 . 1) (70.0 . 1) (66.0 . 1) (64.0 . 1) (52.0 . 1)
       (48.0 . 1) (68.0 . 1) ...)
      ((49 48 47 46 45 44 43 42 41 40 ...) (30 29 28 27 26 25 24 23 22 21 ...)))
     (((("speed" . 24.0) (# # # # # # # # # # ...))
       ((42.0 . 1) (76.0 . 1) (84.0 . 1) (36.0 . 1) (46.0 . 1) (68.0 . 1) (32.0 . 1) (48.0 . 1)
        (52.0 . 1) (56.0 . 2) ...)
       ((45 46 47 48 49) (31 32 33 34 35 36 37 38 39 40 ...)))
      (((85.0 . 1) (120.0 . 1) (93.0 . 1) (92.0 . 1) (70.0 . 1)) (45 46 47 48 49))
      (((54.0 . 1) (66.0 . 1) (64.0 . 1) (52.0 . 1) (48.0 . 1) (32.0 . 1) (68.0 . 1) (46.0 . 1)
        (36.0 . 1) (84.0 . 1) ...)
       (31 32 33 34 35 36 37 38 39 40 ...)))
     (((("speed" . 13.0) (# # # # # # # # # # ...))
       ((2.0 . 1) (4.0 . 1) (22.0 . 1) (16.0 . 1) (10.0 . 2) (18.0 . 1) (17.0 . 1) (14.0 . 1)
        (24.0 . 1) (28.0 . 2) ...)
       ((15 16 17 18 19 20 21 22 23 24 ...) (0 1 2 3 4 5 6 7 8 9 ...)))
      (((50.0 . 1) (40.0 . 2) (32.0 . 2) (54.0 . 1) (20.0 . 1) (80.0 . 1) (60.0 . 1) (36.0 . 1)
        (46.0 . 1) (34.0 . 2) ...)
       (15 16 17 18 19 20 21 22 23 24 ...))
      (((# #) (# # # # # # # # # # ...) (# #)) ((# # # # # # # #) (14 13 12 11 10 9 8 7 6))
       ((# # # # #) (5 4 3 2 1 0)))))
    DECISION-TREE(70): (print-regression-tree *tree*)
    [18.0 <= speed?] (mean = 42.98, n = 50)
       Yes->[24.0 <= speed?] (mean = 65.26, n = 19)
          Yes->(mean = 92.00, n = 5)
          No->(mean = 55.71, n = 14)
       No->[13.0 <= speed?] (mean = 29.32, n = 31)
          Yes->(mean = 39.75, n = 16)
          No->[10.0 <= speed?] (mean = 18.20, n = 15)
             Yes->(mean = 23.22, n = 9)
             No->(mean = 10.67, n = 6)
    NIL
    DECISION-TREE(71): (setf *query* #(24.1 "?"))
    #(24.1 "?")
    DECISION-TREE(72): (predict-regression-tree *query* *cars* *tree*)
    92.0
    
  • regression-tree-validation (unspecialized-dataset objective-variable-name regression-tree)
    • 学習用データセットで作成した回帰木の予測性能を、テスト用データセットを用いて検証する
    • return: real, 残差平方和(error sum of squares)
    • arguments:
      • unspecialized-dataset : テスト用データセット
      • objective-variable-name : 目的変数名
      • regression-tree : 学習用データセットで作成した回帰木
  • sample usage
    DECISION-TREE(10): (setf *bc-train* (read-data-from-file "sample/bc.train.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 338 POINTS
    DECISION-TREE(11): (setf *tree* (make-regression-tree *bc-train* "Cell.size"))
    (((("Class" . "benign")
       (("Bare.nuclei" . 4.0) ("Bare.nuclei" . 1.0) ("Bare.nuclei" . 5.0) ("Bare.nuclei" . 10.0) ("Bare.nuclei" . 2.0)
        ("Bare.nuclei" . 3.0) ("Bare.nuclei" . 8.0) ("Bare.nuclei" . 6.0) ("Bare.nuclei" . 7.0) ("Bare.nuclei" . 9.0) ...))
      ((7.0 . 10) (9.0 . 3) (3.0 . 22) (6.0 . 11) (5.0 . 18) (2.0 . 22) (1.0 . 188) (10.0 . 25) (8.0 . 19) (4.0 . 20))
      ((336 335 333 332 331 330 328 327 326 325 ...) (337 334 329 323 305 295 292 291 285 280 ...)))
     (((("Cell.shape" . 7.0) (# # # # # # # # # # ...)) ((8.0 . 1) (7.0 . 1) (4.0 . 5) (2.0 . 15) (3.0 . 12) (1.0 . 187))
       ((1 124) (0 3 4 5 6 8 9 12 13 14 ...)))
      (((# #) (# #) (# #)) ((#) (1)) ((#) (124))) (((# #) (# # # #) (# #)) ((# # #) (# # #) (# # #)) ((# # #) (# #) (# # #))))
     (((("Cell.shape" . 7.0) (# # # # # # # # # # ...))
       ((1.0 . 1) (2.0 . 7) (9.0 . 3) (3.0 . 10) (6.0 . 11) (4.0 . 15) (5.0 . 18) (7.0 . 9) (10.0 . 25) (8.0 . 18))
       ((2 23 52 55 71 76 80 83 84 85 ...) (7 10 11 18 19 20 24 25 26 27 ...)))
      (((# #) (# # # # # #) (# #)) ((# # #) (# # #) (# # #)) ((# # #) (# # #) (# # #)))
      (((# #) (# # # # # # # # #) (# #)) ((# # #) (# #) (# # #)) ((# # #) (# # #) (# # #)))))
    DECISION-TREE(12): (setf *bc-test* (read-data-from-file "sample/bc.test.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 345 POINTS
    DECISION-TREE(13): (regression-tree-validation *bc-test* "Cell.size" *tree*)
    812.9077777777777
    

2.12 Random-Forest

ランダムフォレストのpackage

  • make-random-forest (unspecialized-dataset objective-variable-name &key (test #'delta-gini) (tree-number 500))
    • 判別分析のためのランダムフォレストを作成する
    • return: (SIMPLE-ARRAY T (* )), CARTに基づく未剪定の決定木からなるランダムフォレスト
    • arguments:
      • unspecialized-dataset : 分析対象データ
      • objective-variable-name : 目的変数名
      • test : delta-gini | delta-entropy , default is delta-gini, 分割基準関数、デフォルトではジニ係数を用いる
      • tree-number : 森を構成する木の本数、デフォルトは500本
    • note : "The Elements of Statistical Learning:Data Mining, Inference, and Prediction" (Trevor Hastie, Robert Tibshirani, Jerome Friedman) http://www-stat.stanford.edu/~tibs/ElemStatLearn/ の15章を実装に際し、参考にした
  • predict-forest (query-vector unspecialized-dataset forest)
    • ランダムフォレストによる予測を行う
    • return: string, ランダムフォレストによる判別予測結果
    • arguments:
      • query-vector : 説明変数からなるベクトル、目的変数に相当する場所には何が入っていてもよい
      • unspecialized-dataset : ランダムフォレスト作成に用いたデータセット
      • forest : make-random-forest で作成したランダムフォレスト
    • comments : 森を構成する各決定木の多数決によって判別予測を行っている
  • forest-validation (unspecialized-dataset objective-variable-name forest)
    • 学習用データセットで作成したランダムフォレストの判別予測性能を、テスト用データセットを用いて検証する
    • return: CONS, 検証結果
    • arguments:
      • unspecialized-dataset : 検証用データセット
      • objective-variable-name : 目的変数名
      • forest : 学習用データセットで作成したランダムフォレスト
    • comments : 返り値の連想リストの各要素は、左からランダムフォレストによる予測、テスト用データにおける正解、件数をそれぞれ表している
  • sample usage
    RANDOM-FOREST(24): (setf *bc-train* (read-data-from-file "sample/bc.train.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 338 POINTS
    RANDOM-FOREST(25): (setf *forest* (make-random-forest *bc-train* "Class"))
    #((((("Normal.nucleoli" . 3.0) NIL) (("benign" . 215) ("malignant" . 123)) ((336 335 328 323 322 319 314 310 304 303 ...) (337 334 333 332 331 330 329 327 326 325 ...)))
       (((# NIL) (# #) (# #)) ((# # #) (# #) (# # #)) ((# # #) (# #) (# #))) (((# NIL) (# #) (# #)) ((#) (27 43 133 150 163 227 329)) ((# # #) (# #) (# # #))))
      (((("Cell.size" . 3.0) NIL) (("benign" . 227) ("malignant" . 111)) ((335 331 329 328 324 322 321 316 313 310 ...) (337 336 334 333 332 330 327 326 325 323 ...)))
       (((# NIL) (# #) (# #)) ((# # #) (# # #) (# # #)) ((#) (39 61 234 255 331))) (((# NIL) (# #) (# #)) ((#) (127 164)) ((#) (1 3 4 5 6 7 10 11 13 15 ...))))
      (((("Normal.nucleoli" . 3.0) NIL) (("malignant" . 118) ("benign" . 220)) ((337 336 334 320 319 310 308 307 306 301 ...) (335 333 332 331 330 329 328 327 326 325 ...)))
       (((# NIL) (# #) (# #)) ((# # #) (# #) (# # #)) ((# # #) (# #) (# #))) (((# NIL) (# #) (# #)) ((#) (8 12 26 91 117 137 180 219 284 298)) ((# # #) (# # #) (# # #))))
      ...)
    RANDOM-FOREST(26): (setf *query* #(3.0 1.0 1.0 1.0 2.0 1.0 2.0 1.0 1.0 "?"))
    #(3.0 1.0 1.0 1.0 2.0 1.0 2.0 1.0 1.0 "?")
    RANDOM-FOREST(27): (predict-forest *query* *bc-train* *forest*)
    "benign"
    RANDOM-FOREST(28): (setf *bc-test* (read-data-from-file "sample/bc.test.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 345 POINTS
    RANDOM-FOREST(29): (forest-validation *bc-test* "Class" *forest*)
    ((("benign" . "malignant") . 3) (("malignant" . "benign") . 7)
     (("malignant" . "malignant") . 119) (("benign" . "benign") . 216))
    
  • make-regression-forest (unspecialized-dataset objective-variable-name &key (tree-number 500))
    • 回帰分析のためのランダムフォレストを作成する
    • return: (SIMPLE-ARRAY T (* )), CARTに基づく未剪定の回帰木からなる、回帰ランダムフォレスト
    • arguments:
      • unspecialized-dataset : 分析対象データ
      • objective-variable-name : 目的変数名
      • tree-number : 森を構成する木の本数、デフォルトは500本
  • predict-regression-forest (query-vector unspecialized-dataset regression-forest)
    • 回帰ランダムフォレストによる予測を行う
    • return: real , 回帰ランダムフォレストによる予測値
    • arguments:
      • query-vector : 説明変数からなるベクトル、目的変数に相当する場所には何が入っていてもよい
      • unspecialized-dataset : 回帰ランダムフォレスト作成に用いたデータセット
      • regression-forest : make-regression-forest で作成した回帰ランダムフォレスト
    • comments : 森を構成する各回帰木の予測値の平均をもって、回帰ランダムフォレストの予測値としている
  • regression-forest-validation (unspecialized-dataset objective-variable-name regression-forest)
    • 学習用データセットで作成した回帰ランダムフォレストの性能を、テスト用データセットを用いて検証する
    • return: real, 残差平方和(error sum of squares)
    • arguments:
      • unspecialized-dataset : テスト用データセット
      • objective-variable-name : 目的変数名
      • regression-forest : 学習用データセットで作成した回帰ランダムフォレスト
  • sample usage
    RANDOM-FOREST(40): (setf *bc-train* (read-data-from-file "sample/bc.train.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 338 POINTS
    RANDOM-FOREST(41):(setf *regression-forest* (make-regression-forest *bc-train* "Cell.size"))
    #((((("Class" . "malignant") NIL)
        ((9.0 . 2) (6.0 . 7) (7.0 . 12) (8.0 . 22) (5.0 . 20) (3.0 . 23) (4.0 . 25) (1.0 . 164) (2.0 . 32) (10.0 . 31))
        ((335 327 322 321 320 319 318 314 312 310 ...) (337 336 334 333 332 331 330 329 328 326 ...)))
       (((# NIL) (# # # # # # # # # #) (# #)) ((# # #) (# # #) (# # #)) ((# # #) (# # #) (# # #)))
       (((# NIL) (# # # # #) (# #)) ((# # #) (# #) (# # #)) ((# # #) (# #) (# # #))))
      (((("Cell.shape" . 6.0) NIL)
        ((9.0 . 1) (2.0 . 20) (5.0 . 16) (7.0 . 13) (4.0 . 16) (3.0 . 19) (10.0 . 20) (6.0 . 10) (8.0 . 22) (1.0 . 201))
        ((335 326 325 317 316 314 312 311 307 299 ...) (337 336 334 333 332 331 330 329 328 327 ...)))
       (((# NIL) (# # # # # # #) (# #)) ((# # #) (# # #) (# #)) ((# # #) (# # #) (# # #)))
       (((# NIL) (# # # # # # # # #) (# #)) ((# # #) (# # #) (# # #)) ((# # #) (# # #) (# # #))))
      (((("Epith.c.size" . 3.0) NIL)
        ((9.0 . 4) (2.0 . 16) (4.0 . 23) (7.0 . 9) (6.0 . 5) (3.0 . 24) (5.0 . 16) (10.0 . 17) (8.0 . 21) (1.0 . 203))
        ((334 332 324 320 319 315 314 313 312 308 ...) (337 336 335 333 331 330 329 328 327 326 ...)))
       (((# NIL) (# # # # # # # # # #) (# #)) ((# # #) (# # #) (# # #)) ((# # #) (# # #) (# # #)))
       (((# NIL) (# # # # #) (# #)) ((# # #) (# # #) (# # #)) ((# # #) (# #) (# # #))))
      ...)
    RANDOM-FOREST(42): (setf *query* #(5.0 "?" 1.0 1.0 2.0 1.0 3.0 1.0 1.0 "benign"))
    #(5.0 "?" 1.0 1.0 2.0 1.0 3.0 1.0 1.0 "benign")
    RANDOM-FOREST(43): (predict-regression-forest *query* *bc-train* *regression-forest*)
    1.0172789943526082
    RANDOM-FOREST(44): (setf *bc-test* (read-data-from-file "sample/bc.test.csv"
                                                         :type :csv
                                                         :csv-type-spec 
                                                         (append (loop for i below 9 collect 'double-float) '(string))))
    #<UNSPECIALIZED-DATASET>
    DIMENSIONS: Cl.thickness | Cell.size | Cell.shape | Marg.adhesion | Epith.c.size | Bare.nuclei | Bl.cromatin | Normal.nucleoli | Mitoses | Class
    TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN
    DATA POINTS: 345 POINTS
    RANDOM-FOREST(45): (regression-forest-validation *bc-test* "Cell.size" *regression-forest*)
    561.9792657670295
    

2.13 K-Nearest-Neighbor

k-近傍法(k-nearest neighbor algorithm) の pacakge

  • Class
    • k-nn-estimator (推定器)
      • accessor:
        • vec : data for learning
        • vec-labels : explanatories
        • vec-profiles : type infomation for each explanatories
        • vec-weight : 重み
        • mins : minimum value for each explanatories
        • maxs : maximum value for each explanatories
        • target : objective variable
        • teachers : values of target
        • k : k-値
        • distance : 距離
  • k-nn-analyze (learning-data k target explanatories
    &key (distance :euclid) use-weight weight-init normalize)
    • return: <k-nn-estimator>
    • arguments:
      • learning-data : <unspecialized-dataset>
      • k : <integer>
      • target : <string>
      • explanatories : <list string> | :all
      • distance : :euclid | :manhattan
      • use-weight : nil | :class | :data
      • weight-init :
        • use-weight が :class なら ((class-name . weight) …) の <assoc-list>
        • use-weight が :data なら重みの vector、list、もしくは入力データの列名(string)が許される。列名が渡された場合、その系列をデータに対する重みとみなす。
      • normalize : t | nil
  • k-nn-estimate (estimator in-data)
    • return: <unspecialized-dataset>
    • arguments:
      • estimator : <k-nn-estimator> 推定器
      • in-data : <unspecialized-dataset> 推定対象データ
  • sample usage
     K-NN(12): (setf data-for-learn
                 (read-data-from-file "sample/learn.csv" :type :csv 
                                      :csv-type-spec (cons 'string (make-list 105 :initial-element 'double-float))))
     #<HJS.LEARN.READ-DATA::UNSPECIALIZED-DATASET>
     DIMENSIONS: id | A/C CLUTCH | A/C PRESSURE | A/C PRESSURE SENSOR | A/C SWITCH | AF B1 LAMBDA CMD | AF B2 LAMBDA CMD | ...
     TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | ...
     DATA POINTS: 344 POINTS
     
     K-NN(13): (setf estimator
                 (k-nn-analyze data-for-learn 2 "id" :all :distance :manhattan :normalize t))
     Number of self-misjudgement : 277
     #<K-NN-ESTIMATOR @ #x2144ae72>
     
     K-NN(14): (setf data-for-estimate
                 (read-data-from-file "sample/estimate.csv" :type :csv
                                      :csv-type-spec (make-list 105 :initial-element 'double-float)))
     #<HJS.LEARN.READ-DATA::UNSPECIALIZED-DATASET>
     DIMENSIONS: A/C CLUTCH | A/C PRESSURE | A/C PRESSURE SENSOR | A/C SWITCH | AF B1 LAMBDA CMD | AF B2 LAMBDA CMD | AF FB CMD | ...
     TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | ...
     DATA POINTS: 23 POINTS
     
     K-NN(15): (k-nn-estimate estimator data-for-estimate)
     #<HJS.LEARN.READ-DATA::UNSPECIALIZED-DATASET>
     DIMENSIONS: estimated-id | A/C CLUTCH | A/C PRESSURE | A/C PRESSURE SENSOR | A/C SWITCH | AF B1 LAMBDA CMD | AF B2 LAMBDA CMD | ...
     TYPES:      UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN | ...
     DATA POINTS: 23 POINTS
    
  • Note
    target すなわち目的変数の値の型が string であった場合は判別分析、number であった場合は 回帰分析を行なう。判別分析の場合、自己分析結果の誤判別数( Number of self-misjudgement)が表示される。

2.14 Support-Vector-Machine

サポートベクターマシンの package

  • Class for kernel-fn
    • polynomial-kernel
      • reader:
        • dimension : 次数
        • homogeneousp : 斉次多項式か否か
      • generator:
        • polynomial-kernel (dimension homogeneousp)
    • radial-kernel
      • reader:
        • gamma : <number> above 0
      • generator:
        • radial-kernel (gamma)
        • gaussian-kernel (sigma2)
    • sigmoid-kernel
      • reader:
        • kappa : <number>
        • shift : <number>
      • generator:
        • sigmoid-kernel (kappa shift)
  • Parameter
     SVM(18): +linear-kernel+
     #<POLYNOMIAL-KERNEL : D = 1 HOMOGENEOUS>
    
  • svm (kernel positive-data negative-data &key (iterations 100) (lagrange-iterations 20) (tolerance 1.0d-20))
    • return: <Closure>
      • return of <Closure>: two values, (result number)
        • result : t(positive) | nil(negative)
        • number : value of kernel-fn
      • argument of <Closure>: <seq>, estimation target
    • arguments:
      • kernel : <kernel-fn>
      • positive-data : <seq seq>, training data e.g. '((8 8) (8 20) (8 44))
      • negative-data : <seq seq>, training data
      • iterations : <integer>
      • lagrange-iterations : <integer>
      • tolerance : <number>, 許容誤差
  • sample usage
    SVM(8): (defparameter *positive-set*
      '((8.0 8.0) (8.0 20.0) (8.0 44.0) (8.0 56.0) (12.0 32.0) (16.0 16.0) (16.0 48.0)
        (24.0 20.0) (24.0 32.0) (24.0 44.0) (28.0 8.0) (32.0 52.0) (36.0 16.0)))
    SVM(9): (defparameter *negative-set*
      '((36.0 24.0) (36.0 36.0) (44.0 8.0) (44.0 44.0) (44.0 56.0)
        (48.0 16.0) (48.0 28.0) (56.0 8.0) (56.0 44.0) (56.0 52.0)))
    SVM(21): (setf linear-fcn
                  (svm +linear-kernel+ *positive-set* *negative-set*))
                  #<Closure (:INTERNAL DECISION 0) @ #x212ebfc2>
    SVM(22): (funcall linear-fcn (car (last *positive-set*)))
    NIL
    -46.88582273865575
    SVM(23): (setf polynomial-fcn
               (svm (polynomial-kernel 3 nil) *positive-set* *negative-set*))
     #<Closure (:INTERNAL DECISION 0) @ #x20b7c122>
    SVM(24): (funcall polynomial-fcn (car (last *positive-set*)))
    T
    4.849458930036461e+7
    SVM(25): (funcall polynomial-fcn '(30.0 20.0))
    T
    2.3224182219070548e+8
    

2.15 Self-Organizing-Map

自己組織化マップの package

  • do-som-by-filename (in-data-file s-topol s-neigh xdim ydim randomize length ialpha iradius num-labels directory &key debug)
    • return: nil
    • arguments:
      • in-data-file : <string>, input data
      • s-topol : "hexa" | "rect", topology type
      • s-neigh : "bubble" | "gaussian", neighborhood type
      • xdim : <integer>, x size of output map
      • ydim : <integer>, y size of output map
      • randomize : random seed for initialization

      ;; training parameters

      • length : how many times train for path1
      • ialpha : learning rate for path1 x100
      • iradius : learning radius for path1 x100

      ;; visualization parameters

      • num-labels : number of labels on same map point

      ;; output ps directory

      • directory : <string>
      • debug : t | nil
  • sample usage
    SOM(27): (do-som-by-filename "som/animal.dat" "hexa" "gaussian"
                                 24 16 123 10000 5 2400 10
                                 '(:absolute #+unix "tmp" #+mswindows "temp"))
    in-data-file [som/animal.dat]
    s-topol[hexa] s-neigh[gaussian] xdim[24] ydim[16] nrand[123]
    num-label[10]
    step 1 : initialization 
    step 2 : learning 
    step 3 : calibration 
    step 4 : labeling 
    step 5 : making sammon map
    384 entries in codebook
    xma-xmi 3.074987831736982 yma-ymi 2.129596273225805
    #P"/tmp/out"
    #P"/tmp/tempa175816032024.ps"
    

2.16 Time-Series-Read-Data

機械学習対象データを時系列データとして読み込むための package

  • Structure
    • ts-point (時系列データ点)
      • time : その点の時間, 1 以上の整数
      • freq : その点が何周期目か, 1 以上の整数
      • label : その点の名前 e.g. "2009/Jan/5th"
      • pos : その点の座標
  • Class
    • time-series-dataset (時系列データ)
      • accessor
        • ts-points : ts-point の vector
        • ts-freq : 時間単位ごとの観測値数
        • ts-start : 最初の観測値の時間、ts-point における time と freq の list で表される。sample usage を参照のこと。
        • ts-end : 最後の観測値の時間、ts-start に同じ
  • time-series-data ((d unspecialized-dataset) &key (start 1) end (frequency 1) (range :all) except time-label)
    • return: <time-series-dataset>
    • arguments:
      • d : <unspecialized-dataset>
      • start : <list integer integer> | integer, 始まり時間の指定、1 以上の整数またはそのリスト。 e.g. (1861 3)
      • end : <list integer integer> | integer, 終わり時間の指定、start に同じ。指定しない場合は全ての行が読み込まれる。
      • frequency : integer >= 1, 周期の指定
      • range : :all | <list integer>, 結果に入る列の指定、0から始まる。 e.g. '(0 1 3 4)
      • except : <list integer>, :range の逆、結果に入らない列の指定、0からはじまる。 e.g. '(2)
      • time-label : integer, 時系列データ点の label を表す列の指定、指定しない場合は label なし
  • ts-cleaning ((d time-series-dataset) &key interp-types outlier-types outlier-values)
    • return: <time-series-dataset>
    • arguments:
      • d : <time-series-dataset>
      • interp-types : <list, nil | :zero | :min | :max | :mean | :median | :spline>
      • outlier-types : <list, nil | :std-dev | :mean-dev | :user | :smirnov-grubbs>
      • outlier-values : <list, nil | outlier-type に見合った値>
    • comment: Read-Data の dataset-cleaning と内容は同じ。外れ値検出, 欠損値補間を行なう。
  • sample usage
     TS-READ-DATA(26): (setf d (read-data-from-file "sample/msi-access-stat/access-log-stat.sexp"))
     #<UNSPECIALIZED-DATASET>
     DIMENSIONS: date/time | hits
     TYPES:      UNKNOWN | UNKNOWN
     DATA POINTS: 9068 POINTS
     TS-READ-DATA(27): (setf msi-access (time-series-data d :range '(1) :time-label 0
                                        :frequency 24 :start '(18 3)))
     #<TIME-SERIES-DATASET>
     DIMENSIONS: hits
     TYPES:      NUMERIC
     FREQUENCY:  24
     START:      (18 3)
     END:        (25 2)
     POINTS:     168
     TIME-LABEL: date/time
     TS-READ-DATA(28): (setf msi-access (time-series-data d :range '(1) :time-label 0
                                        :frequency 24 :start '(18 3) :end '(18 24)))
     #<TIME-SERIES-DATASET>
     DIMENSIONS: hits
     TYPES:      NUMERIC
     FREQUENCY:  24
     START:      (18 3)
     END:        (18 24)
     POINTS:     22
     TIME-LABEL: date/time
     TS-READ-DATA(29): (setf msi-access (time-series-data d :range '(1) :time-label 0
                                        :frequency 3))
     #<TIME-SERIES-DATASET>
     DIMENSIONS: hits
     TYPES:      NUMERIC
     FREQUENCY:  3
     START:      (1 1)
     END:        (56 3)
     POINTS:     168
     TIME-LABEL: date/time
     TS-READ-DATA(29): (ts-points msi-access)
     #(#S(TS-POINT :TIME 1 :FREQ 1 :LABEL "12/May/2008 03:00-03:59" :POS #(210.0))
       #S(TS-POINT :TIME 1 :FREQ 2 :LABEL "12/May/2008 04:00-04:59" :POS #(265.0))
       #S(TS-POINT :TIME 1 :FREQ 3 :LABEL "12/May/2008 05:00-05:59" :POS #(219.0))
       #S(TS-POINT :TIME 2 :FREQ 1 :LABEL "12/May/2008 06:00-06:59" :POS #(284.0))
       #S(TS-POINT :TIME 2 :FREQ 2 :LABEL "12/May/2008 07:00-07:59" :POS #(287.0))
       #S(TS-POINT :TIME 2 :FREQ 3 :LABEL "12/May/2008 08:00-08:59" :POS #(829.0))
       #S(TS-POINT :TIME 3 :FREQ 1 :LABEL "12/May/2008 09:00-09:59" :POS #(1039.0))
       #S(TS-POINT :TIME 3 :FREQ 2 :LABEL "12/May/2008 10:00-10:59" :POS #(1765.0))
       #S(TS-POINT :TIME 3 :FREQ 3 :LABEL "12/May/2008 11:00-11:59" :POS #(2021.0))
       #S(TS-POINT :TIME 4 :FREQ 1 :LABEL "12/May/2008 12:00-12:59" :POS #(1340.0)) ...)
    

2.17 Time-Series-Statistics

時系列データ(time-series-dataset) を対象とした解析 package

  • diff ((d time-series-dataset) &key (lag 1) (differences 1))
    • return: <time-series-dataset>
    • arguments:
      • d : <time-series-dataset>
      • lag : <integer>, degree of lag
      • differences : <integer> >= 1, number of difference
    • comments: 差分をとる。例えば時系列のトレンドが 1 次式であれば、differences 1 でトレンドを除去できる。
  • ts-ratio ((d time-series-dataset) &key (lag 1))
    • return: <time-series-dataset>
    • arguments:
      • d : <time-series-dataset>
      • lag : <integer>, degree of lag
    • comments: lag で指定された幅を周期とみなし、同期比をとる。
  • ts-log ((d time-series-dataset) &key (logit-transform nil))
    • return: <time-series-dataset>
    • arguments:
      • d : <time-series-dataset>
      • logit-transform : t | nil, logit transformation is effective for (0, 1) values ts data
    • comments logit-transform は、0 から 1 の値をとる時系列データを定常化するのに有効。
  • ts-min, ts-max, ts-mean, ts-median
    • argument: <time-series-dataset>
  • ts-covariance, ts-correlation ((d time-series-dataset) &key (k 0))
    • return: <matrix>, auto-covariance or auto-correlation matrix with lag k
    • arguments:
      • d : <time-series-dataset>
      • k : <positive integer>, degree of lag
  • acf ((d time-series-dataset) &key (type :correlation) (plot nil) (print t) max-k)
    • return: nil | <list>
    • arguments:
      • d : <time-series-dataset>
      • type : :covariance | :correlation
      • max-k : <positive integer>
      • plot : nil | t, when plot is t, result will be plotted by R.
      • print : nil | t, when print is t, result will be printed.
  • ccf (d1 d2 &key (type :correlation) (plot t) (print nil) max-k)
    • return: nil | <list>
    • arguments:
      • d1, d2 : <time-series-dataset>, one dimensional
      • type : :covariance | :correlation
      • max-k : <positive integer>
      • plot : nil | t, when plot is t, result picture will be plotted by R.
      • print : nil | t, when print is t, result will be printed.
  • ma ((d time-series-dataset) &key (k 5) weight)
    • return: <time-series-dataset>
    • arguments:
      • d : <time-series-dataset>, one dimensional
      • k : <positive integer>, range of calculation for average
      • weight : nil | <list>, when weight is nil, it will be all same weight.
  • periodgram ((d time-series-dataset) &key (print t) (plot nil) (log t) (smoothing :raw) step)
    • return: nil | <list>
    • arguments:
      • d : <time-series-dataset>
      • plot : nil | t, when plot is t, result picture will be plotted by R.
      • print : nil | t, when print is t, result will be printed.
      • log : nil | t, when log is t, the value of P(f) will be logarized.
      • smoothing : :raw | :mean | :hanning | :hamming, the way of smoothing
      • step : nil | <positive integer>, parameter for smoothing :mean
    • comments: 高速フーリエ変換のアルゴリズムが古く、その入力を 2n の長さの seq にしなければならないことから、周期 m / 2n (m,n : 自然数)の周波数成分の強度しか求められない。
  • sample usage
     TS-STAT(90): (setq ukgas (time-series-data (read-data-from-file "sample/UKgas.sexp") :range '(1) :time-label 0)
                        useco (time-series-data (read-data-from-file "sample/USeconomic.sexp")))
    
     TS-STAT(91): (acf useco)
     log(M1)
     log(M1) log(GNP) rs rl
     1.000 (0.000) 0.573 (0.000) 0.090 (0.000) 0.167 (0.000)
     0.949 (1.000) 0.540 (-1.000) 0.113 (-1.000) 0.154 (-1.000)
     0.884 (2.000) 0.503 (-2.000) 0.123 (-2.000) 0.141 (-2.000)
     0.807 (3.000) 0.463 (-3.000) 0.132 (-3.000) 0.128 (-3.000)
     0.725 (4.000) 0.422 (-4.000) 0.139 (-4.000) 0.117 (-4.000)
     ...
     TS-STAT(92): (ccf (sub-ts useco :range '(0)) (sub-ts useco :range '(1)))
     log(M1) : log(GNP)
     0.195 (-21.000)
     0.190 (-20.000)
     0.190 (-19.000)
     0.193 (-18.000)
     0.198 (-17.000)
     0.205 (-16.000)
     ...
     TS-STAT(95): (periodgram ukgas)
     Frequency | log P(f)
     0.00781250 | 14.38906769
     0.01562500 | 13.00093289
     0.02343750 | 12.34768838
     0.03125000 | 11.73668589
     0.03906250 | 11.20979558
     0.04687500 | 10.62278452
     ...
    

2.18 Time-Series-State-Space-Model

状態空間モデル(時系列モデルを抽象化したもの)の package, これを用いて色々な時系列モデルを表現する。

  • Class
    • state-space-model
      • 状態空間モデル
      • accessors:
        • ts-data : 観測値時系列
    • gaussian-stsp-model
      • ガウス型状態空間モデル
      • parent: state-space-model
    • trend-model
      • parent: gaussian-stsp-model
      • accessors:
        • diff-k : Trend モデルの次数
        • tau2 : Trend モデルにおけるシステムモデルの分散
        • aic : モデルの赤池情報量基準 AIC
    • seasonal-model
      • parent: gaussian-stsp-model
      • accessors
        • s-deg : Seasonal モデルの次数
        • s-freq : Seasonal モデルの周期(通常は時系列データの周期と同じ)
        • tau2 : システムモデルの分散
    • seasonal-adjustment-model
      標準的季節調整モデル( トレンド成分 + 季節成分 )
      • parent: gaussian-stsp-model
      • accessors
        • trend-model : トレンド成分を表す Trend モデル
        • seasonal-model : 季節成分を表す Seasonal モデル
  • trend ((d time-series-dataset) &key (k 1) (t2 0d0) (opt-t2 nil) (delta 0.1d0) (search-width 10))
    • return: <trend-model>
    • arguments:
      • d : <time-series-dataset>
      • k : <positive-integer>
      • t2 : <positive-number>
      • opt-t2 : nil | t
      • delta : <positive-number>
      • search-width : <positive-integer>
    • comments:
      • モデルの次数 k は一般的には 1 か 2 で十分だと言われている。k = 1 なら局 所的にはトレンドは一定、k = 2 なら局所的にはトレンドは直線的に変化する 時系列データに適している。
      • opt-t2 が t なら delta, search-width に従って t2 の値を自動推定する。 具体的には t2 で指定された値を中心に、正負方向に (* delta search-width) の範囲において delta 刻みで t2 の値を動かし、model の aic が一番小さか った t2 を採用する。
  • seasonal-adj ((d time-series-dataset) &key (tr-k 1) (tr-t2 0d0) (s-deg 1) s-freq (s-t2 0d0) (s2 1d0))
    • return: <seasonal-adjustment-model>
    • arguments:
      • d : <time-series-dataset>
      • tr-k : <positive-integer>, トレンド成分の次数
      • tr-t2 : <positive-number>, トレンド成分の分散
      • s-deg : <positive-integer>, 季節成分の次数
      • s-freq : <positive-integer>, 周期, 指定しない場合は入力時系列データの周期が適用される
      • s-t2 : <positive-number>, システムモデルの分散
      • s2 : <positive-number>, 観測モデルの分散
    • comments:
      • 与えられた時系列データ(1次元)をトレンド、季節成分に分解したモデルを構築する。
      • 季節成分の次数は、季節成分に顕著な傾向的変化が見られない限り、1 次のモデルを使用する。
      • 周期は 2 以上でなければならない。
  • predict ((model gaussian-stsp-model) &key (n-ahead 0))
    • return: (values <time-series-dataset> <time-series-dataset>)
      • first value is a prediction by model, second is a standard error of the model.
    • arguments:
      • n-ahead : <non-negative-integer>
    • comments:
      • model が trend-model のとき、n-ahead で指定した観測時系列データより先の値すなわち予測値については、 観測値の最後における trend が保たれる。
  • sample usage
     TS-STSP(123): (defparameter tokyo
                      (time-series-data
                       (read-data-from-file "sample/tokyo-temperature.sexp")))
     TOKYO
    
     TS-STSP(7): (trend tokyo :k 2 :opt-t^2 t)
     #<TREND-MODEL>
     K:   2
     T^2: 0.1
     AIC: 2395.073754930766
    
     TS-STSP(8): (predict * :n-ahead 10)
     #<TIME-SERIES-DATASET>
     DIMENSIONS: trend
     TYPES:      NUMERIC
     FREQUENCY:  1
     START:      (1 1)
     END:        (458 1)
     POINTS:     458
     #<TIME-SERIES-DATASET>
     DIMENSIONS: standard error
     TYPES:      NUMERIC
     FREQUENCY:  1
     START:      (1 1)
     END:        (458 1)
     POINTS:     458
    

2.19 Time-Series-Auto-Regression

時系列解析における自己回帰モデルの package

  • Class
    • ar-model
      • parent: gaussian-stsp-model
      • accessors:
        • ar-coefficients : AR パラメータ
        • sigma2 : AR model の分散推定値
        • aic : モデルの赤池情報量基準 AIC
        • ar-method : AR パラメータの推定方式
  • ar ((d time-series-dataset) &key order-max (method :burg) (aic t) (demean t))
    • return: <ar-model>
    • arguments:
      • d : <time-series-dataset>
      • order-max : <positive integer>
      • method : :yule-walker | :burg
      • aic : nil | t
      • demean : nil | t
    • comments: aic が t なら order-max までの次数のモデルを推定し、AIC が一番小さなモデルを選択する。 aic が nil なら order-max で指定された次数のモデルを推定し、選択する。
  • predict ((model ar-model) &key (n-ahead 0))
    • return: (values <time-series-dataset> <time-series-dataset>)
      • first value is a prediction by model, second is a standard error of the model.
    • arguments:
      • model : <ar-model>
      • n-ahead : <non-negative integer>
  • ar-prediction ((d time-series-dataset) &key (method :yule-walker) (aic t) order-max n-learning (n-ahead 0) (demean t) target-col)
    • return: (values <time-series-dataset> <ar-model> <time-series-dataset>)
    • arguments:
      • d : <time-series-dataset>
      • order-max : <positive integer>
      • method : :yule-walker | :burg
      • aic : nil | t
      • demean : nil | t
      • n-ahead : <non-negative integer>
      • n-learning : nil | <positive integer>, number of points for learning
      • target-col : nil | <string>, name of target parameter
  • parcor-filtering ((ts time-series-dataset) &key (divide-length 15) (parcor-order 1) (n-ahead 10) ppm-fname)
    • return: <time-series-dataset>, values for parcor picture
    • arguments:
      • ts : <time-series-dataset>
      • divide-length : <positive integer>
      • parcor-order : <positive integer> below divide-length
      • n-ahead : <non-negative integer>, number for ar-prediction on parcor picture
      • ppm-fname : <string> | <pathname>, name for parcor picture
    • comments: 論文 http://www.neurosci.aist.go.jp/~kurita/lecture/statimage.pdf の 3.2.1 節を参考にした。時系列を divide-length で区切って各区間を一つの動画と捉え parcor 画像を各区間ごとに作成する。
  • sample usage
     TS-AR(128): (defparameter ukgas 
                    (time-series-data
                     (read-data-from-file "sample/UKgas.sexp")
                     :range '(1) :time-label 0
                     :start 1960 :frequency 4))
    
     TS-AR(14): (setq model (ar ukgas))
     #<AR-MODEL>
     method: BURG
     Coefficients:
     a1 0.17438913366790465
     a2 -0.20966263354643136
     a3 0.459202505071864
     a4 1.0144694385486095
     a5 0.2871426375860843
     a6 -0.09273505423571009
     a7 -0.13087574744684466
     a8 -0.34467398543738703
     a9 -0.1765456124104221
     Order selected 9, sigma^2 estimated as 1231.505368951319
    
     TS-AR(15): (predict model :n-ahead 12)
     #<TIME-SERIES-DATASET>
     DIMENSIONS: UKgas
     TYPES:      NUMERIC
     FREQUENCY:  4
     START:      (1962 2)
     END:        (1989 4)
     POINTS:     111
     TIME-LABEL: year season
     #<TIME-SERIES-DATASET>
     DIMENSIONS: standard error
     TYPES:      NUMERIC
     FREQUENCY:  4
     START:      (1962 2)
     END:        (1989 4)
     POINTS:     111
     TIME-LABEL: year season
    
     TS-AR(16): (ar-prediction ukgas :method :burg :n-learning 80 :n-ahead 12)
     #<TIME-SERIES-DATASET>
     DIMENSIONS: UKgas
     TYPES:      NUMERIC
     FREQUENCY:  4
     START:      (1962 2)
     END:        (1983 1)
     POINTS:     84
     TIME-LABEL: year season
     #<AR-MODEL>
     method: BURG
     Coefficients:
     a1 0.03855018085036885
     a2 -0.16131564249720193
     a3 0.43498481388230215
     a4 1.050917089787715
     a5 0.5797305440261313
     a6 -0.13363258905263287
     a7 -0.16163235104434967
     a8 -0.3748978324320104
     a9 -0.3151508389321235
     Order selected 9, sigma^2 estimated as 741.5626361893945
     #<TIME-SERIES-DATASET>
     DIMENSIONS: standard error
     TYPES:      NUMERIC
     FREQUENCY:  4
     START:      (1962 2)
     END:        (1983 1)
     POINTS:     84
     TIME-LABEL: year season
    
     TS-AR(6): (setq traffic (time-series-data
                              (read-data-from-file "sample/mawi-traffic/pointF-20090330-0402.sexp")
                              :except '(0) :time-label 0))
     #<TIME-SERIES-DATASET>
     DIMENSIONS: [   32-   63] | [   64-  127] | [  128-  255] | [  256-  511] | [  512- 1023] | ...
     TYPES:      NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | ...
     FREQUENCY:  1
     START:      (1 1)
     END:        (385 1)
     POINTS:     385
     TIME-LABEL: Time
    
     TS-AR(7): (parcor-filtering traffic :ppm-fname "traffic.ppm")
     #<TIME-SERIES-DATASET>
     DIMENSIONS: [   32-   63] | [   64-  127] | [  128-  255] | [  256-  511] | [  512- 1023] | ...
     TYPES:      NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | NUMERIC | ...
     FREQUENCY:  1
     START:      (1 1)
     END:        (35 1)
     POINTS:     35
     TIME-LABEL: Time
    
    

2.20 Exponential-Smoothing (HoltWinters)

時系列解析における指数平滑化法の package

  • Class
    • holtwinters-model
      • accessors:
        • exp-type : 指数平滑化法のタイプ :single, :double or :triple
        • 3-params : alpha, beta, gamma の値
        • err-info : 誤差評価関数およびモデルのその値
        • seasonal : 季節成分の適用方法 :additive or :multiplicative
  • holtwinters ((d time-series-dataset) &key alpha beta gamma (err-measure 'mse)
    (optim-step 0.1d0) (seasonal :additive))
    • return: <holtwinters-model>
    • arguments:
      • alpha : nil | 0 <= <double-float> <= 1
      • beta : nil | 0 <= <double-float> <= 1
      • gamma : nil | 0 <= <double-float> <= 1
      • err-measure : 'mse | 'mape | 'rae | 're | 'rr
      • optim-step : 0 <= <double-float> <= 1, step for optimizing alpha, beta and gamma
      • seasonal : :additive | :multiplicative
    • comments: alpha, beta, gamma を指定しなければ、alpha, beta, gamma の値を 0 から optim-step ずつ増やして いき、一番 err-measure 値が小さかった alpha, beta, gamma を選ぶ。 よって optim-step を例えば 0.001d0 などとすると非常に時間がかかる。
  • predict ((model holtwinters-model) &key (n-ahead 0))
    • return: <time-series-dataset>
    • arguments:
      • model : <holtwinters-model>
      • n-ahead : <non-negative integer>
  • holtwinters-prediction
    • return: (values <time-series-dataset> <holtwinters-model>)
    • arguments:
      • d : <time-series-dataset>
      • alpha : nil | 0 <= <double-float> <= 1
      • beta : nil | 0 <= <double-float> <= 1
      • gamma : nil | 0 <= <double-float> <= 1
      • err-measure : 'mse | 'mape | 'rae | 're | 'rr
      • optim-step : 0 <= <double-float> <= 1
      • seasonal : :additive | :multiplicative
      • n-ahead : <non-negative integer>
      • n-learning : nil | <positive integer>, number of points for learning
      • target-col : nil | <string>, name of target parameter
  • sample usage
     EXPL-SMTHING(106): (setq ukgas (time-series-data (read-data-from-file "sample/UKgas.sexp")
                                                      :range '(1) :time-label 0
                                                      :frequency 4))
     #<TIME-SERIES-DATASET>
     DIMENSIONS: UKgas
     TYPES:      NUMERIC
     FREQUENCY:  4
     START:      (1 1)
     END:        (27 4)
     POINTS:     108
     TIME-LABEL: year season
    
     EXPL-SMTHING(108): (setq model (holtwinters ukgas :seasonal :multiplicative))
     #<HOLTWINTERS-MODEL>
     alpha: 0.1, beta: 0.2, gamma: 0.7999999999999999
     seasonal: MULTIPLICATIVE
     error: 1132.6785446257877 ( MSE )
    
     EXPL-SMTHING(109): (predict model :n-ahead 12)
     #<TIME-SERIES-DATASET>
     DIMENSIONS: UKgas
     TYPES:      NUMERIC
     FREQUENCY:  4
     START:      (1 2)
     END:        (30 4)
     POINTS:     119
    
     EXPL-SMTHING(110): (holtwinters-prediction ukgas :seasonal :multiplicative
                                                :n-learning 80
                                                :n-ahead 12)
     #<TIME-SERIES-DATASET>
     DIMENSIONS: UKgas
     TYPES:      NUMERIC
     FREQUENCY:  4
     START:      (1 2)
     END:        (30 4)
     POINTS:     119
     #<HOLTWINTERS-MODEL>
     alpha: 0.1, beta: 0.2, gamma: 0.7999999999999999
     seasonal: MULTIPLICATIVE
     error: 1132.6785446257877 ( MSE )
    
    

2.21 Notes

  • OPTICS
    近傍探索アルゴリズムが naive なので遅い。M-tree という方法で早くなる。
  • SVM
    • ここでは訓練サンプルは二種類( positive-data, negative-data )であり推定結果も二値だが、VMS では二種類以上の訓練サンプルでも推定ができる。
    • 判別分析が未実装
    • 現状ハードマージンのみ、ソフトマージンもあれば有効。
  • SOM
    • 現状 do-som-by-filename は、分析結果の画像ファイルと map データを指定されたディレクトリ以下に出力するが、map データを出力する部分とそれを画像に変換する部分とに分ける予定。
  • cluster-validation
    • 現状 k-means の結果にしか適用できないが、OPTICS の結果にも適用できるようにする予定。
    • Silhouette Index の計算に時間がかかる。dunn および davies-bouldin も metrics によっては時間がかかる。
    • :intercluster を :average-to-centroids にしたときの値が VMS と違う。
    • 以下の指標が未実装(VMS にはある)
      • Ratkowsky and Lance
      • Scott and Symons
      • Marriot
      • C Index
      • Likelihood
  • handling missing value
    • IEEE 754 に従う処理系を前提 (e.g. ACL, sbcl, lispworks 現状 ACL のみ対応)
    • 欠損値の種類
      • Not Available:*na* ( :NA )
        • Not a Number (numeric):*nan* (処理系で定義される Not a Number)
        • Not a Number (category):*c-nan* ( 0 )
    • 欠損値のあるデータも読み込める。欠損値を含むデータの例としては、sample/original-airquality.sexp
    • 欠損値補間(ゼロ・平均・中央・3次スプラインなど)、外れ値検定(標準偏差、平均偏差、スミルノフ・グラッブズ検定など)がある。
    • TODO: 計算結果として無限大・欠損(divided by zero など)が生じるような場合の処理
  • read-data
    • TODO: カテゴリー型データの読み込み
      • 取り得るデータ値に 1 以上の整数で indexing (欠損値は*c-nan*の通り 0 で表現される)
      • 必要であれば、-1 以下の整数を用いて、対応する正の整数が意味するデータ値の補集合を意味するようにする。
      • 現状は、データを read したものをそのまま読み込んでいる。
  • Precision
    基本的には double-float を前提としているが、single-float で SSE を使うと 2 倍速く処理できるので、二つのバージョンを作成できるとよい。
  • 追加予定エンジン
    • Time Series Analysis
      • gaussian-state-space-model
        • 季節調整モデル
        • 時変係数ARモデル
      • non-gaussian-state-space-model
    • Bayesian Network
  • 追加候補エンジン
    • Non-Linear Regression Analysis
    • Feature Selection
    • Neural Network
    • kernel P.C.A. : 非線形な主成分分析
    • Independent Component Analysis : 独立主成分分析
    • BIRCH : データをある程度量子化した partitioning method clustering

3 Statistics

3.1 Requirements

The package does not depend on any libraries (yet). Any ANSI-compliant Common Lisp should be enough. However, to load it easily, you need the ASDF package (http://www.cliki.net/asdf).

3.2 Usage

  • One-valued data
    There is a range of functions that operate on a sequence of data.
    • mean (seq)
      Returns the mean of SEQ.
    • median (seq)
      Returns the median of SEQ. (Variant: median-on-sorted (sorted-seq))
    • discrete-quantile (seq cuts)
      Returns the quantile(s) of SEQ at the given cut point(s). CUTS can be a single value or a list. (Variant: discrete-quantile-on-sorted (sorted-seq cuts))
    • five-number-summary (seq)
      Returns the "five number summary" of SEQ, ie. the discrete quantiles at the cut points 0, 1/4, 1/2, 3/4 and 1. (Variant: five-number-summary-on-sorted (sorted-seq))
    • range (seq)
      Returns the difference of the maximal and minimal element of SEQ.
    • interquartile-range (seq)
      Returns the interquartile range of SEQ, ie. the difference of the discrete quantiles at 3/4 and 1/4. (Variant: interquartile-range-on-sorted (sorted-seq))
    • mean-deviation (seq)
      Returns the mean deviation of SEQ.
    • variance (seq)
      Returns the variance of SEQ.
    • standard-deviation (seq &key populationp)
      Returns the standard deviation of SEQ. If populationp is true, the returned value is the population standard deviation. Otherwise, it is the sample standard deviation.
  • Two-valued data
    These functions operate on two sequences.
    • covariance (seq1 seq2)
      Returns the covariance of SEQ1 and SEQ2.
    • linear-regression (seq1 seq2)
      Fits a line y = A + Bx on the data points from SEQ1 x SEQ2. Returns (A B).
    • correlation-coefficient (seq1 seq2)
      Returns the correlation coefficient of SEQ1 and SEQ2, ie. covariance / (standard-deviation1 * standard-deviation2).
    • spearman-rank-correlation (seq1 seq2)
      Returns the Spearman rank correlation, ie. the coefficient based on just the relative size of the given values.
    • kendall-rank-correlation (seq1 seq2)
      Returns the Kendall "tau" rank correlation coefficient.
  • Distributions
    Distributions are CLOS objects, and they are created by the constructor of the same name. The objects support the methods CDF (cumulative distribution function), DENSITY (MASS for discrete distributions), QUANTILE, RAND (gives a random number according to the given distribution), RAND-N (convenience function that gives n random numbers), MEAN and VARIANCE (giving the distribution's mean and variance, respectively). These take the distribution as their first parameter.

    Most distributions can also be created with an estimator constructor. The estimator function has the form <distribution>-ESTIMATE, unless noted.

    The following distributions are supported:

    • beta-distribution
      • Parameters: shape1 shape2
    • binomial-distribution
      • Parameters: size, probability
    • cauchy-distribution
      • Parameters: location, scale
    • chi-square-distribution
      • Parameters: degree
      • Estimators: [none]
    • exponential-distribution
      • Parameters: hazard (or scale)
    • f-distribution
      • Parameters: degree1 degree2
      • Estimators: [none]
    • gamma-distribution
      • Parameters: scale, shape
      • (Variant: erlang-distribution [shape is an integer])
    • geometric-distribution
      • Parameters: probability
      • (Supported on k = 1, 2, … (the # of trials until a success, inclusive))
    • hypergeometric-distribution
      • Parameters: elements, successes, samples
      • Estimators: hypergeometric-distribution-estimate-successes-unbiased, hypergeometric-distribution-estimate-successes-maximum-likelihood, hypergeometric-distribution-estimate-elements
    • logistic-distribution
      • Parameters: location, scale
    • log-normal-distribution
      • Parameters: expected-value, deviation
      • Estimators: log-normal-distribution-estimate-unbiased, log-normal-distribution-estimate-maximum-likelihood
    • negative-binomial-distribution
      • Parameters: successes, probability, failuresp
      • Estimators: negative-binomial-distribution-estimate-unbiased, negative-binomial-distribution-estimate-maximum-likelihood
      • When failuresp is NIL, the distribution is supported on k = s, s+1, … (the # of trials until a given number of successes, inclusive))
      • When failuresp is T (the default), it is supported on k = 0, 1, … (the # of failures until a given number of successes, inclusive)
      • Estimators also have the failuresp parameter
      • (Variant: geometric-distribution [successes = 1, failuresp = nil])
    • normal-distribution
      • Parameters: expected-value, deviation
      • Estimators: normal-distribution-estimate-unbiased, normal-distribution-estimate-maximum-likelihood
      • (Variant: standard-normal-distribution)
    • poisson-distribution
      • Parameters: rate
    • t-distribution
      • Parameters: degree
      • Estimators: [none]
    • uniform-distribution
      • Parameters: from, to
      • Estimators: uniform-distribution-estimate-moments, uniform-distribution-estimate-maximum-likelihood
      • (Variant: standard-uniform-distribution)
    • weibull-distribution
      • Parameters: scale, shape
  • Distribution tests
    • normal-dist-test
      • Input: frequation sequence, infimum of the first class, class width, precision
      • Output( 3 values of property-list )
        • result (:TOTAL 全度数 :MEAN 平均 :VARIANCE 分散 :SD 標準偏差)
        • table (:MID 各階級の中心値 :FREQ 各級の度数 :Z 級限界の標準化得点 :CDF 累積確率 :EXPECTATION 期待値)
        • result2 (:CHI-SQ カイ二乗統計量 :D.F. 自由度 :P-VALUE P-値)
    • poisson-dist-test
      • Input: sequence of frequency
      • Output( 3 values of p-list )
        • result (:N 全度数 :MEAN 平均)
        • table (:C-ID 仮の階級値 :FREQ 度数 :P 確率 :E 期待値)
        • result2 (:CHI-SQ カイ二乗統計量 :D.F. 自由度 :P-VALUE P-値)
    • binom-dist-test
      • Input: sequence of frequency, sequence of class-value, size of Bernoulli trials
      • Output( 3 values of p-list )
        • result (:D-SIZE サンプルサイズ :PROBABILITY 母比率)
        • table (:FREQ 度数分布 :P 確率 :E 期待値)
        • result2 (:CHI-SQ カイ二乗統計量 :D.F. 自由度 :P-VALUE P-値)
  • Outlier verification
    外れ値検定
    • smirnov-grubbs (seq alpha &key (type :max) (recursive nil))
      Smirnov-Grubbs の棄却検定
  • Sample listener log
    • Loading without ASDF
      (assuming you are in the directory where the library resides)
      CL-USER> (load "package")
      T
      CL-USER> (load "utilities")
      T
      CL-USER> (load "math")
      T
      CL-USER> (load "statistics")
      T
      CL-USER> (load "distribution-test")
      T
      CL-USER> (in-package :statistics)
      #<PACKAGE "STATISTICS">
      STAT> 
      
    • Loading with ASDF
      (assuming that the path to statistics.asd is in ASDF:*CENTRAL-REGISTRY*)
      CL-USER> (asdf:operate 'asdf:load-op 'statistics)
      ; loading system definition from ~/.sbcl/systems/statistics.asd
      ; into #<PACKAGE "ASDF0">
      ; registering #<SYSTEM :STATISTICS {B65C489}> as STATISTICS
      NIL
      CL-USER> (in-package :statistics)
      #<PACKAGE "STATISTICS">
      STAT> 
      
    • Simple usage (examples taken from "Lisp-Statによる統計解析入門" by 垂水共之)
      • One-valued data
        STAT> (defparameter height '(148 160 159 153 151 140 156 137 149 160 151 157 157 144))
        HEIGHT
        STAT> (mean height)
        1061/7
        STAT> (+ (mean height) 0.0d0)
        151.57142857142858d0
        STAT> (median height)
        152
        STAT> (five-number-summary height)
        (137 297/2 152 157 160)
        STAT> (mapcar (lambda (x) (discrete-quantile height x)) '(0 1/4 1/2 3/4 1))
        (137 297/2 152 157 160)
        STAT> (interquartile-range height)
        17/2
        STAT> (+ (mean-deviation height) 0.0d0)
        5.857142857142857d0
        STAT> (+ (variance height) 0.0d0)
        50.10204081632653d0
        STAT> (standard-deviation height)
        7.345477789500419d0
        STAT> 
        
      • Two-valued data
        STAT> (defparameter weight '(41 49 45 43 42 29 49 31 47 47 42 39 48 36))
        WEIGHT
        STAT> (linear-regression height weight)
        (-70.15050916496945d0 0.7399185336048879d0)
        STAT> (+ (covariance height weight) 0.0d0)
        39.92307692307692d0
        STAT> (correlation-coefficient height weight)
        0.851211920646571d0
        STAT> (defparameter baseball-teams '((3 2 1 5 4 6) (2 6 3 5 1 4))
                "Six baseball teams are ranked by two people in order of liking.")
        BASEBALL-TEAMS
        STAT> (+ (apply #'spearman-rank-correlation baseball-teams) 0.0d0)
        0.02857142857142857d0
        STAT> (+ (apply #'kendall-rank-correlation baseball-teams) 0.0d0)
        -0.06666666666666667d0
        STAT> 
        
      • Distributions
        STAT> (quantile (standard-normal-distribution) 0.025d0)
        -1.9599639551896222d0
        STAT> (density (standard-uniform-distribution) 1.5d0)
        0
        STAT> (cdf (standard-uniform-distribution) 0.3d0)
        0.3d0
        STAT> (defparameter normal-random (rand-n (standard-normal-distribution) 1000))
        NORMAL-RANDOM
        STAT> (five-number-summary normal-random)
        (-3.048454339464769d0 -0.6562483981626692d0 -0.0378855048937908d0
         0.6292440569288786d0 3.3461196116924925d0)
        STAT> (mean normal-random)
        -0.003980893528421081d0
        STAT> (standard-deviation normal-random)
        0.9586638291006542d0
        STAT> (quantile (t-distribution 5) 0.05d0)
        -2.0150483733330242d0
        STAT> (density (t-distribution 10) 1.0d0)
        0.23036198922913856d0
        STAT> (defparameter chi-random (rand-n (chi-square-distribution 10) 1000))
        CHI-RANDOM
        STAT> (mean chi-random)
        10.035727383909936d0
        STAT> (standard-deviation chi-random)
        4.540307733714504d0
        STAT> 
        
      • Distribution tests (examples taken from http://aoki2.si.gunma-u.ac.jp/R/)
        STAT(6): (normal-dist-test '(4 19 86 177 105 33 2) 40 5 0.1)
        (:TOTAL 426 :MEAN 57.931225 :VARIANCE 26.352928 :SD 5.13351)
        (:MID (37.45 42.45 47.45 52.45 57.45 62.45 67.45 72.45 77.45) :FREQ
        (0 4 19 86 177 105 33 2 0) :Z
        (-3.5027153 -2.5287228 -1.5547304 -0.58073795 0.3932545 1.3672462
         2.3412387 3.315231 4.2892237)
        :CDF
        (2.3027066827641107d-4 0.005493650023016494d0 0.0542812231219722d0
         0.2207033969433026d0 0.3722256949242654d0 0.2612916822967053d0
         0.07616414571442975d0 0.009152099332533692d0 4.578369754981715d-4)
        :EXPECTATION
        (0.09809530468575112d0 2.4383902144907776d0 23.123801049960157d0
         94.01964709784691d0 158.56814603773705d0 111.31025665839645d0
         32.44592607434708d0 4.093832867221574d0 0.19503855156222105d0))
        (:CHI-SQ 6.000187256825313d0 :D.F. 4 :P-VALUE 0.19913428945535006d0)
        
        STAT(10): (poisson-dist-test '(27 61 77 71 54 35 20 11 6 2 1))
        (:N 365 :MEAN 1092/365)
        (:C-ID (0 1 2 3 4 5 6 7 8 9 ...) :FREQ (27 61 77 71 54 35 20 11 6 2 ...)
         :P
         (0.050197963 0.1501813 0.22465476 0.22403927 0.1675691 0.100266
          0.04999565 0.021368004 0.0079910485 0.002656385 ...)
         :E
         (18.322256 54.816174 81.998985 81.77434 61.162724 36.59709 18.248411
          7.7993217 2.9167328 0.96958053 ...))
        (:CHI-SQ 14.143778 :D.F. 8 :P-VALUE 0.07809402061210624d0)
        
        STAT(16): (binom-dist-test '(2 14 20 34 22 8) '(0 1 2 3 4 5) 5)
                                   (binom-dist-test '(2 14 20 34 22 8) '(0 1 2 3 4 5) 5)
        (:SIZE 6 :PROBABILITY 0.568)
        (:FREQ (2 14 20 34 22 8) :P
         (0.015045918 0.098912984 0.26010454 0.3419893 0.22482634 0.059121) :E
         (1.5045917 9.891298 26.010454 34.198933 22.482634 5.9121003))
        (:CHI-SQ 4.007576 :D.F. 4 :P-VALUE 0.4049815220790788d0)
        
      • Outlier verification
        STAT(6): (defparameter *sample*
                     '(133 134 134 134 135 135 139 140 140 140 141 142 142 144 144 147 147 149 150 164))
        
        STAT(7): (smirnov-grubbs *sample* 0.05 :type :max)
        Data: MAX = 164.000
        t= 3.005, p-value = 2.557, df = 18
        
        STAT(8): (smirnov-grubbs *sample* 0.05 :type :min)
        Data: MIN = 133.000
        t= 1.172, p-value = 2.557, df = 18
        
        STAT(11): (smirnov-grubbs *sample* 0.05 :type :max :recursive t)
        (133 134 134 134 135 135 139 140 140 140 ...)
        
        STAT(12): (set-difference *sample* *)
        (164)
        

3.3 Notes

  • Numbers are not converted to (double) floats, for better accuracy with whole number data. This should be OK, since double data will generate double results (the number type is preserved).
  • Places marked with TODO are not optimal or not finished (see the TODO file for more details).

4 Test package

テストスクリプト package として lisp-unit を採用。 各エンジンのテストスクリプトは基本的にこれを用いることとする。

4.1 How to use

  • 1. Read the documentation in http://www.cs.northwestern.edu/academics/courses/325/readings/lisp-unit.html
  • 2. Make a file of DEFINE-TEST's. See exercise-tests.lisp for many examples. If you want, start your test file with (REMOVE-TESTS) to clear any previously defined tests.
  • 2. (use-package :lisp-unit)
  • 3. Load your code file and your file of tests.
  • 4. Test your code with (RUN-TESTS test-name1 test-name2 …) – no quotes! – or simply (RUN-TESTS) to run all defined tests.
  • A summary of how many tests passed and failed will be printed, with details on the failures.
  • Note: Nothing is compiled until RUN-TESTS is expanded. Redefining functions or even macros does not require reloading any tests.
  • 必要動作チェック OS
    linux32, linux64, win32, sparc/solaris32

5 Licensing

The MSI Software License Agreement governs the use of CL Machine-Learning and is available for review by clicking http://cl-www.msi.co.jp/solutions/knowledge/lisp-world/products/LICENSE.html.

5.1 Commercial Licenses

For pricing, contact mailto:clml-info@msi.co.jp.

  • CL Machine-Learning Standard
    Including all machine learning packages. One year Technical Support and version ups are included.
  • CL Machine-Learning with Intel MKL
    Including all machine learning packages and intel MKL based matrix libraries. One year Technical Support and version ups are included.
  • CL Machine-Learning with fork-future
    Including all machine learning packages and fork-future. One year Technical Support and version ups are included.
  • CL Machine-Learning with Source Codes
    Including all machine learning packages and source codes. One year Technical Support and version ups are included.

5.2 Free License

  • CL Machine-Learning Free Edition
    You can download and use compiled fasl images freely for any purpose. See Download section of this page. Source codes or technical supports are not included in Free Edition.

6 Supported CL implementations

We're supporting only ANSI Common Lisp. If you need support for CL dialect such as Allegro's mlisp, contact mailto:clml-info@msi.co.jp.

  • Allegro CL 8.1 Enterprise 32 Edition (ANSI mode, any platforms)
  • Allegro CL 8.1 Enterprise 64 Edition (ANSI mode, any platforms)
  • lispworks-6-0-0-amd64-linux
  • lispworks-6-0-0-x86-linux
  • sbcl-1.0.24-x86-64-linux

7 Download

Author: Salvi Péter, Naganuma Shigeta, Tada Masashi, Abe Yusuke, Jianshi Huang, Fujii Ryo, Abe Seika, Kuroda Hisao <kuroda@msi.co.jp>

Date: 2010-01-13 16:20:56 JST

HTML generated by org-mode 6.33f in emacs 22