做论文股票期权会计研究研报,求关联规则挖掘方法在股票分析中的应用实例,一定要有python源代码,谢谢各位高手

机器学习在证券分析中的应用&-&Python版(续)
Life is Short, I Use Python
人生苦短,我用大蟒
看了卓金武老师的《数据挖掘技术与实践(MATLAB版)》让我决定以证券分析作为Python的学习方向.并且萌生了把此书中的实例用Python重写一遍的想法.结合TuShare的数据接口会让我的内容更具有实战性.更想以此向卓老师和TuShare的团队致敬.又从网上看到牛人"字王"计划出版一本专讲Python大数据与量化交易的书,拜读了大纲,顿觉高山仰止,惊为天人.我这浅陋的文字恐怕都不能博各位看官一笑了.
这是所有涉及数据挖掘必讲的案例和算法,但我惊讶地发现居然没有现成的Python库提供Apriori和FP-Growth算法的API.网上和书里都有源代码样本.就不在这里大段的盗版了
一种用来表示两个变量之间相关关系的数学方法(有别于函数关系,那是一种确定关系).我很怀疑对K线图之类的曲线用回归方法学习并预测是否有效.日期是价格的因变量吗?为了举例我还是把histd里的5日均线拿来回归一下.histd的数据获得请看前一篇博客了.需要注意把histd的date列转换成float
day格式.Numpy直接提供回归API,ployfit()是用来计算回归方程的系数,deg代表方程的次数,等于1就是一元线性回归;大于1就变成一元多次回归.
polyval()是用获得的回归系数算出每个x对应的y回归值
Reg = np.polyfit(hist['date'],
histd['ma5'], deg=1)
histd['regy1'] = np.polyval(reg,
histd['date'])
histd[['date',
'Regy1']].plot(figsize=(9, 6), grid=True, rot=30)
还可以选择用于回归的其他非线性基函数,需要创建一个矩阵,宽度取决于要引入函数的个数,长度取决于样本数据的长度,本例中是len(histd)
matrix = np.zeros((3+1,
len(histd)))
matrix[3, :] =
np.sin(histd['date'])&&
引入Sin函数
matrix[2, :] =
histd['date']**2&&
引入平方函数
matrix[1, :] = histd['date']
matrix[0, :] = 1
reg2 = np.linalg.lstsq(matrix.T,
histd['ma5'])[0]&&
用新构建的矩阵来计算回归系数
histd['regy2'] = np.dot(reg2,
histd[['ma5', 'regy2']].plot(figsize=(8,5), grid=True,
多元回归, 以二元变量x, y为例
创建一组基函数
matrix = np.zeros((len(histd),
matrix[:, 6] =
np.sqrt(y)& 引入平方根函数
matrix[:, 5] =
np.sin(x)&&
引入正弦函数
matrix[:, 4] = y **
引入平方函数
matrix[:, 3] = x **
引入平方函数
matrix[:, 2]
matrix[:, 1] = x
matrix[:, 0] = 1
调用statsmodels库提供的OLS函数计算回归系数
import statsmodels.api as
model = sm.OLS(fm((x, y)),
matrix).fit()
model.params
一直受困于如何简洁地从DataFrame里删除不需要的行.灵光一闪想到把不需要的值替换成'nan'再用dropna()一次性删除所有带nan的行.tick是TuShare的股票分时数据,经常有'--'这样的值,影响运算.做除法时要强制数据格式为float,可以用astype()
tick['change'].replace('--', np.nan,
inplace=True) &#把空值--替换成np.nan
tick.dropna(inplace=True)
& #用dropna把含有nan的行删除
tick['p_change'] =
tick['change'].astype(float) /
tick['price'].astype(float)
对指定股票在指定周期内,收集所有跳档买入的交易
'600839'&&&&
# 指定股票代码
ts.get_hist_data(code=ccode,
&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&
ktype='D',)&&&
#从TuShare下载该股票的历史数据,DataFrame
histd.sort_index(inplace=True)&&&
#按日期从远到近排序
histd.reset_index(inplace=True)&&&
#把日期从index转换成一个普通字段
histd['date']&&&
np.zeros(len(period))&&&&
#新建一个全零一维数组,长度和histd相同x =
#新建一个计数变量
for vdate in
histd['date']:&&&&&&&#对histd里的date列循环取值,
对取到的每一天进行如下循环
&&& tick =
ts.get_tick_data(code=ccode,
date=vdate)&&&&&
#根据日期读取该日分笔交易数据,DataFrame格式
if len(tick) &
添加对返回数据是否为空的判断
tick['change'].replace('--', np.nan,
inplace=True)&&&&
#把空值--替换成np.nan&&&&&&&
tick.dropna(inplace=True)&&&&&
#用dropna把含有nan的行删除&&&&&&&
tick['p_change'] = tick['change'].astype(float) /
tick['price'].astype(float)&&&&
#计算每笔交易价格变化率&&&&&&&
tick_filtered =
tick[(tick['type']=='买盘')&(tick['p_change']&0.003)]&&&&
#选出价格变化率大于0.003的买盘
&rate = tick_filtered['volume'].sum() /
tick['volume'].sum()&&&&&
#大变化率交易总量除以该日交易总量
r_array[x] = rate *
#所得比例乘以100以便显示,并存入数组相应日期的位置
print('Error on date', vdate)
r_array[x] =
#&计数变量加一
histd['jump'] =
r_array&&&
#把所得数组加到histd的最后一列,并对齐日期
histd['date'] =
pd.to_datetime(histd['date'])&&&&
# 把字符串格式的date转换成日期格式的date
histd['date'] =
mdt.date2num(histd['date'].astype(dt.date))&
#把日期格式的date转换成float格式用来画图
list(histd)&&&&
#提取Label List
collist.insert(2,
collist.pop(collist.index('low')))&&&&
#调整label次序histd = histd.ix[:,
collist]&&&&&&
#调整列的次序
np.array(histd)&&&&&&
#convert DataFrame to
Arrayfig, (ax1, ax2) = plt.subplots(2,
sharex=True, figsize=(12, 5))
fig.subplots_adjust(bottom=0.2)
mpf.candlestick_ohlc(ax1, hista, width=0.6, colorup='r',
colordown='g')
ax1.xaxis_date()
ax1.grid(True)
plt.bar(hista[:,0]-0.25, hista[:, 15], width=0.5)
ax2.grid(True)
plt.setp(plt.gca().get_xticklabels(), rotation=90)
plt.show()&&&&&&
#画出蜡烛图
可以看到有一天大比例的跳档买入盘发生后,股价从40涨到了50
我的第一个股票分析模型建立
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。豆丁微信公众号
君,已阅读到文档的结尾了呢~~
关联规则挖掘在股票预测中的应用研究,关联规则挖掘应用,关联规则挖掘,关联规则挖掘算法,数据挖掘 关联规则,数据挖掘中的关联规则,数据挖掘关联规则算法,关联规则挖掘的实例,数据挖掘关联规则论文,数据挖掘的关联规则
扫扫二维码,随身浏览文档
手机或平板扫扫即可继续访问
关联规则挖掘在股票预测中的应用研究
举报该文档为侵权文档。
举报该文档含有违规或不良信息。
反馈该文档无法正常浏览。
举报该文档为重复文档。
推荐理由:
将文档分享至:
分享完整地址
文档地址:
粘贴到BBS或博客
flash地址:
支持嵌入FLASH地址的网站使用
html代码:
&embed src='http://www.docin.com/DocinViewer--144.swf' width='100%' height='600' type=application/x-shockwave-flash ALLOWFULLSCREEN='true' ALLOWSCRIPTACCESS='always'&&/embed&
450px*300px480px*400px650px*490px
支持嵌入HTML代码的网站使用
您的内容已经提交成功
您所提交的内容需要审核后才能发布,请您等待!
3秒自动关闭窗口Python 数据分析与挖掘实战原文链接:
原来用markdown写的,简书公式编辑比较麻烦。所以正常公式版本可以戳以下链接程序和数据的下载地址:欢迎转载,转载注明出处即可。如有错误,请指正。
运行:cmd下"python hello.py"
基本命令:
for k in range(101):
def add2(x):
return x+2
print add2(1)
def add2(x=0, y=0):
return [x+2, y+2]
def add3(x, y):
return x+3, y+3
a,b = add3(1, 2)
f = lambda x : x+2
g = lambda x, y : x+y
a = [1, 2, 3]
for i in a:
b.append(i+2)
a =[1, 2, 3]
b =[i + 2 for i in a]
d = {'today' : 20, "tomorrow" : 30}
d['today']
dict(['today', 20], ['tomorrow', 30])
dict.fromkeys(['today', 'tomorrow'], 20)
s = {1, 2, 2, 4}
s = set([1,2,2,4])
b = map(lambda x :x+2, a)
b = list(b);
reduce(lambda x, y: x*y, range(1, n+1))
b = filter(lambda x :x & 5 and x &8, range(10))
b = list(b)
import math
math.sin(1)
import math as m
from math import exp as e
from math import *
from __future__ import print_function
from __future__ import division
Windows中 pip install numpy
或者下载源代码安装 python setup.py install
Pandas默认安装不能读写Excel文件,需要安装xlrd和xlwt库才能支持excel的读写 pip install xlrd
pip install xlwt
StatModel可pip可exe安装,注意,此库依赖于Pandas和patsy
Scikit-Learn是机器学习相关的库,但是不包含人工神经网络 model.fit()
model.predict(X_new)
model.predict_proba(X_new)
model.score()
model.transform()
model.fit_transform()
Keras是基于Theano的强化的深度学习库,可用于搭建普通神经网络,各种深度学习模型,如自编码器,循环神经网络,递归神经网络,卷积神经网络。Theano也是一个Python库,能高效实现符号分解,速度快,稳定性好,实现了GPU加速,在密集型数据处理上是CPU的10倍,缺点是门槛太高。Keras的速度在Windows会大打折扣。
Windows下:安装MinGWindows--安装Theano---安装Keras--安装配置CUDA
Gensim用来处理语言方面的任务,如文本相似度计算、LDA、Word2Vec等,建议在Windows下运行。
Linux中 sudo apt-get install python-numpy
sudo apt-get install python-scipy
sudo apt-get install python-matplotlib
Matplotlib默认字体是英文,如果要使用中文标签, plt.rcParams['font.sans-serif'] = ['SimHei']
保存作图图像时,负号显示不正常: plt.rcParams['axes.unicode_minus'] = False
脏数据:缺失值、异常值、不一致的值、重复数据
简单统计量分析:超出合理范围的值
3sigma原则:若正态分布,异常值定义为偏差超出平均值的三倍标准差;否则,可用远离平均值的多少倍来描述。
箱型图分析:异常值定义为小于Q_L-1.5IQR或者大于Q_U +1.5IQR。Q_L是下四分位数,全部数据有四分之一比他小。Q_U是上四分位数。IQR称为四分位数间距,IQR=Q_U-Q_L
import pandas as pd
catering_sale = '../data/catering_sale.xls'
data = pd.read_excel(catering_sale, index_col = u'日期')
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure()
p = data.boxplot()
x = p['fliers'][0].get_xdata()
y = p['fliers'][0].get_ydata()
for i in range(len(x)):
plt.annotate(y[i], xy = (x[i],y[i]), xytext=(x[i]+0.05 -0.8/(y[i]-y[i-1]),y[i]))
plt.annotate(y[i], xy = (x[i],y[i]), xytext=(x[i]+0.08,y[i]))
plt.show()
定量数据的分布分析:求极差(max-min),决定组距和组数,决定分点,列出频率分布表,绘制频率分布直方图。
定性数据的分布分析:饼图或条形图
集中趋势度量:均值、中位数、众数
离中趋势度量:极差、标准差、变异系数、四份位数间距
变异系数为:s表示标准差,x表示均值
from __future__ import print_function
import pandas as pd
catering_sale = '../data/catering_sale.xls'
data = pd.read_excel(catering_sale, index_col = u'日期')
data = data[(data[u'销量'] & 400)&(data[u'销量'] & 5000)]
statistics = data.describe()
print(statistics)
print("--------------")
statistics.loc['range'] = statistics.loc['max']-statistics.loc['min']
statistics.loc['var'] = statistics.loc['std']/statistics.loc['mean']
statistics.loc['dis'] = statistics.loc['75%']-statistics.loc['25%']
print(statistics)
又称帕累托分析,原理是帕累托法则,即20/80定律,同样的投入放在不同的地方会产生不同的收益。
from __future__ import print_function
import pandas as pd
dish_profit = '../data/catering_dish_profit.xls'
data = pd.read_excel(dish_profit, index_col = u'菜品名')
data = data[u'盈利'].copy()
data.sort(ascending = False)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure()
data.plot(kind='bar')
plt.ylabel(u'盈利(元)')
p = 1.0*data.cumsum()/data.sum()
p.plot(color = 'r', secondary_y = True, style = '-o',linewidth = 2)
plt.annotate(format(p[6], '.4%'), xy = (6, p[6]), xytext=(6*0.9, p[6]*0.9),
arrowprops=dict(arrowstyle="-&", connectionstyle="arc3,rad=.2"))
plt.ylabel(u'盈利(比例)')
plt.show()
途径:绘制散点图、散点图矩阵、计算相关系数
Pearson相关系数:要求连续变量的取值服从正态分布。
$$\begin{cases}
{|r|\leq 0.3}&\text{不存在线性相关}\
0.3 & |r| \leq 0.5&\text{低度线性相关}\
0.5 & |r| \leq 0.8&\text{显著线性相关}\
0.8 & |r| \leq 1&\text{高度线性相关}\
\end{cases}$$
相关系数r的取值范围[-1, 1]
Spearman相关系数:不服从正态分布的变量、分类或等级变量之间的关联性可用该系数,也称等级相关系数。
对两个变量分别按照从小到大的顺序排序,得到的顺序就是秩。R_i表示x_i的秩次,Q_i表示y_i的秩次。
判定系数:相关系数的平方,用来解释回归方程对y的解释程度。
from __future__ import print_function
import pandas as pd
catering_sale = '../data/catering_sale_all.xls'
data = pd.read_excel(catering_sale, index_col = u'日期')
data.corr()
data.corr()[u'百合酱蒸凤爪']
data[u'百合酱蒸凤爪'].corr(data[u'翡翠蒸香茜饺'])
按列计算总和
计算算数平均
D.corr(method = ' pearson')
Spearman(Pearson)相关系数矩阵
协方差矩阵
偏度(三阶矩)
峰度(四阶距)
D.describe()
给出样本的基础描述
D = pd.DataFrame([range(1,8), range(2, 9)])
D.corr(method = 'spearman')
S1 = D.loc[0]
S2 = D.loc[1]
S1.corr(S2, method = 'pearson')
D = pd.DataFrame(np.random.randn(6, 5))
print D.cov()
print D[0].cov(D[1])
print D.skew()
print D.describe()
依次给出前1-n个数的和
依次给出前1-n个数的积
依次给出前1-n个数的最大值
依次给出前1-n个数的最小值
rolling_sum()
按列计算数据样本的总和
rolling_mean()
算数平均数
rolling_var()
rolling_std()
rolling_corr()
相关系数矩阵
rolling_cov()
rolling_skew()
rolling_kurt()
D = pd.Series(range(0,20))
print D.cumsum()
print pd.rolling_sum(D, 2)
绘制线性二维图,折线图
绘制饼形图
绘制二维条形直方图,可现实数据的分配情形
绘制箱型图
plot(logy = True)
绘制y轴的对数图形
plot(yerr = error)
绘制误差条形图
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize = (7, 5))
plt.show()
x = np.linspace(0, 2*np.pi, 50)
y = np.sin(x)
plt.plot(x, y, 'bp--')
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode = explode, labels = labels, colors = colors, autopct =
'%1.1f%%', shadow = True, startangle = 90)
plt.axis('equal')
plt.show()
x = np.random.randn(1000)
plt.hist(x, 10)
plt.show()
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = np.exp(np.arange(20))
plt.subplot(121)
plt.plot(range(0,20), x, label = u"原始数据图")
plt.legend()
plt.subplot(122)
plt.semilogy(range(0,20), x, label = u"对数数据图")
plt.legend()
plt.show()
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
error = np.random.random(10)
y = pd.Series(np.sin(np.arange(10)))
y.plot(yerr = error)
plt.show()
包括:删除原始数据中的无关数据、重复数据,平滑噪声数据,处理缺失值。拉格朗日插值法:
当插值节点增减时,插值多项式就会发生变化,在实际计算中不方便。牛顿插值法:P(x)是牛顿插值逼近函数,R(x)是误差函数
Python的Scipy库中只提供了拉格朗日插值法的函数(实现上比较容易)
import pandas as pd
from scipy.interpolate import lagrange
inputfile = '../data/catering_sale.xls'
outputfile = '../tmp/sales.xls'
data = pd.read_excel(inputfile)
data[u'销量'][(data[u'销量'] & 400) | (data[u'销量'] & 5000)] = None
def ployinterp_column(s, n, k=5):
y = s[list(range(n-k, n)) + list(range(n+1, n+1+k))]
y = y[y.notnull()]
return lagrange(y.index, list(y))(n)
for i in data.columns:
for j in range(len(data)):
if (data[i].isnull())[j]:
if (j &= k) and (j & len(data) - k):
y = data[i][list(range(j-k, j)) + list(range(j+1, j+1+k))]
elif j & k :
y = data[i][list(range(0, j)) + list(range(j+1, 2 * k + 1))]
elif j &= len(data) - k:
y = data[i][list(range(len(data) - 1 - 2 * k, j)) + list(range(j+1, len(data)))]
y = y[y.notnull()]
data[i][j] = lagrange(y.index, list(y))(j)
data.to_excel(outputfile)
包括实体识别,冗余属性识别
简单函数变换规范化
离差标准化(最小最大规范化)
标准差标准化
小数定标规范化:属性值映射在[-1, 1]之间
import pandas as pd
import numpy as np
datafile = '../data/normalization_data.xls'
data = pd.read_excel(datafile, header = None)
print (data - data.min())/(data.max() - data.min())
print (data - data.mean())/data.std()
print data/10**np.ceil(np.log10(data.abs().max()))
连续属性离散化
等宽法(至于相同宽度)、等频法(将相同数量的记录放进每个区间)、基于聚类分析的方法(K-means) import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
datafile = '../data/discretization_data.xls'
data = pd.read_excel(datafile)
data = data[u'肝气郁结证型系数'].copy()
d1 = pd.cut(data, k, labels = range(k))
w = [1.0*i/k for i in range(k+1)]
w = data.describe(percentiles = w)[4:4+k+1]
w[0] = w[0]*(1-1e-10)
d2 = pd.cut(data, w, labels = range(k))
kmodel = KMeans(n_clusters = k, n_jobs = 1)
kmodel.fit(data.reshape((len(data), 1)))
c = pd.DataFrame(kmodel.cluster_centers_).sort(0)
w = pd.rolling_mean(c, 2).iloc[1:]
w = [0] + list(w[0]) + [data.max()]
d3 = pd.cut(data, w, labels = range(k))
def cluster_plot(d, k):
plt.figure(figsize = (8, 3))
for j in range(0, k):
plt.plot(data[d==j], [j for i in d[d==j]], 'o')
plt.ylim(-0.5, k-0.5)
return plt
cluster_plot(d1, k).show()
cluster_plot(d2, k).show()
cluster_plot(d3, k).show()
属性构造:比如利用供入电量和供出电量计算线损率。
import pandas as pd
inputfile= '../data/electricity_data.xls'
outputfile = '../tmp/electricity_data.xls'
data = pd.read_excel(inputfile)
data[u'线损率'] = (data[u'供入电量'] - data[u'供出电量'])/data[u'供入电量']
data.to_excel(outputfile, index = False)
用于非平稳信号的时频分析。基于小波变换的主要方法有:多尺度空间能量分布特征提取、多尺度空间的模极大值特征提取、小波包变换的特征提取、适应性小波神经网络的特征提取。小波基函数:Harry小波基,db系列小波基,均值为0。积分为0.小波变换:a是伸缩因子,b是平移因子,对小波基函数进行伸缩和平移变换
任意函数f(t)的连续小波变换(CWT)为:
在约束条件下有逆变换:
python中scipy本身提供了信号处理函数,更好的信号处理库是PyWavelets(pywt)。
import pywt
from scipy.io import loadmat
inputfile= '../data/leleccum.mat'
mat = loadmat(inputfile)
signal = mat['leleccum'][0]
coeffs = pywt.wavedec(signal, 'bior3.7', level = 5)
属性规约:合并属性,逐步向前选择,逐步向后删除,决策树归纳,主成分分析。主成分分析步骤:
设原始变量X_1,X_2,..., X_p的n次观测数据矩阵为:
将数据矩阵按列进行中心标准化
求相关系数矩阵R,$$R=(r_{ij})_{p\times p}$$
求R的特征方程
确定主成分个数m:alpha根据实际问题确定,一般取0.8
计算m个相应的单位特征向量:
计算主成分:
import pandas as pd
from sklearn.decomposition import PCA
inputfile = '../data/principal_component.xls'
outputfile = '../tmp/dimention_reducted.xls'
data = pd.read_excel(inputfile, header = None)
pca = PCA()
pca.fit(data)
print pca.components_
print pca.explained_variance_ratio_
pca = PCA(3)
pca.fit(data)
low_d = pca.transform(data)
pd.DataFrame(low_d).toexcel(outputfile)
pca.inverse_transform(low_d)
数值规约:通过选择替代的、较小的数据来减少数据量。
interpolate
一维、高维数据插值
去除数据终端额重复数据
判断是否空值
判断是否非空值
主成分分析
生成随机矩阵
f = scipy.interpolate.lagrange(x,y)
#一维数据的拉格朗日插值
#计算插值结果
###################################################################
D = pd.Series([1,2,1,3,5])
D.unique()
np.uinque(D)
#这时候D可以是list,array,Series
###################################################################
D.isnull()
#D是series对象,返回布尔Series,D[D.isnull()]找到空值
###################################################################
np.random.rand(k,m,n)
#0-1均匀分布
np.random.randn(k,m,n)
#标准正态分布
常用算法:回归分析、决策树、人工神经网络、贝叶斯网络、支持向量机。Logistic回归Logistic函数:
回归模型:
import pandas as pd
from sklearn.linear_model import LogisticRegression as LR
from sklearn.linear_model import RandomizedLogisticRegression as RLR
filename = '../data/bankloan.xls'
data = pd.read_excel(filename)
x = data.iloc[:,:8].as_matrix()
y = data.iloc[:,8].as_matrix()
rlr = RLR()
rlr.fit(x, y)
rlr.get_support()
print(u'通过随机逻辑回归模型筛选特征结束')
print(u'有效特征为:%s' % ','.join(data.columns[rlr.get_support()]))
x = data[data.columns[rlr.get_support()]].as_matrix()
lr.fit(x, y)
print(u'逻辑回归模型训练结束。')
print(u'模型的平均正确率为:%s' % lr.score(x, y))
Scikit-Learn提供了REF包可以用于特征消除。还提供了REFCV,可以通过交叉验证来对特征进行排序。决策树ID3、C4.5、CART算法ID3:在决策树的各级节点上都用信息增益作为判断标准进行属性的选择,使得在每个节点上都能获得最大的类别分类增益,使分类后的额数据集的熵最小,这样使得树的平均深度最小,从而有效地提高了分类效率。步骤:
对当前样本集合,计算所有属性的信息增益
选择信息增益最大的属性作为测试属性,把测试属性取值相同的样本划为同一个子样本集
若子样本集的类别只有单个,则分支为叶节点;否则对子样本集循环调用本算法
import pandas as pd
from sklearn.tree import export_graphviz
from sklearn.externals.six import StringIO
from sklearn.tree import DecisionTreeClassifier as DTC
inputfile = '../data/sales_data.xls'
data = pd.read_excel(inputfile, index_col = u'序号')
data[data == u'好'] = 1
data[data == u'是'] = 1
data[data == u'高'] = 1
data[data != 1] = -1
x = data.iloc[:,:3].as_matrix().astype(int)
y = data.iloc[:,3].as_matrix().astype(int)
dtc = DTC(criterion='entropy')
dtc.fit(x, y)
with open("tree.dot", 'w') as f:
f = export_graphviz(dtc, feature_names = ['tianqi', 'zhoumo', 'cuxiao'], out_file = f)
人工神经网络
import pandas as pd
inputfile = '../data/sales_data.xls'
data = pd.read_excel(inputfile, index_col = u'序号')
data[data == u'好'] = 1
data[data == u'是'] = 1
data[data == u'高'] = 1
data[data != 1] = 0
x = data.iloc[:,:3].as_matrix().astype(int)
y = data.iloc[:,3].as_matrix().astype(int)
from keras.models import Sequential
from keras.layers.core import Dense, Activation
model = Sequential()
model.add(Dense(3, 10))
model.add(Activation('relu'))
model.add(Dense(10, 1))
model.add(Activation('sigmoid'))
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', class_mode = 'binary')
model.fit(x, y, nb_epoch = 1000, batch_size = 10)
yp = model.predict_classes(x).reshape(len(y))
from cm_plot import *
cm_plot(y,yp).show()
算法评价:相对误差、均方误差、识别准确度、识别精确率、ROC曲线
K-Means算法
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
inputfile = '../data/consumption_data.xls'
outputfile = '../tmp/data_type.xls'
iteration = 500
data = pd.read_excel(inputfile, index_col = 'Id')
data_zs = 1.0*(data - data.mean())/data.std()
model = KMeans(n_clusters = k, n_jobs = 1, max_iter = iteration)
model.fit(data_zs)
r1 = pd.Series(model.labels_).value_counts()
r2 = pd.DataFrame(model.cluster_centers_)
r = pd.concat([r2, r1], axis = 1)
r.columns = list(data.columns) + [u'类别数目']
r = pd.concat([data, pd.Series(model.labels_, index = data.index)], axis = 1)
r.columns = list(data.columns) + [u'聚类类别']
r.to_excel(outputfile)
def density_plot(data):
p = data.plot(kind='kde', linewidth = 2, subplots = True, sharex = False)
[p[i].set_ylabel(u'密度') for i in range(k)]
plt.legend()
return plt
pic_output = '../tmp/pd_'
for i in range(k):
density_plot(data[r[u'聚类类别']==i]).savefig(u'%s%s.png' %(pic_output, i))
聚类算法评价:purity评价法、RI评价法、F值评价法
AffinityPropagation
吸引力传播聚类
SpectralClustering
谱聚类,由于KMeans
AgglomerativeClustering
具有噪声的基于密度的聚类算法
均值漂移聚类算法
层次聚类算法,可以处理大规模数据
先用对应的函数建立模型,然后使用fit方法训练模型,之后用label_方法给出样本数据的标签,或者用predict方法预测新的输入的标签。
TENSE:提供一种有效地数据降维的方式,在2维或者3维战士聚类结果。
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
tsne = TSNE()
tsne.fit_transform(data_zs)
tsne = pd.DataFrame(tsne.embedding_, index = data_zs.index)
d = tsne[r[u'聚类类别'] == 0]
plt.plot(d[0], d[1], 'r.')
d = tsne[r[u'聚类类别'] == 1]
plt.plot(d[0], d[1], 'go')
d = tsne[r[u'聚类类别'] == 2]
plt.plot(d[0], d[1], 'b*')
plt.show()
常用算法:Apriori、FP-Tree、Eclt算法、灰色关联法
Ariori算法
,A、B同时发生的概率
A发生B发生的概率同时满足最小支持度和最小置信度称满足强规则算法步骤:
扫描事物集,得到没个候选项的支持度
比较候选支持度与最小支持度,得到1项频繁集L_1
由L_1产生候选项集C_2,并计算支持度
比较候选支持度和最小支持度,得到2项频繁集L_2
类推,直至不能产生新的候选项集
from __future__ import print_function
import pandas as pd
def connect_string(x, ms):
x = list(map(lambda i:sorted(i.split(ms)), x))
l = len(x[0])
for i in range(len(x)):
for j in range(i,len(x)):
if x[i][:l-1] == x[j][:l-1] and x[i][l-1] != x[j][l-1]:
r.append(x[i][:l-1]+sorted([x[j][l-1],x[i][l-1]]))
def find_rule(d, support, confidence, ms = u'--'):
result = pd.DataFrame(index=['support', 'confidence'])
support_series = 1.0*d.sum()/len(d)
column = list(support_series[support_series & support].index)
while len(column) & 1:
print(u'\n正在进行第%s次搜索...' %k)
column = connect_string(column, ms)
print(u'数目:%s...' %len(column))
sf = lambda i: d[i].prod(axis=1, numeric_only = True)
d_2 = pd.DataFrame(list(map(sf,column)), index = [ms.join(i) for i in column]).T
support_series_2 = 1.0*d_2[[ms.join(i) for i in column]].sum()/len(d)
column = list(support_series_2[support_series_2 & support].index)
support_series = support_series.append(support_series_2)
column2 = []
for i in column:
i = i.split(ms)
for j in range(len(i)):
column2.append(i[:j]+i[j+1:]+i[j:j+1])
cofidence_series = pd.Series(index=[ms.join(i) for i in column2])
for i in column2:
cofidence_series[ms.join(i)] = support_series[ms.join(sorted(i))]/support_series[ms.join(i[:len(i)-1])]
for i in cofidence_series[cofidence_series & confidence].index:
result[i] = 0.0
result[i]['confidence'] = cofidence_series[i]
result[i]['support'] = support_series[ms.join(sorted(i.split(ms)))]
result = result.T.sort(['confidence','support'], ascending = False)
print(u'\n结果为:')
print(result)
return result
from __future__ import print_function
import pandas as pd
from apriori import *
inputfile = '../data/menu_orders.xls'
outputfile = '../tmp/apriori_rules.xls'
data = pd.read_excel(inputfile, header = None)
print(u'\n转换原始数据至0-1矩阵...')
ct = lambda x : pd.Series(1, index = x[pd.notnull(x)])
b = map(ct, data.as_matrix())
data = pd.DataFrame(b).fillna(0)
print(u'\n转换完毕。')
support = 0.2
confidence = 0.5
ms = '---'
find_rule(data, support, confidence, ms).to_excel(outputfile)
非平稳时间序列分析:许多非平稳序列差分后会显示出平稳序列的性质,这时称之为差分平稳序列,可以先做差分然后用ARMA模型进行拟合。这种方法称之为ARIMA模型。
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.tsa.stattools import adfuller as ADF
from statsmodels.graphics.tsaplots import plot_pacf
from statsmodels.stats.diagnostic import acorr_ljungbox
from statsmodels.tsa.arima_model import ARIMA
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
discfile = '../data/arima_data.xls'
forecastnum = 5
data = pd.read_excel(discfile, index_col = u'日期')
data.plot()
plt.show()
plt.title('Time Series')
plot_acf(data).show()
print(u'原始序列的ADF检验结果为:', ADF(data[u'销量']))
D_data = data.diff().dropna()
D_data.columns = [u'销量差分']
D_data.plot()
plt.show()
plot_acf(D_data).show()
plot_pacf(D_data).show()
print(u'差分序列的ADF检验结果为:', ADF(D_data[u'销量差分']))
print(u'差分序列的白噪声检验结果为:', acorr_ljungbox(D_data, lags=1))
data[u'销量'] = data[u'销量'].astype(float)
pmax = int(len(D_data)/10)
qmax = int(len(D_data)/10)
bic_matrix = []
for p in range(pmax+1):
for q in range(qmax+1):
tmp.append(ARIMA(data, (p,1,q)).fit().bic)
tmp.append(None)
bic_matrix.append(tmp)
bic_matrix = pd.DataFrame(bic_matrix)
p,q = bic_matrix.stack().idxmin()
print(u'BIC最小的p值和q值为:%s、%s' %(p,q))
model = ARIMA(data, (p,1,q)).fit()
model.summary2()
model.forecast(5)
计算自相关系数
画自相关系数图
计算偏相关系数
单位根检验
给出ARIMA模型的报告
aic/bic/hqic
计算ARIMA模型的指标
acorr_ljungbox
Ljung-Box检验,是否白噪声
autocorr = acf(data, unbiased = False, nlags = 40, qstat = False, fft = False, alpha = False)
h = adfuller(Series, maxlag = None, Regression = 'c', autolog = 'AIC', store = False, regresults =False)
arima = ARIMA(data, (p, 1, q)).fit()
amima.summary()
a,b,c = arima.forecast(num)
方法:基于统计、基于邻近度、基于密度、基于聚类。基于统计:一元正态分布若数据点在3倍标准差之外。混合模型的离群点检测:数据的统计分布未知或者没有训练数据可用,很难建立模型。基于原型的聚类:聚类所有的对象,然后评估对象属于簇的程度。如果删除一个对象导师制该目标显著改进,则可将该对象视为离群点。离群点可能形成小簇从而逃避检测。
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
inputfile = '../data/consumption_data.xls'
threshold = 2
iteration = 500
data = pd.read_excel(inputfile, index_col = 'Id')
data_zs = 1.0*(data - data.mean())/data.std()
model = KMeans(n_clusters = k, n_jobs = 1, max_iter = iteration)
model.fit(data_zs)
r = pd.concat([data_zs, pd.Series(model.labels_, index = data.index)], axis = 1)
r.columns = list(data.columns) + [u'聚类类别']
for i in range(k):
norm_tmp = r[['R', 'F', 'M']][r[u'聚类类别'] == i]-model.cluster_centers_[i]
norm_tmp = norm_tmp.apply(np.linalg.norm, axis = 1)
norm.append(norm_tmp/norm_tmp.median())
norm = pd.concat(norm)
norm[norm &= threshold].plot(style = 'go')
discrete_points = norm[norm & threshold]
discrete_points.plot(style = 'ro')
for i in range(len(discrete_points)):
id = discrete_points.index[i]
n = discrete_points.iloc[i]
plt.annotate('(%s, %0.2f)'%(id, n), xy = (id, n), xytext = (id, n))
plt.xlabel(u'编号')
plt.ylabel(u'相对距离')
plt.show()
数据分析:
分布分析:用户类别窃漏电情况分布发现,非居民类不存在漏电情况。故可清理
周期性分析:找到一个正常的用户和漏电用户,分别观察规律。发现正常用户有明显的周期性。
数据预处理
数据清洗:过滤掉非居民类的数据和节假日数据。
缺失值处理:拉格朗日插补法进行插补
数据变换:用电趋势指标、5天平均线损率、告警指标计数
用LM神经网络和CART决策树模型建模
ROC曲线比较性能
数据分析:缺失值分析和异常值分析,异常值看最大和最小值
数据预处理:
数据清洗,丢弃缺失值、票价为0折扣率不为0的数据
属性规约,删除不相关或者弱相关属性
数据变换:计算指标,并对数据进行标准化处理
K-Means算法对客户数据进行分群,分为5类。
结合图表对结果进行分析
数据预处理
数据清洗:删除整理无效问卷
属性规约:将冗余属性和无关属性删除
数据变换:构造属性,并将属性离散化
采用Apriori关联规则算法对模型的样本数据进行分析,以模型参数设置的最小支持度和最小置信度作为条件,输出关联规则结果。
数据预处理
图像切割:提取水样图像中间部分具有代表意义的图像
特征提取:颜色的一阶、二阶、三阶矩
为提高区分度,将所有特征乘以常数k。然后建立支持向量机模型。
对新增的水质图像作评价。
数据预处理
数据规约:去除无用的属性和状态
数据变换:确定用水事件的阈值
模型构建:训练神经网络
模型检验:使用测试数据
数据分析:通过时序图观察数据的平稳性和周期性
数据预处理
数据清洗:删除重复值
属性构造:合并属性
检验平稳性,单位根检验
白噪声检验
模型识别:采用极大似然比方法进行模型的参数估计,采用BIC信息准则对模型进行定阶。ARIMA(0,1,1)
模型检验:检验模型残差序列是否为白噪声如果不是,说明还有未提取的有用信息,需要修改模型。
模型评价:计算平均绝对误差,均方根误差
数据抽取:建立数据库--导入数据--搭建Python数据库操作环境
网页类型分析
点击次数分析
数据预处理
数据清洗:删除数据(中间页面网址、发布成功网址、登录助手页面)
数据变化:识别翻页网址并去重,错误分类网址手动分类,并进一步分类
属性规约:只选择用户和用户选择的网页数据
基于物品的协同滤波算法:计算物品之间的相似度,建立相似度矩阵;根据物品的相似度和用户的历史行为给用户生成推荐列表。
相似度计算方法:夹角余弦、Jaccard系数、相关系数
描述性统计分析
对于财政收入、增值税、营业税、企业所得税、政府性基金、个人所得税
Adaptive-Lasso变量选择模型:去除无关变量
分别建立灰色预测模型与神经网络模型
数据预处理
属性规约:删除冗余属性,合并时间属性
数据变换:计算工作日人均停留时间、凌晨、周末、日均等指标,并标准化。
构建商圈聚类模型:采用层次聚类算法
模型分析:对聚类结果进行特征观察
文本采集:八爪鱼采集器(爬虫工具)
文本预处理:
文本去重:自动评价、完全重复评价、复制的评论
机械压缩去词:
文本评论分词:采用Python中文分词包“Jieba”分词,精度达97%以上。
情感倾向性模型:生成词向量;评论集子集的人工标注与映射;训练栈式自编码网络
基于语义网络的评论分析
基于LDA模型的主题分析
相关热门文章分享}

我要回帖

更多关于 论文股票期权会计研究 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信