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

Snowpark编写向量化UDF时遭遇TypeError错误求助

Snowpark向量化UDF TypeError错误排查建议

我在Snowpark中编写向量化UDF函数时遇到TypeError错误,代码如下:

import pandas as pd
from snowflake.snowpark.functions import pandas_udf
from snowflake.snowpark.types import StringType

@pandas_udf(  
  name='EXERCISE_CO2_VS_TEMPERATURE.GLOBAL_TEMPERATURES.GET_REVIEW_CLASSIFICATION',
  session=new_session,
  is_permanent=True,
  replace=True,
  imports=[
      '@EXERCISE_CO2_VS_TEMPERATURE.GLOBAL_TEMPERATURES.ZERO_SHOT_CLASSIFICATION/bart-large-mnli.joblib'
  ],
  input_types=[StringType()],
  return_type=[StringType()],
  stage_location='@EXERCISE_CO2_VS_TEMPERATURE.GLOBAL_TEMPERATURES.ZERO_SHOT_CLASSIFICATION',
  packages=['cachetools==4.2.2', 'transformers==4.14.1']
)
def get_review_classification(sentences: pd.Series) -> pd.Series:
  # Classify using the available categories
  candidate_labels = ['customer support', 'product experience', 'account issues']
  classifier = read_model()

  # Apply the model
  predictions = []
  for sentence in sentences:
      result = classifier(sentence, candidate_labels)
      if 'scores' in result and 'labels' in result:
          category_idx = pd.Series(result['scores']).idxmax()
          predictions.append(result['labels'][category_idx])
      else:
          predictions.append(None)
  return pd.Series(predictions)

错误信息如下:

Cell In[55], line 17
      1 from snowflake.snowpark.functions import pandas_udf
      2 from snowflake.snowpark.types import StringType
      4 @pandas_udf(  
      5     name='EXERCISE_CO2_VS_TEMPERATURE.GLOBAL_TEMPERATURES.GET_REVIEW_CLASSIFICATION',
      6     session=new_session,
      7     is_permanent=True,
      8     replace=True,
      9     imports=[
     10         '@EXERCISE_CO2_VS_TEMPERATURE.GLOBAL_TEMPERATURES.ZERO_SHOT_CLASSIFICATION/bart-large-mnli.joblib'
     11     ],
     12     input_types=[StringType()],
     13     return_type=[StringType()],
     14     stage_location='@EXERCISE_CO2_VS_TEMPERATURE.GLOBAL_TEMPERATURES.ZERO_SHOT_CLASSIFICATION',
     15     packages=['cachetools==4.2.2', 'transformers==4.14.1']
.
.
.
.
TypeError: invalid type 

错误解决建议

  • 修正return_type参数格式:当前代码中return_type=[StringType()]使用了列表格式,这是UDTF(表函数)的多返回值写法。对于单返回值的UDF,应直接传入StringType()而非列表,类型不匹配是触发TypeError的核心原因。
  • 检查read_model函数实现:确保read_model()能正确加载stage上的joblib模型,返回合法的ZeroShotClassificationPipeline实例。如果模型加载失败或返回非预期类型,会导致后续调用classifier时触发类型错误。
  • 验证输入数据合法性:确认传入UDF的列是纯字符串类型,无Null或非字符串值,避免循环处理时因数据类型异常报错。
  • 核对依赖版本兼容性:检查指定的cachetools和transformers版本是否与当前使用的Snowpark版本兼容,部分旧版本transformers可能存在与Snowpark pandas_udf的类型适配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:13:13