Python中的随机森林

普吉(Pulkit Jha)

我已经在python中运行了一个随机森林模型,并且能够看到分类表。但是我希望从python中的数据准备,模型运行,模型验证和准确性检查的代码开始,涵盖所有方面的全面代码吗?我的模型中出现了很多误报。任何改进的帮助也将非常有帮助。

鲁西克·图马尔(Rushik Thumar)

请参阅,

import urllib2
import numpy
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
import random
from math import sqrt
import matplotlib.pyplot as plot


# Define function confusion matrix
def confusionMatrix(predicted, actual, threshold):
    if len(predicted) != len(actual): return -1
    tp = 0.0
    fp = 0.0
    tn = 0.0
    fn = 0.0
    for i in range(len(actual)):
        if actual[i] > 0.5: #labels that are 1.0  (positive examples)
            if predicted[i] > threshold:
                tp += 1.0 #correctly predicted positive
            else:
                fn += 1.0 #incorrectly predicted negative
        else:              #labels that are 0.0 (negative examples)
            if predicted[i] < threshold:
                tn += 1.0 #correctly predicted negative
            else:
                fp += 1.0 #incorrectly predicted positive
    rtn = [tp, fn, fp, tn]
    return rtn



#Hyperlink for Python
target_url = ("https://archive.ics.uci.edu/ml/machine-learning-databases/pendigits/pendigits.tra")
data = urllib2.urlopen(target_url)

xList = []
labels = []
names = []
firstline = True

for line in data:
    #row strip by "," sign
    row = line.strip().split(",")
    # assign labels as last column
    labels.append(float(row[-1]))
    #remove label from row
    row.pop()
    #feature vector
    floatRow = [float(num) for num in row]
    #append on the xList
    xList.append(floatRow)


nrows = len(xList)
ncols = len(xList[0])

#Split Data for Test and Train
random.seed(1)
nSample = int(nrows * 0.30)
idxTest = random.sample(range(nrows),nSample)
idxTest.sort()
idxTrain = [idx for idx in range(nrows) if not(idx in idxTest)]

xTrain = [xList[r] for r in idxTrain]
xTest = [xList[r] for r in idxTest]
yTrain = [labels[r] for r in idxTrain]
yTest = [labels[r] for r in idxTest]



numTreesMax = 30

treeDepth = 12

nAttr = 4

modelList = []
indexList = []
predList = []
nTrainRows = len(yTrain)


for iTrees in range(numTreesMax):

        idxAttr = random.sample(range(ncols), nAttr)
        idxAttr.sort()
        indexList.append(idxAttr)

        idxRows = []
        for i in range(int(0.5 * nTrainRows)):
                idxRows.append(random.choice(range(len(xTrain))))
        idxRows.sort()

        xRFTrain = []
        yRFTrain = [] 

        for i in range(len(idxRows)):
                temp = [xTrain[idxRows[i]][j] for j in idxAttr]
                xRFTrain.append(temp)
                yRFTrain.append(yTrain[idxRows[i]])

        modelList.append(DecisionTreeClassifier(max_depth = treeDepth))

        modelList[-1].fit(xRFTrain,yRFTrain)

        xRFTest = []
        for xx in xTest:
                temp = [xx[i] for i in idxAttr]
                xRFTest.append(temp)

        latestOutSAmplePrediction = modelList[-1].predict(xRFTest)
        predList.append(list(latestOutSAmplePrediction))



classerror = []
allPredictions = []
for iModels in range(len(modelList)):
        prediction = []
        for iPred in range(len(xTest)):
                prediction.append(sum([predList[i][iPred] for i in range(iModels +1)])/(iModels +1))

        allPredictions.append(prediction)
        conMatTest = confusionMatrix(prediction,yTest,0.5)
        errors = 1.0 - ((conMatTest[0] + conMatTest[3])/(conMatTest[0]+conMatTest[1]+conMatTest[2]+conMatTest[3]))
        classerror.append(errors)





nModels = [i + 1 for i in range(len(modelList))]

plot.plot(nModels,classerror)
plot.axis('tight')
plot.xlabel('Number of Trees in Ensamble')
plot.ylabel('Class Error')
plot.ylim((0.0,max(classerror)))
plot.show()

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Python中的随机森林

来自分类Dev

scikit-learn / python中带有字符的随机森林

来自分类Dev

使用Python的面板数据随机森林

来自分类常见问题

什么是“随机森林”中的出库错误?

来自分类Dev

结合scikit学习中的随机森林模型

来自分类Dev

插入符号包中的“随机森林”错误

来自分类Dev

R中的多栅格随机森林

来自分类Dev

R中随机森林图的图例

来自分类Dev

随机森林模型中预测结果的差异

来自分类Dev

插入符号包中的“随机森林”错误

来自分类Dev

在 R 中打开 csv 文件随机森林

来自分类Dev

R内存错误中的随机森林

来自分类Dev

随机森林搜索参数中hyperopt的ValueError

来自分类Dev

在随机森林模型(Python,scikit-learn)中访问单个树的底层(tree_)对象

来自分类Dev

如何在Python scikit-learn中从随机森林中的每棵树输出回归预测?

来自分类Dev

对象中缺少值-R中的随机森林混淆矩阵

来自分类Dev

将python随机森林模型保存到文件

来自分类Dev

随机森林分类器Matlab v / s Python

来自分类Dev

随机森林分类器Matlab v / s Python

来自分类Dev

Python - 使用 scikit 学习随机森林关于值格式的错误

来自分类Dev

鼠标r包中执行随机森林时出错

来自分类Dev

调整Caret包中随机森林的两个参数

来自分类Dev

获取R中随机森林的准确性

来自分类Dev

如何为随机森林修复“ eval()中的错误”?

来自分类Dev

获得R中连续变量的随机森林预测精度

来自分类Dev

在插入符号中拟合随机森林模型后使用partialPlot

来自分类Dev

R中随机森林时间序列的变量重要性

来自分类Dev

提高sklearn中的随机森林回归器的性能

来自分类Dev

如何更改R中随机森林的分割条件?

Related 相关文章

热门标签

归档