TypeError: ufunc ‘multiply‘ did not contain a loop with signature matching types dtype(‘<U32‘) dtype

from numpy import *
import operator


def createDataSet():
    group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels


# print(createDataSet())

def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    sortedDistIndicies = distances.argsort()
    classCount = {}
    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
    sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


# print(classify0([0,0],array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]]), ['A', 'A', 'B', 'B'], 3 ))

def file2matrix(filename):
    fr = open(filename)
    arrayOlines = fr.readlines()
    numberOfLines = len(arrayOlines)  # 文件行数
    returnMat = zeros((numberOfLines, 3))  # 初始化数组
    classsLabelVector = []
    index = 0
    for line in arrayOlines:
        line = line.strip()  # 去掉回车字符
        listFromLine = line.split('\t')
        returnMat[index, :] = listFromLine[0:3]
        classsLabelVector.append(listFromLine[-1])
        index += 1
    return returnMat, classsLabelVector


dataMat, dataLabels = file2matrix('data\datingTestSet.txt')

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
# print(dataMat[:,1])

# ax.scatter(dataMat[:, 1], dataMat[:, 2])
ax.scatter(dataMat[:, 1], dataMat[:, 2], 15.0 * array(dataLabels), 15.0 * array(dataLabels))
plt.show()

在这里插入图片描述
在这里插入图片描述
K近邻算法调试碰到TypeError: ufunc ‘multiply’ did not contain a loop with signature matching types dtype(’<U32’) dtype 问题,原因:

  1. 代码classsLabelVector.append(listFromLine[-1])
    在返回类型时返回的是字符串数组 不是整形数组
    ax.scatter(dataMat[:, 1], dataMat[:, 2], 15.0 * array(dataLabels), 15.0 * array(dataLabels))
    此处需要整型数组
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值