- 参考spark机器学习,稍微加些自己的操作
- 基于pycharm进行开发,pyspark安装见上篇博文
- 数据集包含的字段为:id,年龄,性别,职业,邮编
- 数据集连接在:http://files.grouplens.org/datasets/movielens/ml-100k.zip
- 涉及的计算函数包含:
- textFile
- count
- first
- map
- reduce
- distinct
- reduceByKey
- countByValue
from pyspark import SparkContext,SparkConf
#
conf = SparkConf().setAppName("test").setMaster("local")
sc = SparkContext(conf=conf)
# 读取文件
data=sc.textFile("/Users/hqh/pycharm/机器学习/pyspark/ml-100k/u.user")
# 统计总的记录数
print(data.count())
# 观察第一条数据
print(data.first()) # 分别对应 id,年龄,性别,职业,邮编
# 统计其中一个字段的职业的去重数量
print(data.map(lambda x:x.split("|")[3]).distinct().count())
# 分布图
import matplotlib.pyplot as plt
ages=data.map(lambda x:int(x.split("|")[1])).collect()
plt.hist(ages,bins=20,color='blue',density=True) # density参数表示y轴显示的为占比
plt.show()
# 职业分布情况
zydist=data.map(lambda x:x.split("|")[3]).map(lambda x:(x,1)).reduceByKey(lambda x,y:x+y).collect()
print(zydist) # 返回的是一个list,里面的元素为tuple
## 直接使用countByValue,
zydist1=data.map(lambda x:x.split("|")[3]).countByValue()
print(dict(zydist1)) # 返回的是一个dict
- 涉及函数
- groupByKey
- reduceByKey
- sortBy
- Udf的使用
# 自定义函数并转换
ts=data.map(lambda x:int(x.split("\t")[3]))
import datetime
def format_ts(ts):
'''
将时间戳格式化,并根据小时,转化为上午,中午,下午,晚上
:param ts:
:return:
'''
temp=datetime.datetime.fromtimestamp(ts)
if temp.hour in range(1,10):
return "早上"
elif temp.hour in range(10,14):
return "中午"
elif temp.hour in range(14,18):
return "下午"
else:
return "晚上"
ts=ts.map(lambda x:format_ts(x))
print(ts.collect())
- 涉及函数
- zipWithIndex 词与下标的映射关系
- collectAsMap 返回一个dict
import jieba
test=["我的名字叫做推推","我出身在浙江温州","我是硕士学历"]
test=sc.parallelize(test,2)
def conv2index(text):
return list(jieba.cut(text))
# 建立词的字典
res=test.flatMap(lambda x:conv2index(x)).zipWithIndex().collectAsMap()
print(res)
- 正则化-Normalizer
from pyspark.mllib.feature import Normalizer
seq=sc.parallelize([range(1,11)],2)
normalizer=Normalizer()
print(normalizer.transform(seq).collect())
#[DenseVector([0.051, 0.1019, 0.1529, 0.2039, 0.2548, 0.3058, 0.3568, 0.4077, 0.4587, 0.5096])]