import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import LeaveOneOut

# 设置随机种子
np.random.seed(10)

# 生成样本数据和标签
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]])
y = np.random.randint(0, 2, 5).reshape((5, 1))

# 初始化最好的划分精度和对应的划分次序
best_score = 0.0
best_split = 0

# 使用LeaveOneOut进行留一法交叉验证
loo = LeaveOneOut()
for split, (train_index, test_index) in enumerate(loo.split(X)):
    # 划分训练集和测试集
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    # 训练逻辑回归模型
    lr = LogisticRegression()
    lr.fit(X_train, y_train.ravel())

    # 计算测试集精度
    score = lr.score(X_test, y_test)

    # 更新最好的划分精度和对应的划分次序
    if score > best_score:
        best_score = score
        best_split = split

# 输出最好的划分精度和对应的划分次序
print('the {} th leaveOneOut split of dataset is among the better split with score of {:.2f}'.format(best_split + 1, best_score))

示例说明:

  1. 样本数据和标签生成: 使用 np.array() 生成二维样本数据 X,使用 np.random.randint(a,b,5).reshape((5,1)) 生成标签数据 y,其中 ab 是类别区间的开始和结束。
  2. 留一法交叉验证: 使用 LeaveOneOut() 创建留一法交叉验证对象,并循环遍历每个划分,提取训练集和测试集。
  3. 逻辑回归训练: 使用 LogisticRegression() 创建逻辑回归模型,并使用 fit() 方法训练模型。
  4. 精度计算: 使用 score() 方法计算模型在测试集上的精度。
  5. 最佳划分次序: 比较每个划分下的精度,记录最高精度和对应的划分次序。
  6. 输出结果: 打印最佳划分次序和对应的精度。

输入样例:

0
2

输出样例:

the 3 th leaveOneOut split of dataset is among the better split with score of 1.00

注意: 该代码使用随机种子 np.random.seed(10) 以保证结果的可重复性。您也可以尝试更改 ab 的值来生成不同的标签数据,并观察结果的变化。

使用留一法和逻辑回归分析二维样本数据

原文地址: https://www.cveoy.top/t/topic/mMhu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录