# spark | spark 机器学习chapter3 数据的获取、处理与准备

unzip ml-100k.zip
cd ml-100k

２、查看上述三种数据

３、启动python，分析数据

/home/hadoop/spark/bin/pyspark

４、读数据

from pyspark import SparkContext
user_data = sc.textFile("u.user")
user_data.first()

u’1|24|M|technician|85711’

５、基本的分析

＃分割数据，函数split
user_fields=user_data.map(lambda line:line.split("|"))
#用户数量
num_users=user_fields.map(lambda fields:fields[0]).count()
＃性别数
num_genders = user_fields.map(lambda fields:fields[2]).distinct().count()
＃职业种数
num_occupations = user_fields.map(lambda fields:fields[3]).distinct().count()
＃其他
num_zipcodes=user_fields.map(lambda fields:fields[4]).distinct().count()

＃结果打印
print "Users:%d ,genders:%d ,occupations:%d ,ZIP codes:%d" % (num_users,num_genders,num_occupations,num_zipcodes)

Users:943 ,genders:2 ,occupations:21 ,ZIP codes:795

6、画图 对ages这个属性做直方图。 由于在终端下没法画图，这里给出代码

ages = user_fields.map(lambda x: int(x[1])).collect()
hist(ages, bins=20, color='lightblue', normed=True)
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(16, 10)

７、统计职业的种类和数量

import numpy as np
count_by_occupation = user_fields.map(lambda fields:(fields[3],1)).reduceByKey(lambda x,y:x+y).collect()

x_axis1 = np.array([c[0] for c in count_by_occupation])
y_axis1 = np.array([c[1] for c in count_by_occupation])

print x_axis1

[u’administrator’ u’retired’ u’lawyer’ u’none’ u’student’ u’technician’ u’programmer’ u’salesman’ u’homemaker’ u’executive’ u’doctor’ u’entertainment’ u’marketing’ u’writer’ u’scientist’ u’educator’ u’healthcare’ u’librarian’ u’artist’ u’other’ u’engineer’]

print y_axis1

[ 79 14 12 9 196 27 66 12 7 32 7 18 26 45 31 95 16 51 28 105 67]

y_axis = y_axis1[np.argsort(y_axis1)]

array([ 7, 7, 9, 12, 12, 14, 16, 18, 26, 27, 28, 31, 32, 45, 51, 66, 67, 79, 95, 105, 196])

np.argsort() : 得到升序的下标

pos = np.arange(len(x_axis))
width = 1.0

ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(x_axis)
plt.bar(pos, y_axis, width, color='lightblue')
plt.xticks(rotation=30)
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(16, 10)

count_by_occupation2 = user_fields.map(lambda fields: fields[3]).countByValue()
print "Map-reduce approach:"
print dict(count_by_occupation2)
print ""
print "countByValue approach:"
print dict(count_by_occupation)

Map-reduce approach print(dict(count_by_occupation2)) {u’administrator’: 79, u’retired’: 14, u’lawyer’: 12, u’healthcare’: 16, u’marketing’: 26, u’executive’: 32, u’scientist’: 31, u’student’: 196, u’technician’: 27, u’librarian’: 51, u’programmer’: 66, u’salesman’: 12, u’homemaker’: 7, u’engineer’: 67, u’none’: 9, u’doctor’: 7, u’writer’: 45, u’entertainment’: 18, u’other’: 105, u’educator’: 95, u’artist’: 28}

countByValue approach {u’administrator’: 79, u’writer’: 45, u’retired’: 14, u’lawyer’: 12, u’doctor’: 7, u’marketing’: 26, u’executive’: 32, u’none’: 9, u’entertainment’: 18, u’healthcare’: 16, u’scientist’: 31, u’student’: 196, u’educator’: 95, u’technician’: 27, u’librarian’: 51, u’programmer’: 66, u’artist’: 28, u’salesman’: 12, u’other’: 105, u’homemaker’: 7, u’engineer’: 67}

movie_data = sc.textFile("u.item")

＃第一行
print movie_data.first()

1|Toy Story (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)|0|0|0|1|1|1|0|0|0|0|0|0|0|0|0|0|0|0|0

print "Movies:%d" % num_movies

Movies:1682

def convert_year(x):
try:
return int(x[-4:])
except:
return 1900 

movie_fields = movie_data.map(lambda lines: lines.split("|"))

years = movie_fields.map(lambda fields: fields[2]).map(lambda x: convert_year(x))

years_filtered = years.filter(lambda x: x != 1900)

movie_ages = years_filtered.map(lambda yr: 1998-yr).countByValue()
values = movie_ages.values()
bins = movie_ages.keys()

print values
print bins

[65, 286, 355, 219, 214, 126, 37, 22, 24, 15, 11, 13, 15, 7, 8, 5, 13, 12, 8, 9, 4, 4, 5, 6, 8, 4, 3, 7, 3, 4, 6, 5, 2, 5, 2, 6, 5, 3, 5, 4, 9, 8, 4, 5, 7, 2, 3, 5, 7, 4, 3, 5, 5, 4, 5, 4, 2, 5, 8, 7, 3, 4, 2, 4, 4, 2, 1, 1, 1, 1, 1]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 72, 76]

hist(values, bins=bins, color='lightblue', normed=True)
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(16,10)

>>> #评级数据
...
rating_data = sc.textFile("u.data")
print rating_data.first()
196 242 3   881250949
num_ratings = rating_data.count()
print "Ratings: %d" % num_ratings
Ratings: 100000

196 242 3 881250949 Ratings: 100000 总共10万条数据

#数据分割
rating_data1 = rating_data.map(lambda line:line.split("\t"))
#评分
ratings = rating_data1.map(lambda fields:int(fields[2]))
#最高得分
max_rating = ratings.reduce(lambda x,y:max(x,y))
#最低得分
min_rating = ratings.reduce(lambda x,y:min(x,y))
#评价得分
mean_rating = ratings.reduce(lambda x,y:x+y) / num_ratings
#中位数
median_rating = np.median(ratings.collect())
#平均每个用户打分数
ratings_per_user = num_ratings / num_users
＃平均每部电影有多少评分
ratings_per_movie = num_ratings / num_movies
print "Min ratings: %d" % min_rating
print "Max rating: %d" % max_rating
print "Average rating: %2.2f" % mean_rating
print "Median rating: %d" % median_rating
print "Average # of rating per user:%2.2f" % ratings_per_user
print "Average # of ratings per movie: %2.2f" % ratings_per_movie

Min ratings: 1 Max rating: 5 Average rating: 3.00 Median rating: 4 Average # of rating per user:106.00 Average # of ratings per movie: 59.00

ratings.stats()

(count: 100000, mean: 3.52986, stdev: 1.12566797076, max: 5.0, min: 1.0)

user_ratings_grouped = rating_data.map(lambda fields:(int(fields[0]),int(fields[2]))).groupByKey()

user_ratings_byuser = user_ratings_grouped.map(lambda (k,v):(k,int(len(v))))

user_ratings_byuser.take(5)　　＃这里在spark2.1下报错，后续探究

user_ratings_byuser_local = user_ratings_byuser.map(lambda (k, v): v).collect()
hist(user_ratings_byuser_local, bins=200, color='lightblue', normed=True)
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(16,10)

0 条评论

• ### 两数之和 (一)

[[1, 3, [0, 14]], [1, 3, [1, 13]], [1, 3, [2, 12]], [1, 3, [3, 11]], [2, 2, [4, ...

• ### json介绍

skipkeys默认为False，如果为True，当字典的key不是str, int, float, bool, None类型时，将会跳过，而不会抱错。否则，为...

• ### spark | 做基本计算和批量提交

结果： Total purchases: 5 Unique users: 4 Total revenue: 39.91 Most popular...

• ### patch命令

patch指令让用户利用设置修补文件的方式、修改、更新原始文件，倘若一次仅修改一个文件，可直接在指令列中下达指令依序执行，如果配合修补文件的方式则能一次修补大批...

• ### Wiztalk第三场：鉴别真话假话，人工智能终于也能行了

6月23日晚19:00，我们将邀请清华大学计算机副教授、博士生导师刘知远和清华大学计算机系硕士生周界进行主题为“基于图结构的事实验证”的Wiztalk腾讯广告...

• ### 热门数据分析面试题。

Sql中有一类函数叫聚合函数，比如count、sum、avg、min、max等，这些函数的可以将多行数据按照规整聚集为一行，一般聚集前的数据行要大于聚集后的数据...

• ### 3道TMD热门数据分析面试题，我们帮你解了

导读：本文通过几道TMD面试题介绍一下如何使用窗口函数。涉及知识点有用于排序的窗口函数、用于用户分组查询的窗口函数、用于偏移分析的窗口函数，每种会通过一道面试题...

• ### 一些关于并行计算的科研思路

最近想要找点新的点子来优化之前看到的一些立体匹配论文，我之前一直是用图割做立体匹配，刚开始时候用图割做图像分割，后来发现这块都被人做烂了，继续往下看发现...

• ### 腾讯云专家工程师廖龙：CDN边缘智能助力5G

10月19日，云+社区开发者大会（北京站）圆满落幕。本次开发者大会的主题为“5G探索：核心技术与挑战”，邀请了腾讯内部及业内行业大咖就5G场景下应该如何面对新业...