大数据处理知识点总结

一.Request库基础知识

方法说明返回对象
.request ()构造请求
.get()获取HTML网页,对应HTTP的GET返回的response对象包含服务器的所有资源
.head()获取网页头信息,对应HEAD
.post()提交POST请求
.put()提交PUT请求
.patch()提交局部修改请求,对应PATCH
.delete()提交删除请求,对应DELETE

在这里插入图片描述
爬取页面的通用框架:

try:
	r = requests.get(url,timeout = 30)
	r.raise_for_status()
	r.encoding = r.apparent_encoding
	return r.text
except:
	return "产生异常"

二.Lending Club贷款数据转换与融合

1.随机采样

loan.sample(frac=0.01)
loan.sample(n=10,replace=True)

n 指定数量,frac指定比例采样,axis可以指定列采样

2.数据融合

2.1 merge

left.merge(right,how='inner',on=None,left_on=None,right_on=None,left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), indicator=False)

举例:

# 基于用户信息数据的'user_id'变量和贷款交易数据的'user'变量进行外连接(outer)。
test_user.merge(test_loan,how="inner",left_on="user_id",right_on="user")

设定参数indicator参数为True,结果多了一列merge。

2.2 join

left.join(right, on=None, how='left', lsuffix='', rsuffix='', sort=False)

使用join更简介

data.sort_values(by='xxx')
data.sort_index(by='xxx')

ascending默认将缺失值排在最后

2.3 数据转换

object类型 先 str.strip(’%’),再pd.to_numeric(xxx)

3.变量离散化

annual_inc=pd.cut(combine.annual_inc,bins=[np.min(combine.annual_inc)-1,np.percentile(combine.annual_inc,50),np.max(combine.annual_inc)+1],labels=['low','high'])

bins参数设置分割点
qcut直接按频数划分

4.变量值替换

写法1:

combine['loan_status'].replace(to_replace=['Fully Paid','Current','Charged Off','In Grace Period','Late (31-120 days)'],value=[0,0,1,1,1],inplace=True)

写法2:

test_loan.replace(to_replace={'loan_status':{'Fully Paid':0,'Charged Off':0,'In Grace Period':1}}
# 也可以指定不同变量
test_loan.replace(to_replace={'loan_status':'Fully Paid','grade':'A'},value='Good')

map
只针对某一个series进行数值替代

test_loan['loan_status'].map({'Fully Paid':0,'Charged Off':0,'In Grace Period':1})

输入函数进行映射

combine['int_rate'][:5]
def f(x):
    if x < 12:
        return 'Low'
    else:
        return 'High'
combine['int_rate'][:5].map(f)

5.哑变量(虚拟变量)处理

需要进行处理的属性

cat_vars=['term','grade','emp_length','annual_inc','home_ownership','verification_stat us']

循环处理

for var in cat_vars:
	car_list = pd.get_dummies(combine[var],prefix=var,drop_first=True)
	combine = combine.join(cat_list)

drop_first设置为True将删去所获得哑变量的第一个,这是因为在建模中,有k类的分类变量只需要k-1个变量就可以将其描述,如果使用k个变量则会出现完全共线性的问题。

6.添加常数项列

const = pd.Series([1]*combine.shape[0],name='const')
X.reset_index(drop=True,inplace=True)
X=pd.concat([const,X],axis=1)
X.head()

join是DateFrame的方法,X.join(const)
concat的对象要是一个list

三.行星数据分组与聚合

1.数据分组

1.1 分组方式

特征分组

grouped = =planets.groupby('method')

array,list,series分组

a=np.repeat([0,1],[500,535])
planets.groupby(a).mean()

函数分组

new=plantes.set.index('year')
def test(x):
	if x<2000:
		return 'Before'2000
	else:
		return 'After 2000'
		
new.groupby(test).mean()
group_index=new.index.map(test)
new.groupby(group_index).mean()

1.2 分组应用

取出需要的列 grouped[‘year’]
查看不同方法下距离的中位数:

plants.groupby('method')['distance'].median()

年份变为对应年代

decade = 10 * (planets['year'] // 10)
decade = decade.astype(str) + 's'
decade[:5]

按方法和年代进行分组

plants.groupby(['method',decade])['number'].sum()

使用unstack将按层次化索引拆开为新的列索引并使用fillna将缺失值用0填充。

planets.groupby(['method', decade])['number'].sum().unstack().fillna(0)

2.分析行星数据

2.1GroupBy.apply

grouped.apply(lambda x:.....)
grouped.apply(func)

比较慢

2.2GroupBy.agg

分别计算各种方法发现的行星的距离的均值和发现的数量之和

grouped.agg({'distance':'mean','number':'sum'})
grouped.agg({'distance':['min','max','mean','median'],'number':'sum'})

也可以自定义函数
apply是对每一组数据整个DataFrame进行一次运算。
agg对每一组数据中的每一个特征进行运算。
①对每组数据中的每一列执行函数
②将每一列返回结果合并
③将每一组数据返回结果合并

2.3GroupBy.transform

使用transform实现分组数据标准化(分组数据维度相同的数据):

grouped.transform(lambda x:x(x-x.mean())/x.std()).head()

不能使用字典方式指定特征进行函数操作

四.德国能源数据时间序列分析

1.转化为时间序列

指定以日为频率

opsd['Date']=pd.to_datetime(opsd['Date'])
opsd=opsd.asfreg('D')

2.基于时间索引的操作

2.1 loc与truncate

获取时间范围

opsd.loc('2017-01-01':'2017-01-31')
opsd.truncate(before='2017-01-01',after='2017-01-31')

2.2 时间数据基本操作

年月日的选择

# 之前将索引设为日期
opsdtime=opsd.index
opsdtime.year
opsdtime.mounth.name()

月份和对应季节构建map

seasons=[1,1,2,2,2,3,3,3,4,4,4,1]
mouth_to_season=dict(zip(range(1,13),seasons))
opsd['season']=opsdtime.month.map(mouth_to_season)

2.3周期性分析

使用groupby按变量season分组/按星期分组,并计算每个季节的用电量均值

opsd.groupby('season')['Consumption'].mean()
opsd.groupby(lambda x:x.weekday)['Consumotion'].mean()

周期性不明显,使用resample对数据进行降采样

wind = opsd.loc['2012':'2018','Wind'].resample('M').mean()

消除数据趋势性 diff()
自行计算:将数据向后移一天shift(1),再两序列相减

dif=opsd['Solar']-opsd['Solar'].shift(1,freq='d')

滚动窗口
例如,设定窗口为7天,且以数据中心为基准点,则每一个数据对应的窗口将包含前面三天与后面三天。具体来看,2017-07-06对应的窗口就是2017-07-03到2017-07-09。

opsd.loc['2011':'2020','Wind'].rolling(window=365,min_periods=360).mean().plot(figsize=(12,6))

五.K-means算法

1.算法原理

给定样本集,事先确定簇数K,让簇内样本尽可能距离相近,簇间距离尽可能大
输入:样本集D,簇数K,最大迭代次数N
输出: 划分之后的簇
步骤
1.从样本中选K个样本作为初始聚类中心
2.对每个样本集中的样本
a.计算每个样本距离K个簇中心的距离
b.将每个点分配到距离最近的簇内
3.重新计算K个簇的中心点
4.重复2,3直到满足收敛性

2.特点

优点缺点
容易理解,聚类效果局部最优K值需要人为确定
处理大数据集伸缩性好对簇中心和异常值敏感
算法复杂度低不适合多分类任务,不适合太离散,样本类别不平衡,非凸形状分类

改进:采用核函数

3.实验操作

# %load kmeans.py

#导入模块
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt

#计算欧式距离
def eucDistance(vec1,vec2):
    return sqrt(sum(pow(vec2-vec1,2)))

#初始聚类中心选择
def initCentroids(dataSet,k):
    numSamples,dim = dataSet.shape
    centroids = np.zeros((k,dim))
    for i in range(k):
        index = int(np.random.uniform(0,numSamples))
        centroids[i,:] = dataSet[index,:]
    return centroids

#K-means聚类算法,迭代
def kmeanss(dataSet,k):
    numSamples = dataSet.shape[0]
    clusterAssement = np.mat(np.zeros((numSamples,2)))
    clusterChanged = True
    #  初始化聚类中心
    centroids = initCentroids(dataSet,k)
    while clusterChanged:
        clusterChanged = False
        for i in range(numSamples):
            minDist = 100000.0
            minIndex = 0
            # 找到哪个与哪个中心最近
            for j in range(k):
                distance = eucDistance(centroids[j,:],dataSet[i,:])
                if distance<minDist:
                    minDist = distance
                    minIndex = j
              # 更新簇
            clusterAssement[i,:] = minIndex,minDist**2
            if clusterAssement[i,0]!=minIndex:
                clusterChanged = True
         # 坐标均值更新簇中心
        for j in range(k):
            pointsInCluster = dataSet[np.nonzero(clusterAssement[:0].A==j)[0]]
            centroids[j,:] = np.mean(pointsInCluster,axis=0)
    print('Congratulations,cluster complete!')
    return centroids,clusterAssement

#聚类结果显示
def showCluster(dataSet,k,centroids,clusterAssement):
    numSamples,dim = dataSet.shape
    mark = ['or','ob','og','ok','^r','+r','<r','pr']
    if k>len(mark):
        print('Sorry!')
        return 1
    for i in np.xrange(numSamples):
        markIndex = int(clusterAssement[i,0])
        plt.plot(centroids[i,0],centroids[i,1],mark[i],markersize=12)
    plt.show()

六.逻辑回归

1.算法原理

线性回归是利用数理统计中回归分析,来确定两种或两种以上变量间相互依赖的定量关系的一种统计分析方法。
LR本质上还是线性回归,只是特征到结果的映射过程中加了一层函数映射,即sigmoid函数,即先把特征线性求和,然后使用sigmoid函数将线性和约束至(0,1)之间,结果值用于二分或回归预测。
逻辑回归是一种预测在不同的自变量情况下,发生某种情况的概率有多大的算法。
Logistic 回归的本质是:假设数据服从这个分布,然后使用极大似然估计做参数的估计。
输入变量与输出变量均为连续变量的预测问题是回归问题,输出变量为有限个离散变量的预测问题成为分类问题.

2.特点

优点缺点
预测结果是0-1之前的概率对多重共线性较为敏感
适用性强难以处理数据不平衡问题
适用与连续性和类别性变量准确率不高
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值