我正在尝试通过 GridSearchCV 找到最佳的 xgboost 模型,并且作为 cross_validation 我想使用 4 月的目标数据。这是代码:
x_train.head()
Run Code Online (Sandbox Code Playgroud)
y_train.head()
Run Code Online (Sandbox Code Playgroud)
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.metrics import make_scorer
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import TimeSeriesSplit
import xgboost as xg
xgb_parameters={'max_depth':[3,5,7,9],'min_child_weight':[1,3,5]}
xgb=xg.XGBRegressor(learning_rate=0.1, n_estimators=100,max_depth=5, min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8)
model=GridSearchCV(n_jobs=2,estimator=xgb,param_grid=xgb_parameters,cv=train_test_split(x_train,y_train,test_size=len(y_train['2016-04':'2016-04']), random_state=42, shuffle=False),scoring=my_func)
model.fit(x_train,y_train)
model.grid_scores_
model.best_params_
Run Code Online (Sandbox Code Playgroud)
但是我在训练模型时遇到了这个错误。
有人可以帮我解决这个问题吗?或者有人可以建议我如何分割非洗牌数据来训练/测试以验证上个月的模型?
感谢您的帮助
python machine-learning cross-validation grid-search train-test-split
首先是我的设置:X 是我的特征表。它有 150 000 个特征和 96 个样本。所以有 150 000 列和 96 行。
y 是我的目标表。它有 4 个标签,当然还有 96 个样品。所以 4x96(列 x 行)。
分成训练数据和测试数据后,我使用 MLPRegressor。基于 Sci-kit 的文档,它是一个原生的多输出回归器。因此我可以使用它通过 150 000 个特征的新样本来预测我的四个所需输出值。我的代码:
mlp = MLPRegressor(hidden_layer_sizes=(2000, 2000), solver= 'lbfgs', max_iter=100)
mlp.fit(X_train,y_train)
Run Code Online (Sandbox Code Playgroud)
然后我使用交叉验证。
cross_validation.cross_val_score(mlp, X, y, scoring='r2')
Run Code Online (Sandbox Code Playgroud)
输出是一个包含 3 个条目的列表(参数 cv=3)。我真的不明白我的 4 个标签是如何由这 3 个值表示的。我期望的格式如下:标签 1: 3 个条目,标签 2: 3 个条目,标签 3 和 4 也相同。因此,对于不同的分割,我将所有标签的 R^2 值三次获取测试和训练数据。
我错过了什么吗?我需要使用多输出回归器吗? (请参阅此处的文档)
这里是交叉验证的文档。
谢谢。
python machine-learning neural-network scikit-learn cross-validation
以下示例脚本输出预测值和预测概率:
from sklearn import datasets, linear_model
from sklearn.model_selection import cross_val_predict
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
lg = linear_model.LogisticRegression(random_state=0, solver='lbfgs')
y_prob = cross_val_predict(lg, X, y, cv=4, method='predict_proba')
y_pred = cross_val_predict(lg, X, y, cv=4)
y_prob[0:5]
y_pred[0:5]
Run Code Online (Sandbox Code Playgroud)
我尝试以下但没有成功:
test = cross_val_predict(lg, X, y, cv=4, method=['predict','predict_proba'])
Run Code Online (Sandbox Code Playgroud)
问题:有没有一种方法可以一步获得预测值和预测概率,而无需运行两次交叉验证?另外,我必须确保值和概率对应于相同的输入数据。
我GridSearchCV用来识别最佳参数,但我不确定如何实际使用最佳参数,也就是说,在下面的代码中,在第三行中,更改第一行后我的结果不会改变(例如,如果我更改参数空格,或用精确度替换召回率等)
cv = GridSearchCV(pipeline, parameters, cv=len(range(2014,2019)), scoring='recall', refit=True)
cv.fit(X,y)
y_pred = cross_val_predict(cv, X, y, cv=len(range(2014,2019)))
Run Code Online (Sandbox Code Playgroud)
有没有办法确保无论何时GridSearchCV我打电话时,所确定的最佳参数实际上也会被使用cv.predict?
python machine-learning scikit-learn cross-validation grid-search
我该如何获取逻辑回归中model.coef_RandomForest()等特征的系数?
model = GridSearchCV(estimator=classifier, param_grid=grid_param,
scoring='roc_auc',
cv=5,
n_jobs=-1)
best_model= model.fit(X_train, y_train)
best_model.feature_importances_
Run Code Online (Sandbox Code Playgroud) python machine-learning random-forest scikit-learn cross-validation
我正在关注Kaggle 上的内核,并发现了以下代码:
n_folds = 5
def rmsle_cv(model):
kf = KFold(n_folds, shuffle=True, random_state=42).get_n_splits(train.values)
rmse= np.sqrt(-cross_val_score(model, train.values, y_train, scoring="neg_mean_squared_error", cv = kf))
return(rmse)
Run Code Online (Sandbox Code Playgroud)
我了解 KFold 的目的和用途以及在 中使用的事实cross_val_score。我不明白的是为什么get_n_split使用。据我所知,它返回用于交叉验证的迭代次数,即在本例中返回值 5。当然对于这一行:
rmse= np.sqrt(-cross_val_score(model, train.values, y_train, scoring="neg_mean_squared_error", cv = kf))
Run Code Online (Sandbox Code Playgroud)
简历=5?这对我来说没有任何意义。get_n_splits如果它返回一个整数,为什么还需要使用?我认为KFold 返回一个类,而get_n_splits返回一个整数。
任何人都可以澄清我的理解吗?
我试图弄清楚如何使用 cross_validate 生成混淆矩阵。我可以使用迄今为止的代码打印出分数。
# Instantiating model
model = DecisionTreeClassifier()
#Scores
scoring = {'accuracy' : make_scorer(accuracy_score),
'precision' : make_scorer(precision_score),
'recall' : make_scorer(recall_score),
'f1_score' : make_scorer(f1_score)}
# 10-fold cross validation
scores = cross_validate(model, X, y, cv=10, scoring=scoring)
print("Accuracy (Testing): %0.2f (+/- %0.2f)" % (scores['test_accuracy'].mean(), scores['test_accuracy'].std() * 2))
print("Precision (Testing): %0.2f (+/- %0.2f)" % (scores['test_precision'].mean(), scores['test_precision'].std() * 2))
print("Recall (Testing): %0.2f (+/- %0.2f)" % (scores['test_recall'].mean(), scores['test_recall'].std() * 2))
print("F1-Score (Testing): %0.2f (+/- %0.2f)" % (scores['test_f1_score'].mean(), scores['test_f1_score'].std() * 2))
Run Code Online (Sandbox Code Playgroud)
但我正在尝试将这些数据放入混淆矩阵中。我可以使用 cross_val_predict 制作混淆矩阵 -
y_train_pred …Run Code Online (Sandbox Code Playgroud) python machine-learning confusion-matrix scikit-learn cross-validation
我正在尝试将文本数据分类为多个类。我想执行交叉验证来比较多个模型与样本权重。
对于每个模型,我都可以输入这样的参数。
all_together = y_train.to_numpy()
unique_classes = np.unique(all_together)
c_w = class_weight.compute_class_weight('balanced', unique_classes, all_together)
clf = MultinomialNB().fit(X_train_tfidf, y_train, sample_weight=[c_w[i] for i in all_together])
Run Code Online (Sandbox Code Playgroud)
似乎不允许cross_val_score()有关sample_weight的参数。我如何通过交叉验证来做到这一点?
models = [
RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0),
LinearSVC(),
MultinomialNB(),
LogisticRegression(random_state=0),
]
all_together = y_train.to_numpy()
unique_classes = np.unique(all_together)
c_w = class_weight.compute_class_weight('balanced', unique_classes, all_together)
CV = 5
cv_df = pd.DataFrame(index=range(CV * len(models)))
entries = []
for model in models:
model_name = model.__class__.__name__
f1_micros = cross_val_score(model, X_tfidf, y_train, scoring='f1_micro', cv=CV)
for fold_idx, f1_micro in enumerate(f1_micros):
entries.append((model_name, fold_idx, f1_micro))
cv_df_women …Run Code Online (Sandbox Code Playgroud) 我使用插入包来训练随机森林,包括重复的交叉验证.我想知道是否使用了Breiman的原始RF中的OOB,或者是否将其替换为交叉验证.如果它被替换,我是否具有与Breiman 2001中描述的相同的优点,如通过减少输入数据之间的相关性来提高准确度?由于OOB是在更换时绘制的,而CV是在没有替换的情况下绘制的,两个程序是否可比?什么是错误率的OOB估计(基于CV)?
树木是如何生长的?是否使用CART?
由于这是我的第一个主题,如果您需要更多详细信息,请告诉我.提前谢谢了.
在Jupyter笔记本上本地运行并使用MNIST数据集(28k条目,每个图像28x28像素,接下来的时间为27秒)。
from sklearn.neighbors import KNeighborsClassifier
knn_clf = KNeighborsClassifier(n_jobs=1)
knn_clf.fit(pixels, labels)
Run Code Online (Sandbox Code Playgroud)
但是,以下过程需要1722秒,也就是说,要花费〜64 倍的时间:
from sklearn.model_selection import cross_val_predict
y_train_pred = cross_val_predict(knn_clf, pixels, labels, cv = 3, n_jobs=1)
Run Code Online (Sandbox Code Playgroud)
我天真的理解是cv = 3的cross_val_predict正在执行3倍交叉验证,因此我希望它可以拟合模型3次,因此至少需要3倍的时间,但是我不知道为什么会这样花64倍!
要检查它是否特定于我的环境,我在Colab笔记本上运行了相同的东西 -差异不那么极端(15x),但仍远高于我预期的〜3x:
我想念什么?为什么cross_val_predict比仅拟合模型要慢得多?
万一重要,我正在运行scikit-learn 0.20.2。
python performance machine-learning scikit-learn cross-validation
cross-validation ×10
python ×8
scikit-learn ×7
grid-search ×2
k-fold ×1
performance ×1
prediction ×1
r-caret ×1