Finding the corresponding sample fraction for a predicted response in classification trees Python 2.7
Question: I know how to fit a tree using `sklearn`. I also know how to use it for
prediction using either `predict` or `predict_proba`. However, for prediction
I want to get the (raw) sample fractions rather than the probability.

For example, in a fitted tree, two leaf nodes might both have probability of
0.2 for class A but one with 2/10 while the other with 400/2000. Now, if I use
this tree, I want to get something like [400,2000] or [2,10] rather than just
0.2.

`n_node_sample` and `value` attributes store such information in the fitted
tree object but I dont know how to extract the appropriate values from them in
prediction.

Thanks in advance.


Answer: You can use the tree's `tree.tree_.apply` method to find out which leaf the
point ends up in, and then use the `tree.tree_.value` array to check how many
samples of each class are in this leaf:

    
    
    import numpy as np
    from sklearn.datasets import load_iris
    from sklearn.tree import DecisionTreeClassifier
    
    iris = load_iris()
    tree = DecisionTreeClassifier(max_depth=2).fit(iris.data, iris.target)
    
    leaf = tree.tree_.apply(iris.data[50:51].astype(np.float32))
    print(leaf)
    # output [3]
    print(tree.tree_.value[leaf])
    # output [[[  0.  49.   5.]]]
    print(tree.predict_proba(iris.data[50:51]))
    # output [[ 0.          0.90740741  0.09259259]]
    

In the next version 0.17 `tree.tree_.apply` will be "public" as `tree.apply`
and will take care of the datatype conversion (to float32). See [the
docs](http://scikit-
learn.org/dev/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.apply).

