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

运行代码时遇TypeError: ufunc 'isfinite'不支持输入类型问题求助

解决ufunc 'isfinite'不支持输入类型的错误

问题详情

  • 触发错误:TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
  • 错误代码行:
plt.contourf(x1, x2, classifier.predict(np.array([x1.ravel(), x2.ravel()]).T).reshape(x1.shape), alpha = 0.75, cmap = ListedColormap(('purple','green' )))

核心原因

这个错误本质是plt.contourf接收的第三个参数(预测结果)不是数值型数组,可能是object类型、字符串类型,导致numpy无法执行isfinite(判断数值是否有限)的操作。

解决步骤

  1. 排查预测结果的类型
    在报错代码前加两行调试代码,确认问题根源:

    pred_result = classifier.predict(np.array([x1.ravel(), x2.ravel()]).T)
    print(pred_result.dtype)  # 查看数据类型,若为object/str则存在问题
    print(pred_result[:10])   # 查看具体值,确认是否是类别字符串而非0/1这类数值标签
    
  2. 转换预测结果为数值型

    • 如果预测结果是类别字符串(比如"purple"/"green"),用LabelEncoder转成数值:
      from sklearn.preprocessing import LabelEncoder
      le = LabelEncoder()
      pred_num = le.fit_transform(pred_result)
      # 替换原代码中的预测结果部分
      plt.contourf(x1, x2, pred_num.reshape(x1.shape), alpha=0.75, cmap=ListedColormap(('purple','green')))
      
    • 如果是存储数值的object类型,直接强制转换为数值型:
      pred_num = pred_result.astype(np.float64)  # 也可根据实际情况选int类型
      plt.contourf(x1, x2, pred_num.reshape(x1.shape), alpha=0.75, cmap=ListedColormap(('purple','green')))
      
  3. 确认x1/x2的类型
    偶尔也可能是x1/x2不是数值型,同样转换为数值型数组:

    x1 = x1.astype(np.float64)
    x2 = x2.astype(np.float64)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:05:09