ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-09-25 21:00:25  阅读:560  来源: 互联网

标签:map TypeError float list dataSet operand 报错 date


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

程序正常运行了!

标签:map,TypeError,float,list,dataSet,operand,报错,date
来源: https://blog.csdn.net/edward_zcl/article/details/101384781

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有