ランダムフォレスト(Random Forests)

v3.0.0

In [19]:
# -*- coding: utf-8 -*-
import cv2
import numpy as np

#Ipythonで表示用の設定
import matplotlib.pyplot as plt
%matplotlib inline

#RFなので大量のデータを使うべきだが、ここでは以下とする。
TrainData = np.array([[-1, -1], [-2, -3],[-1, -1.5], [1, 3], [2, 2], [3, 5], [5, -9],[5, -6],[5, -4]]).astype(np.float32)
response  = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3]).astype(np.int)

#学習データの表示
print "Training Data\nlabel: feature"
for i in range(9):
   print response[i],":",TrainData[i]

#学習器を生成
RF = cv2.ml.RTrees_create()

#パラメータ設定
#葉ノードに割り当てる最少サンプル数(全データの1%以下ぐらい?)
RF.setMinSampleCount(2)
#決定木の最大深さ
RF.setMaxDepth(5)

#学習フェーズ
RF.train(TrainData, cv2.ml.ROW_SAMPLE, response)

#推定対象生成
test = np.array([[3., -5.]]).astype(np.float32)

#推定フェーズ
(ret, res) = RF.predict(test) 

print "\nEstimate Result"
print test,"->",res

#ヘルプ
#print "\n",help(RF)
Training Data
label: feature
1 : [-1. -1.]
1 : [-2. -3.]
1 : [-1.  -1.5]
2 : [ 1.  3.]
2 : [ 2.  2.]
2 : [ 3.  5.]
3 : [ 5. -9.]
3 : [ 5. -6.]
3 : [ 5. -4.]

Estimate Result
[[ 3. -5.]] -> [[ 3.]]

inserted by FC2 system