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

如何通过循环实现DCNN神经网络批量处理文本并输出情感概率

批量处理文本正面评论概率预测实现方案

基础循环实现(适合少量文本)

直接遍历每条文本,复用你已有的单条预测逻辑,格式化输出结果即可:

import numpy as np

# 替换成你的批量文本列表
texts = [
    "I feel very happy with the product",
    "This product is a waste of money",
    "The quality meets my expectations",
    "Worst purchase I've made this year"
]

# 循环处理每条文本
for idx, text in enumerate(texts, start=1):
    # 编码文本(和单条预测的编码逻辑一致)
    encoded_input = np.array([tokenizer.encode(text)])
    # 预测概率
    prob_result = Dcnn(encoded_input, training=False).numpy()
    # 从二维数组中提取具体概率值
    positive_prob = prob_result[0][0]
    # 按照要求格式化输出,保留4位小数
    print(f'Text {idx}: "{text}" ; prob: {positive_prob:.4f}')

批量优化实现(适合大量文本)

如果待处理文本数量较多,建议一次性编码所有文本后批量预测,减少模型调用次数提升效率:

import numpy as np

texts = [
    "I feel very happy with the product",
    "This product is a waste of money",
    "The quality meets my expectations",
    "Worst purchase I've made this year"
]

# 批量编码所有文本
batch_encoded = np.array([tokenizer.encode(text) for text in texts])
# 批量预测所有文本的概率
batch_probs = Dcnn(batch_encoded, training=False).numpy()

# 遍历输出结果
for idx, (text, prob) in enumerate(zip(texts, batch_probs.flatten()), start=1):
    print(f'Text {idx}: "{text}" ; prob: {prob:.4f}')

关键说明

  • enumerate(..., start=1)用来生成从1开始的文本序号,匹配你要的格式
  • prob_result[0][0]或batch_probs.flatten()是为了把模型输出的二维数组(如array([[0.9083]]))转换成单个浮点数
  • {prob:.4f}用来格式化概率值,保留4位小数,和示例格式统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:20:44