Skip to main content
 首页 » 编程设计

python之以下用于绘制决策面的代码卡在哪里

2024年09月07日7daizhj

作为练习,我从 iris 数据集上的 sklearn 文档中复制粘贴了决策表面绘图代码:

# Few differences from the original at the link below (two classes, some renamed vars): 
# http://scikit-learn.org/stable/auto_examples/tree/plot_iris.html 
# Parameters 
n_classes = 2 
plot_colors = "rb" 
plot_step = 0.02 
 
# Get my X and y - each sample is a histogram with a binary class label. 
X, y, positives = Loader.load_cluster_size_histograms_singular(m=115, upper=21, norm=False, display_plot=False, pretty_print=False) 
 
my_features = [str(i+1) for i in range(X.shape[1])] 
my_features[-1] = my_features[-1] + '+' 
features = np.asarray(my_features) 
 
# Load iris data 
iris = load_iris() 
 
iris.data = iris.data[:, 100] 
iris.target = iris.target[:, 100] 
 
features = iris.feature_names  # Comment or uncomment as necessary 
 
# Now asserting that my X and y does not contain np.nan or np.inf (wouldn't sklearn catch this though?) 
# Also check for correct sizing. We're really running out of potential failures here. 
for i in range(115): 
    assert(np.nan not in X[i]) 
    assert(np.inf not in X[i]) 
    assert(X[i].shape[0] == 21) 
 
# They do not. X and y are clean. 
 
for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], 
                                [1, 2], [1, 3], [2, 3]]): 
    # Set local_X = X[:, pair], local_y = y, features to my_features... BOOOOOM!  
    # CPU gets nuked, doesn't terminate. 
    local_X = iris.data[:, pair] 
    local_y = iris.target 
 
    # Train 
    clf = Pipeline(steps=[("scaling", StandardScaler()), ("classifier", LogisticRegression(verbose=100))]) 
    clf.fit(local_X, local_y) 
 
    # Plot the decision boundary 
    plt.subplot(2, 3, pairidx + 1) 
 
    x_min, x_max = local_X[:, 0].min() - 1, local_X[:, 0].max() + 1 
    y_min, y_max = local_X[:, 1].min() - 1, local_X[:, 1].max() + 1 
    xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step), 
                         np.arange(y_min, y_max, plot_step)) 
    plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5) 
 
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 
    Z = Z.reshape(xx.shape) 
    cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu) 
 
    plt.xlabel(features[pair[0]]) 
    plt.ylabel(features[pair[1]]) 
 
    # Plot the training points 
    for i, color in zip(range(n_classes), plot_colors): 
        idx = np.where(local_y == i) 
        plt.scatter(local_X[idx, 0], local_X[idx, 1], c=color, label=features[i], 
                    cmap=plt.cm.RdBu, edgecolor='black', s=15) 
 
plt.suptitle("Decision surface of a decision tree using paired features") 
plt.legend(loc='lower right', borderpad=0, handletextpad=0) 
plt.axis("tight") 
plt.show() 

输出如下:

好吗?所以代码完全没问题,只是重命名并使用/删除了一些小细节。这里绝对没有问题。

我的问题是这样的 - 当我用我自己的虹膜数据集替换 iris 数据集时,它会在 clf.fit(local_X, local_y) 行完全消耗 CPU。不管什么分类器,Logistic Regression,SVM,GaussianNB,一大堆。一切都慢得令人难以置信的缓慢爬行,点击注册需要几十秒。不会终止,即使在听到我的 CPU 被水刑几分钟后也是如此。上面代码的唯一区别是我设置了local_X = X[:, pair],我设置了local_y = y,然后我设置了features = np.asarray(my_features)(其中 my_features 是我自己的特征名称向量,作为一个 numpy 数组)。

配备 1.4 GHz Intel Core i5 的 Macbook Air 上的 CPU 负载视觉图:

我的数据集也不是很大 - 只有 (115, 21) 和 (115,) 用于我自己的 X 和 y。所以数据的大小不能成为一个因素。

现在对那些喜欢批评而不是帮助的人进行问答:

您没有缩放输入。

  • 错误。这实际上是我管道中的第一阶段。我会说我的特征向量是一个直方图。我尝试通过将每个直方图总和设为 1 来进行缩放。完全相同的问题。

你做错了。

  • 出色的观察力。你介意解释一下我做错了什么吗?

您是否尝试过将其关闭然后重新打开?

  • 这有什么帮助?是的,我有,尽管完全没有理由说明为什么我应该这样做。我已经重新启动内核,新 session 。同样的问题。

当我在我的机器上运行代码并将分类器的详细程度设置为 100 时,我得到的唯一输出是:

[LibLinear]

不是很多,但它打印的全部。感谢任何有帮助的评论、建议和理想的答案!

EDTI:

已被要求提供我的数据集的代表性样本。如前所述,样本是直方图。示例可能如下所示(np.array 类型,元素类型为 np.float32):

[1515. 1072.  598.  447.  307.  221.  184.  166.  121.   82.   76.   67.   69.   58.   39.   49.   40.   37.   24.   27.  590.] 

更新:因此尝试使用 norm=True 再次加载我的数据集(这意味着每个直方图总计为 1,所以我的浮点值在 0 和 1 之间,但没有发生其他标准化,这是管道中没有 StandardScaler()),代码运行,但得到无用的结果:

当 StandardScaler() 包含在管道中时,我在使用 Logistic 回归时得到类似的奇怪结果:

当norm=False时仍然会出现完全挂起。这很奇怪。

请您参考如下方法:

所以我发现了问题 - 它实际上不是 fit() 函数中断。这是 np.meshgrid()!事实上,当输入范围为数百或数千时,plot_size 参数设置为 0.02。

我的猜测是,当使用值范围调用 np.meshgrid() 时,绝对数量的坐标会导致它完全失控。一旦我开始使用更能反射(reflect)合理步骤的值(例如 100)作为我的输入,它就开始起作用了。

很傻,np.meshgrid() 不会对这些类型的输入发出警告。由于缺乏单挑,我的 CPU 负载量一度达到 475%。同样,sklearn 文档可能会提到 plot_step 参数应相应调整。