首页 > 解决方案 > “类型错误只有大小为 1 的数组可以转换为 Python 标量”

问题描述

def eval(self, knn_k=-1,Kpca=-1):
        if knn_k <= 0:
            knn_k = self.knn
        knn_k += 1  # exclude itself
        if Kpca<0:
            Kpca = self.K
        responses = []
        for name,img,label in self.image_dictionary:
            responses.append(label)

        knn = cv2.ml.KNearest_create()
        knn.train(self.weightTraining[0:Kpca,:].T.astype(np.float32), np.asarray(responses, dtype=np.float32))
        # we have to discard the first predict result, since it has to be itself
        ret, results, neighbours2 ,dist = knn.find_nearest(self.weightTraining[0:Kpca,:].T.astype(np.float32), knn_k)
        neighbours = neighbours2[:,1:]
        eval_data = []
        for idx,nb in enumerate(neighbours):
            neighbours_count = []
            for n in nb:
                neighbours_count.append(nb.tolist().count(n))
            vote = nb[neighbours_count.index(max(neighbours_count))]
            eval_data.append((vote,responses[idx]))
            # print ("predict:%s, neight: %s, label: %d" % (str(vote),str(nb), responses[idx]))
        return eval_data

我有一个列表(响应)被传递给一个 numpy 数组,但是即使我有 np.asarray 将此列表转换为数组,我仍然会出错。有人可以帮忙吗?

标签: python

解决方案


推荐阅读