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

匿名 (未验证) 提交于 2019-12-03 00:11:01

最近使用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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!