对于两个rdd函数的理解及python3不能使用
第一个:
def get_mapping(rdd,idx):
return rdd.map(lambda fields:fields[idx])
.distinct().zipWithIndex().collectAsMap()
定义了一个映射函数,首先将idx列的特征值去重,然后对每个值使用zipWithIndex()映射到一个唯一的索引。键是变量,值是索引
即将该段不重复的数据进行编号
collectAsMap()将其转换为字典形式
例如:
原始数据:[‘4’, ‘1’, ‘3’, ‘2’]
经过上述函数转换后
get_mapping(records,2)
结果:
mapping of first categorical feature column:{‘4’: 0, ‘1’: 1, ‘3’: 2, ‘2’: 3}
第二个:
def extract_features(record):
cat_vec=np.zeros(cat_len) #初始化一个类别变量长度的零矩阵
i=0
step=0
for field in record[2:9]:
m=mappings[i]
idx=m[field]
cat_vec[idx+step]=1
i=i+1
step=step+len(m)
num_vec=np.array([float(field) for field in record[10:14]])
return np.concatenate((cat_vec,num_vec))
对于m=mappings[i]
mappings=[get_mapping(records,i)for i in range(2,10)] 返回结果是:
[{‘1’: 1, ‘2’: 3, ‘3’: 2, ‘4’: 0},{‘0’: 0,
‘1’: 1},
{‘1’: 6, ‘10’: 0,‘11’: 10, ‘12’: 7, ‘2’: 4,
‘3’: 3,‘4’: 1, ‘5’: 2,‘6’: 11,‘7’: 5,‘8’: 8,‘9’: 9},
{‘0’: 6,‘1’: 16,‘10’: 0,‘11’: 10,‘12’: 18,‘13’: 15,‘14’: 2,
‘15’: 17,‘16’: 9,‘17’: 7,‘18’: 1,‘19’: 11,‘2’: 4,‘20’: 22,
‘21’: 21,‘22’: 14,‘23’: 19,‘3’: 13,‘4’: 12,‘5’: 3,‘6’: 23,
‘7’: 5,‘8’: 8,‘9’: 20},
{‘0’: 0, ‘1’: 1},
{‘0’: 5, ‘1’: 1, ‘2’: 4, ‘3’: 3, ‘4’: 0, ‘5’:2, ‘6’: 6},
{‘0’: 0, ‘1’: 1},
{‘1’: 1, ‘2’: 3, ‘3’: 2, ‘4’: 0}]
这段代码的作用是对类别变量做one-hot编码变化,将数值变量进行float类型转换
第三个:
Python 3 的lambda 不能对元组进行操作
mse = true_vs_predicted.map(lambda n,q: squared_error(n, q)).mean() #n,q是一个元组的两个元素(n,q)
这种语法在python3中是错误,改成下面的形式就ok了
mse = true_vs_predicted.map(lambda x: squared_error(x[0], x[1])).mean()
第四个:
spark.ml 和spark.millb 的比较