2026a

# repartition


重新划分交叉验证的分区数据

函数库: TyMachineLearning

# 语法

kf = repartition(n_obsvts::Int, method::String; k::Int=10, p::Float64=0.1)
train_set, test_set = repartition(n_obsvts::Int, method::String; k::Int=10, p::Float64=0.1)

# 说明

kfnew = repartition(kf) 对数据集进行重新划分(k-fold)

snew = repartition(s) 对数据集进行重新划分(holdout)

# 示例

划分数据集训练决策树模型

加载 iris 数据集。

using TyMachineLearning
using CSV
using DataFrames
iris_X, iris_y = get_irsdata()

创建划分数据对象。

使用决策树分类器。

n_observations = size(iris_y)[1]
kf = cvpartition(n_observations, "kFold")

根据真实标签 y 和预测标签预测 y_pred 查看 Accuracy。

for (train_ids, test_ids) in kf
    train_X = iris_X[train_ids, :]
    train_y = iris_y[train_ids]
    test_X = iris_X[test_ids, :]
    test_y = iris_y[test_ids]
    # do something...
    # Create and train the model
    tree = fitctree(train_X, train_y)

    # Make predictions on the test set
    predictions = TyMachineLearning.predict(tree, test_X)

    # Evaluate the model, e.g., calculate accuracy
    accuracy = sum(predictions .== test_y) / length(test_y)

    # Print the accuracy or perform other operations
    println("Accuracy: $accuracy")
end
Accuracy: 1.0
Accuracy: 0.9333333333333333
Accuracy: 1.0
Accuracy: 1.0
Accuracy: 0.8
Accuracy: 0.8666666666666667
Accuracy: 0.9333333333333333
Accuracy: 0.8666666666666667
Accuracy: 0.9333333333333333
Accuracy: 1.0

该函数是随机划分数据集,所以模型评估是有随机性正常情况。

spliting = cvpartition(n_observations, "Holdout")
train_ids, test_ids = spliting
train_X, train_y = iris_X[train_ids, :], iris_y[train_ids]
test_X, test_y = iris_X[test_ids, :], iris_y[test_ids]
([7.7 3.0 6.1 2.3; 4.8 3.0 1.4 0.1; … ; 7.2 3.6 6.1 2.5; 6.2 2.9 4.3 1.3], Int32[2, 0, 1, 2, 2, 1, 1, 0, 2, 0, 0, 1, 1, 2, 1])

该函数是随机划分数据集,所以模型评估是有随机性正常情况。

repartition(kf)
repartition(spliting)
([140, 78, 126, 26, 23, 81, 10, 32, 27, 57  …  79, 95, 124, 135, 45, 38, 19, 35, 104, 76], [134, 117, 5, 146, 61, 136, 14, 103, 150, 40, 6, 125, 142, 93, 109])

该函数是随机划分数据集,所以模型评估是有随机性正常情况。

# 输入参数

kf
kf 对象

一个列表,其中包含 k 折数据划分,每一折中包含了训练集和测试集的索引元组。

s
训练集测试集索引集合

训练集测试集索引集合。

# 输出参数

kfnew
新的 kf 对象

一个列表,其中包含 k 折数据划分,每一折中包含了训练集和测试集的索引元组。

snew
训练集测试集索引集合

返回新的训练集测试集索引集合。

# 另请参阅

confusionmat