我正在尝试使用 train_test_split 和决策树回归器进行这种训练建模:
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import cross_val_score
# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature
new_data = samples.drop('Fresh', 1)
# TODO: Split the data into training and testing sets using the given feature as the target
X_train, X_test, y_train, y_test = train_test_split(new_data, samples['Fresh'], test_size=0.25, random_state=0)
# TODO: Create a decision tree regressor and fit it to the training set
regressor = …Run Code Online (Sandbox Code Playgroud) 我知道这是一个非常经典的问题,可能会在本论坛中多次回答,但是我找不到任何明确的答案从头开始清楚地解释这一点。
首先,我的数据集 my_data 有 4 个变量,例如 my_data = variable1、variable2、variable3、target_variable
所以,让我们来解决我的问题。我将解释我的所有步骤,并就我遇到的问题寻求您的帮助:
# STEP1 : split my_data into [predictors] and [targets]
predictors = my_data[[
'variable1',
'variable2',
'variable3'
]]
targets = my_data.target_variable
# STEP2 : import the required libraries
from sklearn import cross_validation
from sklearn.ensemble import RandomForestRegressor
#STEP3 : define a simple Random Forest model attirbutes
model = RandomForestClassifier(n_estimators=100)
#STEP4 : Simple K-Fold cross validation. 3 folds.
cv = cross_validation.KFold(len(my_data), n_folds=3, random_state=30)
# STEP 5
Run Code Online (Sandbox Code Playgroud)
在这一步,我想根据训练数据集拟合我的模型,然后在测试数据集上使用该模型并预测测试目标。我还想计算所需的统计数据,例如 MSE、r2 等,以了解我的模型的性能。
如果有人帮助我了解 Step5 的一些基本代码行,我将不胜感激。
regression machine-learning random-forest scikit-learn cross-validation
我对机器学习比较陌生,希望在以下方面得到一些帮助:
我使用 10 倍交叉验证对我的数据运行了支持向量机分类器 (SVC),并计算了准确度得分(约为 89%)。我正在使用 Python 和 scikit-learn 来执行任务。这是一个代码片段:
def get_scores(features,target,classifier):
X_train, X_test, y_train, y_test =train_test_split(features, target ,
test_size=0.3)
scores = cross_val_score(
classifier,
X_train,
y_train,
cv=10,
scoring='accuracy',
n_jobs=-1)
return(scores)
get_scores(features_from_df,target_from_df,svm.SVC())
Run Code Online (Sandbox Code Playgroud)
现在,我如何使用我的分类器(在运行 10 倍 cv 之后)在 X_test 上对其进行测试并将预测结果与 y_test 进行比较?您可能已经注意到,我在交叉验证过程中只使用了 X_train 和 y_train。
我注意到 sklearn 有 cross_val_predict:http : //scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html 我应该用 cross_val_predict 替换我的 cross_val_score 吗?仅供参考:我的目标数据列是二值化的(值为 0 和 1)。
如果我的方法是错误的,请告诉我最好的处理方法。
谢谢!
在训练 Ridge 分类器时,我可以像这样执行 10 折交叉验证:
clf = linear_model.RidgeClassifier()
n_folds = 10
scores = cross_val_score(clf, X_train, y_train, cv=n_folds)
scores
array([0.83236107, 0.83937346, 0.84490172, 0.82985258, 0.84336609,
0.83753071, 0.83753071, 0.84213759, 0.84121622, 0.84398034])
Run Code Online (Sandbox Code Playgroud)
如果我想再次执行 10 折交叉验证,我使用:
scores = cross_val_score(clf, X_train, y_train, cv=n_folds)
Run Code Online (Sandbox Code Playgroud)
我最终得到了相同的结果。
因此,似乎两次数据都以相同的方式拆分。有没有办法在每次执行交叉验证时将数据随机划分为 n_folds?
我正在尝试使用 R 的包 xgboost。但有一点让我感到困惑。在 xgboost 手册中,在 xgb.cv 函数下,它说:
原始样本被随机划分为 n 倍大小相等的子样本。
在nfold subsamples中,保留单个subsample作为测试模型的验证数据,剩余nfold-1个subsample作为训练数据。
然后将交叉验证过程重复 n 次,每个 n 倍子样本仅用作验证数据一次。
这是手册中的代码:
data(agaricus.train, package='xgboost')
dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
cv <- xgb.cv(data = dtrain, nrounds = 3, nthread = 2, nfold = 5, metrics =
list("rmse","auc"),
max_depth = 3, eta = 1, objective = "binary:logistic")
print(cv)
print(cv, verbose=TRUE)
Run Code Online (Sandbox Code Playgroud)
结果是:
##### xgb.cv 5-folds
call:
xgb.cv(data = dtrain, nrounds = 3, nfold = 5, metrics = list("rmse",
"auc"), nthread = 2, max_depth = 3, …Run Code Online (Sandbox Code Playgroud) 我希望你能帮忙
我一直在尝试使用 scikit learn 中的随机搜索功能来调整我的随机森林模型。
如下所示,我给出了几个最大深度和几个叶子样本的选项。
# Create a based model
model = RandomForestClassifier()
# Instantiate the random search model
best = RandomizedSearchCV(model, {
'bootstrap': [True, False],
'max_depth': [80, 90, 100, 110],
'min_samples_leaf': [3, 4, 5]
}, cv=5, return_train_score=True, iid=True, n_iter = 4)
best.fit(train_features, train_labels.ravel())
print(best.best_score_)
print(best)
Run Code Online (Sandbox Code Playgroud)
但是当我运行这个时,我得到下面的结果,其中最大深度和每片叶子的最小样本设置为不在我的数组中的值。
我在这里做错了什么?
RandomizedSearchCV(cv=5, error_score='raise',
estimator=RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
**max_depth=None**, max_features='auto', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
**min_samples_leaf=1**, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=10, n_jobs=1,
oob_score=False, random_state=None, verbose=0,
warm_start=False),
fit_params=None, iid=True, n_iter=4, n_jobs=1,
param_distributions={'bootstrap': [True, False], 'max_depth': [80, 90, 100, 110], …Run Code Online (Sandbox Code Playgroud) python machine-learning random-forest scikit-learn cross-validation
我正在用 python 开始我的第一个机器学习代码。但是,我在计算多类模型的召回率、精度和 f1 时遇到了错误。
X = pd.read_excel(path, dtype=int)
allarray = X.values
X_data = allarray[:,0:-1]
Y = allarray[:,-1]
X_scaled = scaler.fit_transform(X_data)
create_model = create_custom_model(n_features, n_classes, 8, 3)
estimator = KerasClassifier(build_fn=create_model, epochs=100, batch_size=100, verbose=0)
scores = cross_validate(estimator, X_scaled, Y, cv=10, scoring=('precision', 'recall', 'f1'), return_train_score=False)
print(scores['precision'])
print(scores['recall'])
print(scores['f1'])
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
ValueError: Target is multiclass but average='binary'. Please choose another average setting.
Run Code Online (Sandbox Code Playgroud)
但cross_validate没有参数average
python machine-learning scikit-learn cross-validation precision-recall
我正在训练多层感知器。我有两个问题,第一个问题是 K 折叠如何防止过度拟合,因为 train-test-split 也做同样的事情,接受训练部分并验证模型,与 K 折叠相同,而不仅仅是有多个折叠。但是 train_test_split 有可能过度拟合,那么 K Fold 如何防止它,因为在我的感知中,模型也可能过度拟合 K Fold 的训练部分,你认为是这样吗?第二个问题是我从 K 折中获得了 95% 以上的准确率,先生告诉我方差太大,这里怎么可能因为 k 折解决了这种过度拟合?
machine-learning scikit-learn cross-validation supervised-learning deep-learning
之前看过一个帖子,代码是这样的:
scalar = StandardScaler()
clf = svm.LinearSVC()
pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])
cv = KFold(n_splits=4)
scores = cross_val_score(pipeline, X, y, cv = cv)
Run Code Online (Sandbox Code Playgroud)
我的理解是:当我们应用缩放,我们应该使用3出4倍来计算平均值和标准差,那么我们应用均值和标准差的所有4倍。
在上面的代码中,我怎么知道 Sklearn 遵循相同的策略?另一方面,如果 sklearn 不遵循相同的策略,这意味着 sklearn 将计算所有 4 折的均值/标准差。这是否意味着我不应该使用上述代码?
我喜欢上面的代码,因为它节省了大量的时间。
我有一个包含 84 个月销售额(从 01/2013 到 12/2019)的数据集 - 只是几个月,而不是几天。
Month 01 | Sale 1
Month 02 | Sale 2
Month 03 | Sale 3
.... | ...
Month 84 | Sale 84
Run Code Online (Sandbox Code Playgroud)
通过可视化看起来模型非常适合......但我需要检查它......
所以我的理解是 cross val 不支持 Months,所以我所做的是转换为使用它/天(尽管我的原始 df 中没有日期信息)...
我想在前五年(60 个月)内尝试我的模型,并在剩下的 2 年(24 个月)中查看模型的预测效果......
所以我做了类似的事情:
cv_results = cross_validation( model = prophet, initial='1825 days', period='30 days', horizon = '60 days')
Run Code Online (Sandbox Code Playgroud)
这有意义吗?
我没有得到截止日期和预测期的概念
python machine-learning time-series cross-validation facebook-prophet
cross-validation ×10
python ×7
scikit-learn ×7
pipeline ×1
r ×1
regression ×1
svm ×1
time-series ×1
xgboost ×1