You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写for循环实现y_pr>=1标注1、y_pr<=-1标注-1的分类逻辑

问题说明

你现有代码的判断逻辑存在漏洞:当w^Tx_i + b的计算结果落在(-1, 1)区间时,所有样本都会被错误赋值为-1,不符合你指定的分类规则。

循环版本修改方案

直接拆分原else分支为多分支判断即可,落在间隔带的样本可根据需求设置占位值(示例中用np.nan标记未分类样本,也可自行调整为其他逻辑):

import numpy as np

def cla(X,w,b):
    pre_te = np.zeros(len(X))
    length = X.shape[0]

    for i in range(length):
        y_pred = np.dot(np.array(X[i]), w.T) + b
        if y_pred >= 1:
            pre_te[i] = 1
        elif y_pred <= -1:
            pre_te[i] = -1
        else:
            # 间隔带样本自定义逻辑,如需强制分类可改为按超平面符号判断:pre_te[i] = 1 if y_pred >=0 else -1
            pre_te[i] = np.nan
    return pre_te

更高效的向量化实现(无需循环)

针对numpy数组可以直接用向量化运算替代for循环,运行效率更高,尤其适合样本量更大的场景:

def cla_vectorized(X, w, b):
    y_pred_all = X @ w.T + b
    pre_te = np.where(y_pred_all >= 1, 1,
             np.where(y_pred_all <= -1, -1, np.nan))
    return pre_te

内容的提问来源于stack exchange,提问作者Hermi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:24:05