【问题标题】:TypeError: array(['cycling'], dtype=object) is not JSON serializableTypeError: array(['cycling'], dtype=object) 不是 JSON 可序列化的
【发布时间】:2018-04-19 18:44:00
【问题描述】:

嗨,我已经制作了一个文本分类分类器,我在此使用它返回一个数组,我想返回 jsonresponse,但最后一行代码给了我错误 'array(['cycling'], dtype =object) 不是 JSON 可序列化的'

def classify_text(request):
    if request.method == 'POST' and request.POST.get('text'):
        test = []
        text = request.POST.get('text')
        text = re.sub('[^a-zA-Z]', ' ', text)
        text = text.lower()
        text = text.split()
        ps = PorterStemmer()
        text = [ps.stem(word) for word in text if not word in set(stopwords.words('english'))]
        text = ' '.join(text)
        test.append(text)

        pred = cv.transform(test).toarray()
        pred = svm_model_linear.predict(pred)
        return JsonResponse(pred, safe=False)

【问题讨论】:

  • 请代替奉献给我答案
  • pred 的类型是什么?
  • 它保存了分类器“'pred= ['cycling']”的预测
  • 它是一个numpy数组对象吗?
  • 我认为方法svn_model_linear.predict返回一个numpy数组对象。

标签: python json django serialization machine-learning


【解决方案1】:

您需要将numpy array 转换为list 对象,这可以使用numpy 数组对象上的.tolist() 方法轻松完成。

示例

pred_list = pred.tolist()
return JsonResponse(pred_list, safe=False)

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2019-02-08
    相关资源
    最近更新 更多