机器学习K-Means使用报错TypeError: unsupported operand type(s) for -: 'map' and 'map'

最近使用kmeans做一个二维数据点的聚类,发现网上的代码,要么是自己写的,各种报错,连个txt文件都读取出错,当然这里不排除可能有python版本的原因,要么是sklearn进行调包的,当然这一点,也可以去网上找到一堆例子,但是很少讲很详细的,能够拿来即用的。本文便是使用网上某博客的代码,是手写的,但是会报这个错TypeError: unsupported operand type(s) for -: 'map' and 'map',以及对应的解决办法。

TypeError: unsupported operand type(s) for -: ‘map’ and ‘map’
书中源代码如下:

from numpy import *
def loadDataSet(fileName):
    dataMat = []
    fr = open(fileName)
    for line in fr.readlines():
        curLine = line.strip().split('\t')
		fltLine = map(float, curLine)
        dataMat.append(fltLine)
    return dataMat
    
def distEclud(vecA, vecB):
    return sqrt(sum(power(vecA - vecB, 2))) 
     
def randCent(dataSet, k):
    n = shape(dataSet)[1]
    centroids = mat(zeros((k, n)))
    for j in range(n):
        minJ = min(dataSet[:, j])
        rangeJ = float(max(dataSet[:, j]) - minJ)
        centroids[:, j] = minJ + rangeJ * random.rand(k, 1)
    return centroids

按照书中敲入代码kmeans.randCent(dataSet, 2)出现错误如下:

TypeError: unsupported operand type(s) for -: 'map' and 'map'

rangeJ = float(max(dataSet[:, j]) - minJ)相减的是两个map类型的数据,经过查找,发现fltLine = map(float, curLine)在python2中返回的是一个list类型数据,而在python3中该语句返回的是一个map类型的数据。
因此,我们只需要将该语句改为fltLine = list(map(float, curLine)),错误就解决啦。

还可能报另外一种错:ValueError: could not convert string to float

错误:

ValueError: could not convert string to float

出错的地方为:

month_diff = int(float(date_consumed[-6:-4])) - int(float(date_received[-6:-4])),这一句包含在函数get_time_diff中

我的目的是提取两个时间字符串里面的月份,然后计算月份差

出错的原因:

date_consumed或者date_received中含有空的字符串,

改正方式:

我在这里本意是将date_consumed和date_received中空的字符串去除,但是后来将这两个打印出来发现它们为空时用'nan'来表示了

frame = pd.Series(list(map(lambda x, y, z: 1. if x != 'null' and y != 'null' and z != 'null'and get_time_diff(z, y) <= 15 else 0., df[coupon_label], df[date_consumed_label], df[date_received_label])))

最终我将上面这句改成下面这句:

frame = pd.Series(list(map(lambda x, y, z: 1. if x != 'nan' and y != 'nan' and z != 'nan'and get_time_diff(z, y) <= 15 else 0., df[coupon_label], df[date_consumed_label], df[date_received_label])))

程序正常运行了!

更多参考:

https://blog.csdn.net/wb453178064/article/details/53535518

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值