优达(Udacity)-机器学习基础-数据集与问题(安然数据集)

课程全部代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
""" 
    Starter code for exploring the Enron dataset (emails + finances);
    loads up the dataset (pickled dict of dicts).

    The dataset has the form:
    enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict }

    {features_dict} is a dictionary of features associated with that person.
    You should explore features_dict as part of the mini-project,
    but here's an example to get you started:

    enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000

"""

import pickle

enron_data = pickle.load(open("../final_project/final_project_dataset.pkl", "r"))

#数据集中有多少数据点(人)?
print(len(enron_data))

#对于每个人,有多少个特征可用?
print(len(enron_data["SKILLING JEFFREY K"]))

#在安然数据中查找 POI(也就是说,计算 data[person_name]["poi"]==1 时,字典中条目的数量。)
print (len(dict ((key,value) for key,value in enron_data.items() if value["poi"] == True)))

#存在多少 POI?
poi_reader =open("../final_project/poi_names.txt", "r")
fr=poi_reader.readlines();
print(len(fr[2:])) 
poi_reader.close()

#和任何字典一样,个人特征可以通过以下代码访问:
#enron_data["LASTNAME FIRSTNAME"]["feature_name"]
#或者 
#enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"]["feature_name"]

#James Prentice 名下的股票总值是多少?
print(enron_data["PRENTICE JAMES"]["total_stock_value"])

#我们有多少来自 Wesley Colwell 的发给嫌疑人的电子邮件?
print(enron_data["COLWELL WESLEY"]["from_this_person_to_poi"])

#Jeffrey Skilling 行使的股票期权价值是多少?
print(enron_data["SKILLING JEFFREY K"]["exercised_stock_options"])

#这三个人(Lay、Skilling 和 Fastow)当中,谁拿回家的钱最多(“total_payments”特征的最大值)?
#这个人得到了多少钱?

people=["LAY KENNETH L","SKILLING JEFFREY K","FASTOW ANDREW S"]
money = 0
who = ""
for i in people:
    if money < enron_data[i]["total_payments"]:
        money = enron_data[i]["total_payments"]
        who = i
print(money,who)

#此数据集中有多少雇员有量化的工资?已知的邮箱地址是否可用?
count_salary,count_email = 0,0
for i in enron_data:
    if enron_data[i]["salary"] !="NaN":
        count_salary += 1;
    if enron_data[i]["email_address"]!="NaN":
        count_email += 1;
print(count_salary,count_email)

#(当前的)E+F 数据集中有多少人的薪酬总额被设置了“NaN”?数据集中这些人的比例占多少?
count_totalpay=0
for i in enron_data:
    if enron_data[i]["total_payments"]=="NaN":
        count_totalpay += 1;
#这里要用float,不然会得到整型0
print(count_totalpay,count_totalpay/float(146))

#E+F 数据集中有多少 POI 的薪酬总额被设置了“NaN”?这些 POI 占多少比例?
count_totalpoi=0
poi_num=0
for i in enron_data:
    if enron_data[i]["poi"]==True:
        poi_num+=1
        if enron_data[i]["total_payments"]=="NaN":
            count_totalpoi += 1
print(poi_num,count_totalpoi/float(poi_num))

#POI 中,股票总值为“NaN”的人数变成了多少?
count_t_s_v=0
for i in enron_data:
    if enron_data[i]["poi"]==True:
        if enron_data[i]["total_stock_value"]=="NaN":
            count_t_s_v += 1
print(count_t_s_v)

用到的资料补充:

python2对于中文的处理能力很弱,所以使用中文注解的时候会报错
这里写图片描述

这里写图片描述

解决方案:
在.py文件前加编码注释, 选用utf-8编码即可使用中文.

# -*- coding: utf-8 -*-

附上用到的一些python方法:

  • dict.items( )
    Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

    实例:

#!/usr/bin/python
# coding=utf-8

dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}

print "字典值 : %s" %  dict.items()

# 遍历字典列表
for key,values in  dict.items():
    print key,values

输出:

字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
  • pickle.load(file)

只有一个参数 file ,对应于上面 dump 方法中的 file 参数。这个 file 必须是一个拥有一个能接收一个整数为参数的 read() 方法以及一个不接收任何参数的 readline() 方法,并且这两个方法的返回值都应该是字符串。这可以是一个打开为读的文件对象、StringIO 对象或其他任何满足条件的对象。

实例:

# -*- coding: utf-8 -*-

import pickle
# 也可以这样:
# import cPickle as pickle

obj = {"a": 1, "b": 2, "c": 3}

# 将 obj 持久化保存到文件 tmp.txt 中
pickle.dump(obj, open("tmp.txt", "w"))

# do something else ...

# 从 tmp.txt 中读取并恢复 obj 对象
obj2 = pickle.load(open("tmp.txt", "r"))

print obj2
  • Python File readlines() 方法

    readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for… in … 结构进行处理。
    如果碰到结束符 EOF 则返回空字符串。

语法: fileObject.readlines( );

实例:
文件数据:

1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com

代码(循环读取文件内容)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("runoob.txt", "r")
print "文件名为: ", fo.name

for line in fo.readlines():                          #依次读取每行  
    line = line.strip()                             #去掉每行头尾空白  
    print "读取的数据为: %s" % (line)

# 关闭文件
fo.close()

输出结果:

文件名为:  runoob.txt
读取的数据为: 1:www.runoob.com
读取的数据为: 2:www.runoob.com
读取的数据为: 3:www.runoob.com
读取的数据为: 4:www.runoob.com
读取的数据为: 5:www.runoob.com
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐