您的位置:首页 > 其它

白手起家学习数据科学 ——可视化数据(一)

2015-11-23 11:27 363 查看
有许多库、框架以及模块能够很好的做数据科学,但是他们的确在没有理解数据科学的情况下也能很好的投入到本学科,但是在这里,你将白手起家学习到大多数数据科学的基本原理和算法以及他们如何用Python来实现的。

本系列主要的内容来自《Data Science from ScratchFIRST PRINCIPLES WITH PYTHON》以及个人的理解,如果有个别地方理解错误,请各位同学加以指正。 —— [ 下载地址 ]。

第一部分为Python语言基础,我们在这里使用Python语言进行讲解,如果有没有接触过Python的同学,可以参考本书的第一部分,在这里不在赘述。

数据科学家的工具包中基本部分就是数据可视化。虽然它是很容易创建,但是很难做好数据可视化。

-探索数据

-数据通讯

在这部分,我们将要关注建立探索自己的数据并且进行可视化的技能,在以后的系列中我们会使用这部分的内容,数据可视化是一个非常丰富的领域并且完全可以写成一本书籍。

matplotlib

有各种各样的数据可视化工具,我们会使用matplotlib,因为它被广泛的使用,它能产生简单的柱状图、折线图、以及散射图。尤其我们会使用matplotlib.pyplot模块。例如下面的代码:

from matplotlib import pyplot as plt

years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]

# create a line chart, years on x-axis, gdp on y-axis
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')

# add a title
plt.title("Nominal GDP")

# add a label to the y-axis
plt.ylabel("Billions of $")
plt.show()




排版让做图更复杂,超越了本文的范畴,可以利用axis label、line styles以及point markers定制自己的图表。

Bar Charts

当你想要显示一些变量的条目时柱状图是一个不错的选择,下面显示的是每个电影获得多少奖项:

movies = ["Annie Hall", "Ben-Hur", "Casablanca", "Gandhi", "West Side Story"]
num_oscars = [5, 11, 3, 8, 10]

# bars are by default width 0.8, so we'll add 0.1 to the left coordinates
# so that each bar is centered
xs = [i + 0.1 for i, _ in enumerate(movies)]

# plot bars with left x-coordinates [xs], heights [num_oscars]
plt.bar(xs, num_oscars)
plt.ylabel("# of Academy Awards")
plt.title("My Favorite Movies")

# label x-axis with movie names at bar centers
plt.xticks([i + 0.5 for i, _ in enumerate(movies)], movies)
plt.show()




为了探索某一变量数值是怎样分布的,使用柱状图也是画直方图不错的选择:

grades = [83,95,91,87,70,0,85,82,100,67,73,77,0]
decile = lambda grade: grade // 10 * 10
histogram = Counter(decile(grade) for grade in grades)

plt.bar([x - 4 for x in histogram.keys()], # shift each bar to the left by 4
histogram.values(),                        # give each bar its correct height
8)                                         # give each bar a width of 8

plt.axis([-5, 105, 0, 5])                  # x-axis from -5 to 105,

# y-axis from 0 to 5
plt.xticks([10 * i for i in range(11)])    # x-axis labels at 0, 10, ..., 100
plt.xlabel("Decile")
plt.ylabel("# of Students")
plt.title("Distribution of Exam 1 Grades")
plt.show()




plt.axis表示x轴范围-5到105,y轴范围为0到5, plt.xticks设置x轴标签为0,10,20,…,100.

当创建一个柱状图y轴不是从0作为起点是一个不好的形式,因为那很容易误导人们。

mentions = [500, 505]
years = [2013, 2014]

plt.bar([2012.6, 2013.6], mentions, 0.8)
plt.xticks(years)
plt.ylabel("# of times I heard someone say 'data science'")

# if you don't do this, matplotlib will label the x-axis 0, 1
# and then add a +2.013e3 off in the corner (bad matplotlib!)
plt.ticklabel_format(useOffset=False)

# misleading y-axis only shows the part above 500
plt.axis([2012.5,2014.5,499,506])
plt.title("Look at the 'Huge' Increase!")
plt.show()




我们使用更加明智的y轴:

plt.axis([2012.5,2014.5,0,550])
plt.title("Not So Huge Anymore")
plt.show()




折线图

正如我们已经画的图,我们能使用plt.plot()画折线图,这是显示趋势很好的选择:

variance = [1, 2, 4, 8, 16, 32, 64, 128, 256]
bias_squared = [256, 128, 64, 32, 16, 8, 4, 2, 1]
total_error = [x + y for x, y in zip(variance, bias_squared)]
xs = [i for i, _ in enumerate(variance)]

# we can make multiple calls to plt.plot
# to show multiple series on the same chart
plt.plot(xs, variance, 'g-', label='variance') # green solid line
plt.plot(xs, bias_squared, 'r-.', label='bias^2') # red dot-dashed line
plt.plot(xs, total_error, 'b:', label='total error') # blue dotted line

# because we've assigned labels to each series
# we can get a legend for free
# loc=9 means "top center"
plt.legend(loc=9)
plt.xlabel("model complexity")
plt.title("The Bias-Variance Tradeoff")
plt.show()




散射图

散射图是可视化数据集中两个变量关系的正确选择。例如下图阐述的是用户好友数量与用户每天花费上网时间的关系:

friends = [ 70, 65, 72, 63, 71, 64, 60, 64, 67]
minutes = [175, 170, 205, 120, 220, 130, 105, 145, 190]
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

plt.scatter(friends, minutes)

# label each point
for label, friend_count, minute_count in zip(labels, friends, minutes):
plt.annotate(label,
xy=(friend_count, minute_count), # put the label with its point
xytext=(5, -5), # but slightly offset
textcoords='offset points')

plt.title("Daily Minutes vs. Number of Friends")
plt.xlabel("# of friends")
plt.ylabel("daily minutes spent on the site")
plt.show()




如果你想比较两个变量并且选择如下图的plt.axis横纵坐标范围,你可能会得到一副误导图表(看不出两变量的关系):

test_1_grades = [ 99, 90, 85, 97, 80]
test_2_grades = [100, 85, 60, 90, 70]

plt.scatter(test_1_grades, test_2_grades)
plt.title("Axes Aren't Comparable")
plt.xlabel("test 1 grade")
plt.ylabel("test 2 grade")
plt.show()




如果我们调用plt.axis(“equal”),那么图表能够精确反应两变量之间的关系。



这节内容足够让我们开启数据可视化的世界,我们会在接下来的内容中接触更多关于数据可视化的内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: