标签: cross-validation

当random_state为None时,StratifiedShuffleSplit函数(scikit-learn)的结果不同

我正在执行交叉验证以便正确分类.首先,我使用scikit-learn中的StratifiedKfold函数.在某些时候,我想进行更多迭代,然后我改为StratifiedShuffleSplit.通过这个新功能,我获得的结果发生了变化.最后,我意识到如果我指定一个random_state,我会再次获得与使用StratifiedKfold作为CV时获得的结果类似的结果.

总之,如果我指定random_state,对于不同的值,我会得到稍微不同的结果,类似于我使用StratifiedKfold获得的结果(通过一次迭代,或者计算我自己的混洗,如此处所示).但是,如果random_state为none或未指定,则我获得的结果完全改变.

我检查了当random_state为None时,列车和测试索引是不同的,并按预期分层.

我没有随机数生成器的经验,但这对我没有任何意义

查看代码,我意识到当random_state为None时,调用函数check_random_state.此函数,如果seed为none,则返回np.random(link)使用的RandomState单例.

我写了一些有问题的代码.如果我用下面的那个更改注释行,我会得到不同的结果.

import numpy as np
import sklearn as skl

(...)
#skCVs=skl.cross_validation.StratifiedShuffleSplit(classes,n_iter=iterations*kfoldCV,test_size = 1/float(kfoldCV),random_state=5)
skCVs=skl.cross_validation.StratifiedShuffleSplit(classes,n_iter=iterations*kfoldCV,test_size = 1/float(kfoldCV))

for train,test in skCVs:

   (classification, ...)
Run Code Online (Sandbox Code Playgroud)

我正在使用sklearn的0.14版本.

你有任何解释或线索可以帮助理解正在发生的事情吗?

python random machine-learning scikit-learn cross-validation

2
推荐指数
1
解决办法
2767
查看次数

自定义交叉验证拆分sklearn

我正在尝试拆分交叉验证的数据集和sklearn中的GridSearch.我想定义自己的拆分,但GridSearch只采用内置的交叉验证方法.

但是,我不能使用内置的交叉验证方法,因为我需要某些示例组在同一个折叠中.所以,如果我有例子:[A1,A2,A3,A4,A5,B1,B2,B3,C1,C2,C3,C4,......,Z1,Z2,Z3]

我想进行交叉验证,使得每个组[A,B,C ...]中的示例仅存在于一个折叠中.

即K1包含[D,E,G,J,K ...],K2包含[A,C,L,M,...],K3包含[B,F,I,...]等

python validation machine-learning scikit-learn cross-validation

2
推荐指数
1
解决办法
4559
查看次数

如何改善神经网络输出?

我有一个150行,45个功能和40个输出的数据集.我可以很好地过度填充数据,但我的交叉验证集无法获得可接受的结果.

有25个隐藏层和相当多的迭代次数,我的训练集能够达到~94%的准确率; 在我脸上露出笑容.但交叉验证结果不到15%.

因此,为了减轻过度拟合,我开始使用正则化参数(lambda)以及隐藏层的数量.我得到的最好结果(CV)是训练集24%,训练集34%,lambda = 1,70个隐藏层和14000次迭代.增加it的数量也使情况变得更糟; 我无法理解为什么我不能通过增加lambda和iters来改善CV结果?

这是我尝试过的lambda-hiddenLayer-iter组合:

https://docs.google.com/spreadsheets/d/11ObRTg05lZENpjUj4Ei3CbHOh5mVzF7h9PKHq6Yn6T4/edit?usp=sharing

任何建议的方法尝试更智能的监管参数隐藏层分组合?还是其他改善我NN的方法?我使用来自Andrew Ng的ML类的matlab代码(使用反向传播算法.)

machine-learning neural-network cross-validation

2
推荐指数
1
解决办法
4086
查看次数

在MATLAB中使用神经网络分类进行10次交叉验证的示例

我正在寻找一个在神经网络中应用10倍交叉验证的例子.我需要这个问题的链接答案:MATLAB中10倍SVM分类的例子

我想对所有3个类进行分类,而在示例中只考虑了两个类.

编辑:这是我为iris示例编写的代码

load fisheriris                              %# load iris dataset

k=10;
cvFolds = crossvalind('Kfold', species, k);   %# get indices of 10-fold CV
net = feedforwardnet(10);


for i = 1:k                                  %# for each fold
    testIdx = (cvFolds == i);                %# get indices of test instances
    trainIdx = ~testIdx;                     %# get indices training instances

    %# train 

    net = train(net,meas(trainIdx,:)',species(trainIdx)');
    %# test 
    outputs = net(meas(trainIdx,:)');
    errors = gsubtract(species(trainIdx)',outputs);
    performance = perform(net,species(trainIdx)',outputs)
    figure, plotconfusion(species(trainIdx)',outputs)
end
Run Code Online (Sandbox Code Playgroud)

matlab给出的错误:

Error using nntraining.setup>setupPerWorker (line 62)
Targets T{1,1} is …
Run Code Online (Sandbox Code Playgroud)

matlab classification machine-learning neural-network cross-validation

2
推荐指数
1
解决办法
5215
查看次数

StratifiedKfold在异构DataFrame上

我有一个pandas DataFrame,它包含字符串和浮点数,需要拆分成平衡切片才能训练sklearn管道.

理想情况下,我会在DataFrame上使用StratifiedKFold来获取较小的数据块以进行交叉验证.但它抱怨我有无法解决的类型,如下所示:

import pandas as pd
from sklearn.cross_validation import StratifiedKFold

dataset = pd.DataFrame(
    [
        {'title': 'Dábale arroz a la zorra el abad', 'size':1.2, 'target': 1},
        {'title': 'Ana lleva al oso la avellana', 'size':1.0, 'target': 1},
        {'title': 'No te enrollé yornetón', 'size':1.4, 'target': 0},
        {'title': 'Acá sólo tito lo saca', 'size':1.4, 'target': 0},
    ])
skfs = StratifiedKFold(dataset, n_folds=2)

>>>  TypeError: unorderable types: str() > float()
Run Code Online (Sandbox Code Playgroud)

有一些方法可以获得折叠索引并对DataFrame进行切片,但我认为这并不能保证我的类会得到平衡.

拆分DataFrame的最佳方法是什么?

python machine-learning pandas scikit-learn cross-validation

2
推荐指数
2
解决办法
2019
查看次数

sklearn TimeSeriesSplit cross_val_predict仅适用于分区

我试图在sklearn版本0.18.1中使用TimeSeriesSplit交叉验证策略和LogisticRegression估算器.我得到一个错误说明:

cross_val_predict仅适用于分区

以下代码段显示了如何重现:

from sklearn import linear_model, neighbors
from sklearn.model_selection import train_test_split, cross_val_predict, TimeSeriesSplit, KFold, cross_val_score
import pandas as pd
import numpy as np
from datetime import date, datetime

df = pd.DataFrame(data=np.random.randint(0,10,(100,5)), index=pd.date_range(start=date.today(), periods=100), columns='x1 x2 x3 x4 y'.split())


X, y = df['x1 x2 x3 x4'.split()], df['y']
score = cross_val_score(linear_model.LogisticRegression(fit_intercept=True), X, y, cv=TimeSeriesSplit(n_splits=2))
y_hat = cross_val_predict(linear_model.LogisticRegression(fit_intercept=True), X, y, cv=TimeSeriesSplit(n_splits=2), method='predict_proba')
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

python scikit-learn cross-validation logistic-regression

2
推荐指数
1
解决办法
2238
查看次数

Sklearn 0.20+的交叉验证?

我正在尝试进行交叉验证,我遇到了一个错误,上面写着:"发现输入变量的样本数量不一致:[18,1]"

我在pandas数据框(df)中使用不同的列作为功能,最后一列作为标签.这来自加州大学欧文分校的机器学习库.导入我过去使用的交叉验证包时,我收到一个可能已经折旧的错误.我将运行决策树,SVM和K-NN.

我的代码是这样的:

feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.cross_validation import train_test_split
from sklearn.model_selection import cross_val_score
# Model Training 
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)
Run Code Online (Sandbox Code Playgroud)

任何帮助都会很棒!

python machine-learning scikit-learn cross-validation sklearn-pandas

2
推荐指数
1
解决办法
1729
查看次数

验证和测试的准确性差异很大

我目前正在研究kaggle中的数据集.在训练训练数据模型后,我在验证数据上进行测试,得到的精度约为0.49.

但是,相同的模型在测试数据上给出0.05的准确度.

我使用神经网络作为我的模型

那么,发生这种情况的可能原因是什么?如何开始检查和纠正这些问题?

machine-learning training-data cross-validation deep-learning kaggle

2
推荐指数
1
解决办法
3326
查看次数

尚未安装RandomForestClassifier实例。使用此方法之前,请使用适当的参数调用“ fit”

我正在尝试训练决策树模型,保存它,然后在以后需要时重新加载它。但是,我不断收到以下错误:

该DecisionTreeClassifier实例尚未安装。使用此方法之前,请使用适当的参数调用“ fit”。

这是我的代码:

X_train, X_test, y_train, y_test = train_test_split(data, label, test_size=0.20, random_state=4)

names = ["Decision Tree", "Random Forest", "Neural Net"]

classifiers = [
    DecisionTreeClassifier(),
    RandomForestClassifier(),
    MLPClassifier()
    ]

score = 0
for name, clf in zip(names, classifiers):
    if name == "Decision Tree":
        clf = DecisionTreeClassifier(random_state=0)
        grid_search = GridSearchCV(clf, param_grid=param_grid_DT)
        grid_search.fit(X_train, y_train_TF)
        if grid_search.best_score_ > score:
            score = grid_search.best_score_
            best_clf = clf
    elif name == "Random Forest":
        clf = RandomForestClassifier(random_state=0)
        grid_search = GridSearchCV(clf, param_grid_RF)
        grid_search.fit(X_train, y_train_TF)
        if grid_search.best_score_ > score:
            score …
Run Code Online (Sandbox Code Playgroud)

python machine-learning scikit-learn cross-validation grid-search

2
推荐指数
1
解决办法
5760
查看次数

如何在sklearn中使用交叉验证执行SMOTE

我有一个高度不平衡的数据集,并希望执行SMOTE来平衡数据集并进行交叉验证以测量准确性。但是,大多数现有教程仅利用单次trainingtesting迭代来执行SMOTE。

因此,我想知道使用交叉验证执行SMOTE的正确过程。

我当前的代码如下。但是,如上所述,它仅使用一次迭代。

from imblearn.over_sampling import SMOTE
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
sm = SMOTE(random_state=2)
X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel())
clf_rf = RandomForestClassifier(n_estimators=25, random_state=12)
clf_rf.fit(x_train_res, y_train_res)
Run Code Online (Sandbox Code Playgroud)

如果需要,我很乐意提供更多详细信息。

python classification machine-learning scikit-learn cross-validation

2
推荐指数
2
解决办法
1298
查看次数