嗨,我做了一个文本分类器,我已经在使用它了,它返回给我一个数组,而我想返回一个JSON响应,但是代码的最后一行出现了错误 ‘array([‘cycling’], dtype=object) is not JSON serializable’
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)
回答:
你需要将numpy array
转换为list
对象,这可以通过在numpy数组对象上使用.tolist()方法轻松实现。
示例:
pred_list = pred.tolist()return JsonResponse(pred_list, safe=False)