第一個:
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 的比較