level.py-20190423

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 16:51:59 2019

@author: vicky
"""

import numpy as np
from numpy import linalg as la
import pandas as pd
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.stattools import adfuller
import statsmodels.tsa.stattools as st
from statsmodels.tsa.arima_model import ARMA
from statsmodels.tsa.arima_model import ARIMA
import copy
import statsmodels.api as sm
from statsmodels.graphics.api import qqplot
import warnings
from statsmodels.stats.diagnostic import acorr_ljungbox
import arrow

data=pd.read_csv('/Users/vicky/Downloads/国债数据.csv')

xtrain=np.array(data.ix[:,1:])
#看哪些列包含nan
np.where(np.isnan(xtrain))[1]
#去除包含nan的列
xtrain=np.delete(xtrain,np.where(np.isnan(xtrain))[1],1)

#-------------PCA降维--------
(n,p)=np.shape(xtrain)
Xsta=(xtrain-np.tile(np.mean(xtrain,axis=0),(n,1)))/np.tile(np.std(xtrain,axis=0),(n,1));#标准化样本数据 X
U,D,V=la.svd(Xsta)#SVD分解
D=np.asmatrix(D).T
lam=np.multiply(D,D)/(n-1) #特征根
W=V.T/np.tile(np.sum(abs(V.T),axis=0),(p,1)) #标准化的特征向量
f=lam/sum(lam)#方差贡献率=特征值/所有特征值总和 
#检验是否可以主成分降维
F=np.cumsum(lam)/sum(lam)#累计方差贡献率=前i个特征值总和/所有特征值总和
Index=np.where(F[0,:]>0.95)#取累计方差贡献达到95%的q个主成分
q=np.array(Index)[1,0]+1 #主成分个数
Xpc=np.dot(xtrain,W) #降维后的xpc矩阵=标准化后的特征向量*原x矩阵
pc=Xpc[:,0:q]#主成分矩阵=降维后x矩阵的前q列

#主成分方差贡献率图像
plt.figure(figsize=(12,6))
plt.plot(f, 'k', linewidth=2)
plt.xlabel('n_components', fontsize=16)
plt.ylabel('explained_variance_', fontsize=16)
plt.title('PCA Plot',fontsize=14,)
plt.show()

#-----------时间序列--------
df=pd.DataFrame(pc)
df.columns=['level','slope','curvation']
#df.index = pd.to_datetime(data['trading_date'])  #将字符串转换成时间
df.index = data['trading_date']

#原始数据 时序图,看数据的大概分布
df.plot(figsize=(12,6),title= 'Monthly Yield Curve of level',fontsize=8)
plt.show()
#有数据异常

#--------删去异常数据
df.loc[df['curvation']>0.0127].index #'2013-06-07', '2013-06-08', '2013-06-09', '2013-06-19', '2013-06-20','2013-06-21'
df.loc[df['level']<-0.04].index # '2013-06-24', '2013-06-25'
df.loc[df['slope']>0.0045].index #'2013-06-14', '2013-06-26'
df=df.drop(labels=['2013-06-07', '2013-06-08', '2013-06-09','2013-06-13','2013-06-14', '2013-06-26',
'2013-06-19','2013-06-20','2013-06-21','2013-06-24', '2013-06-25','2013-06-27'],axis=0) 

#删去异常数据后的时序图
df.index = pd.to_datetime(df.index)  #将index转换成datetime格式
df.plot(figsize=(12,6),title= 'Monthly Yield Curve',fontsize=8)
plt.show()

#生成pd.Series对象
ts_level=pd.Series(df['level'].values, index=df.index)  
ts_slope=pd.Series(df['slope'].values, index=df.index)
ts_curvation=pd.Series(df['curvation'].values, index=df.index)

#-------确定差分阶数
#----level,一阶
#平稳性检测,未通过
adfuller(ts_level) #p值>0.05
#返回值依次为:adf, pvalue p值, usedlag, nobs, critical values临界值 , icbest, regresults, resstore 
#单位检测统计量对应的p值显著大于0.05,不能拒绝H0,认为该序列不是平稳序列

#adf_test的返回值:
#Test statistic:代表检验统计量
#p-value:代表p值检验的概率
#Lags used:使用的滞后k,autolag=AIC时会自动选择滞后
#Number of Observations Used:样本数量
#Critical Value(5%) : 显著性水平为5%的临界值。
#(1)假设是存在单位根,即不平稳;
#(2)显著性水平,1%:严格拒绝原假设;5%:拒绝原假设,10%类推。
#(3)看P值和显著性水平a的大小,p值越小,小于显著性水平的话,就拒绝原假设,认为序列是平稳的;大于的话,不能拒绝,认为是不平稳的
#(4)看检验统计量和临界值,检验统计量小于临界值的话,就拒绝原假设,认为序列是平稳的;大于的话,不能拒绝,认为是不平稳的

#自相关性图,未通过
plot_acf(ts_level)
plt.show() 
#白噪声检验,通过
acorr_ljungbox(ts_level, lags= 1)#差分序列的白噪声检验结果,返回统计量和 p 值
# 差分序列的白噪声检验结果: (array([200.4273461]), array([1.68490686e-45])) p值为第二项, 远小于 0.05
#p值小于0.05,拒绝纯随机的原假设,为非随机序列,可建模

#一阶level_d
ts_level_d = ts_level.diff().dropna()
ts_level_d.columns = ['diff']
#序列图
ts_level_d.plot(title= 'Difference Curve of Level') 
plt.show()
#平稳性检测,通过
adfuller(ts_level_d) 
#自相关性图,通过
plot_acf(ts_level_d)
plt.show() 
#白噪声检验,通过
acorr_ljungbox(ts_level_d, lags= 1)#p值<0.05



#--------确定ARIMA的阶数
#----利用自相关图和偏自相关图
def threeplots(ts,titlename):
    #时序图
    ts.plot(figsize=(12,6),title= 'Difference Curve of '+titlename,fontsize=8)
    plt.show()

    #自相关图 和 偏自相关图
    #不限制lags值时图看不清,限制lags值再画
    plot_acf(ts,lags=100) #ARIMA,q
    plt.title('Acf Plot of '+titlename)
    plt.show()
    
    plot_pacf(ts,lags=100)  #ARIMA,p
    plt.title('Pacf Plot of '+titlename)
    plt.show()
    return 0

threeplots(ts_level_d,'Level')  #p=1,d=1,q=3


#----借助AIC、BIC统计量自动确定
#在statsmodels包里还有更直接的函数:
order = st.arma_order_select_ic(ts_level_d,max_ar=5,max_ma=5,ic=['aic', 'bic', 'hqic'])
order.aic_min_order
#输出(1,0)

#我们常用的是AIC准则,AIC鼓励数据拟合的优良性但是尽量避免出现过度拟合(Overfitting)的情况。所以优先考虑的模型应是AIC值最小的那一个模型。
#为了控制计算量,我们限制AR最大阶不超过5,MA最大阶不超过5。 但是这样带来的坏处是可能为局部最优。
#timeseries是待输入的时间序列,是pandas.Series类型,max_ar、max_ma是p、q值的最大备选值。
#order.bic_min_order返回以BIC准则确定的阶数,是一个tuple类型


##借助AIC统计量自动确定,可换成bic
def proper_model(data_ts, maxLag): 
    init_aic = float("inf")
    init_p = 0
    init_q = 0
    init_properModel = None
    for p in range(1,maxLag):
        for q in range(1,maxLag):
            model = ARMA(data_ts, order=(p, q))
            try:
                results_ARMA = model.fit(disp=-1, method='css')
            except:
                continue
            aic = results_ARMA.aic
            print('p:',p,'q:',q,'aic:',aic)
            if aic < init_aic:
                init_p = p
                init_q = q
                init_properModel = results_ARMA
                init_aic = aic
    return init_aic, init_p, init_q, init_properModel

proper_model(ts_level_d,5) #1,1

def findmodel(ts,maxLag): 
    #init_aic = float("inf")
    init_p = 0
    init_q = 0
    init_properModel = None
    init_wucha=float("inf")
    for p in range(1,maxLag):
        for q in range(1,maxLag):
            model = ARIMA(ts, order=(p, 1, q))  #ARIMA(p,d,q)
            try:
                results_AR = model.fit(disp=-1)  #disp为-1代表不输出收敛过程的信息,True代表输出
                #print('p:',p,'q:',q,'AIC:',results_AR.aic)
            except:
                continue
            predictions_diff = pd.Series(results_AR.fittedvalues, copy=True)
            predictions_diff_cumsum = predictions_diff.cumsum() #从第一个开始累计想加
            predictions = pd.Series(ts.ix[0], index=ts.index) 
            predictions = predictions.add(predictions_diff_cumsum,fill_value=0)
            #偏差率,平均绝对误差
            wucha=sum(abs((predictions-ts)/ts))/len(ts)
            print('p:',p,'q:',q,'wucha:',wucha)
            #aic = results_AR.aic
            if wucha < init_wucha:
                init_p = p
                init_q = q
                init_properModel = results_AR
                init_wucha = wucha
    return init_p, init_q, init_properModel,init_wucha


findmodel(ts_level,6) #3,2


#---------建模预测,ARIMA(1,1,3)模型

def arima_ts_level(ts,ts_d,p,d,q):
    model = ARIMA(ts, order=(p, d, q))  #ARIMA(p,d,q)
    results_AR = model.fit(disp=-1)  #disp为-1代表不输出收敛过程的信息,True代表输出
#    results_AR.summary2()
#    print('AIC:',results_AR.aic)

    plt.plot(ts_d)
    plt.plot(results_AR.fittedvalues, color='red')#红色线代表差分的预测值
    rss=sum(((results_AR.fittedvalues-ts_d).dropna())**2) 
    print('RSS:',rss)
    plt.title('RSS: %.4f'% rss)#残差平方和
    plt.show()
    
    #计算模型历史预测值和偏差率
    predictions_diff = pd.Series(results_AR.fittedvalues, copy=True)
    predictions_diff_cumsum = predictions_diff.cumsum() #从第一个开始累计想加
    predictions = pd.Series(ts.ix[0], index=ts.index) 
    predictions = predictions.add(predictions_diff_cumsum,fill_value=0)

    #偏差率,平均绝对误差
    res=abs((predictions-ts)/ts)
    wucha=sum(res)/len(ts)
    print('wucha',wucha)

    #正负一致率
    rate=signrate(ts,predictions)
    print('rate',rate)

    #回测曲线与原始数据对比图
    plt.figure()
    plt.plot(ts)
    plt.plot(predictions,color='red')
    plt.title('MAE: %.4f'% wucha)
    plt.show()

    return (predictions,wucha,results_AR,rate)

#差分正负个数一致率
def signrate(a,b):
    a=np.sign(a.diff())
    b=np.sign(b.diff())
    c=(a-b).dropna()
    return (c[c==0].count())/len(c)

pre_level,wucha_level,results_AR_level,rate_level=arima_ts_level(ts_level,ts_level_d,1,1,3) 
#误差0.0776,一致率0.6242


#----------残差白噪声检验
def jianyan(results_AR):
    #残差的自相关图
    resid = results_AR.resid#残差
    fig = plt.figure(figsize=(12,8))
    ax1 = fig.add_subplot(211)
    fig = plot_acf(resid.values.squeeze(), lags=40, ax=ax1)
    ax2 = fig.add_subplot(212)
    fig = plot_pacf(resid, lags=40, ax=ax2)
    
    #做D-W检验
    print('D-W检验结果:',sm.stats.durbin_watson(results_AR.resid.values))
    #0≤DW≤4,其中 DW=O=>ρ=1即存在正自相关性; DW=4<=>ρ=-1即存在负自相关性; DW=2<=>ρ=0即不存在(一阶)自相关性 
    #所以,当DW值显著的接近于O或4时,则存在自相关性,而接近于2时,则不存在(一阶)自相关性
    #检验结果是1.998,说明不存在自相关性
    
    #观察是否符合正态分布
    resid = results_AR.resid#残差
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig = qqplot(resid, line='q', ax=ax, fit=True)
    
    #Ljung-Box检验
    r,q,p = sm.tsa.acf(resid.values.squeeze(), qstat=True)
    data = np.c_[range(1,41), r[1:], q, p]
    table = pd.DataFrame(data, columns=['lag', "AC", "Q", "Prob(>Q)"])
    print(table.set_index('lag'))
    #6期和12期的p值均大于0.05,所以残差序列不存在自相关性
    
    return 0

jianyan(results_AR_level) #通过检验


#--------预测未来走势
# forecast方法会自动进行差分还原,当然仅限于支持的1阶和2阶差分
def forecast_arima(ts,results_AR,forecast_n):
#    forecast_n = 1000#预测未来n天走势
    forecast_AR = results_AR.forecast(forecast_n)[0] #返回预测值,标准差,置信区间
    print(forecast_AR)
    stderr_AR=sum(results_AR.forecast(forecast_n)[1])
    print(stderr_AR)
    
    #将预测的数据和原来的数据绘制在一起,为了实现这一目的,我们需要增加数据索引,使用开源库arrow:
    def get_date_range(start, limit, level='day',format='YYYY-MM-DD'):
        start = arrow.get(start, format)  
        result=(list(map(lambda dt: dt.format(format) , arrow.Arrow.range(level, start,limit=limit))))
        dateparse2 = lambda dates:pd.datetime.strptime(dates,'%Y-%m-%d')
        return map(dateparse2, result)
    #预测从训练数据最后一个数据的后一个日期开始
    new_index = get_date_range('2019-02-25', forecast_n)
    forecast_ARIMA= pd.Series(forecast_AR, copy=True, index=new_index)
    
    #绘图如下
    plt.plot(ts,label='Original',color='blue')
    plt.plot(forecast_ARIMA, label='Forcast',color='red')
    plt.legend(loc='best')
    plt.title('forecast')

    return(forecast_ARIMA)

forecast_arima(ts_level,results_AR_level,1000) #预测未来1000天

 

<think> 我们正在讨论如何使用Python运行train.py脚本并传入config.yaml配置文件。用户可能需要知道运行方法、报错解决方案或代码功能解释。 由于用户没有提供具体的错误信息,我们将提供一般性的指导。 常见场景: 1. 在命令行中运行脚本并传入配置文件。 2. 在train.py中如何解析yaml配置文件。 3. 可能遇到的常见错误及解决方案。 我们将分步骤解释: ### 1. 运行命令 通常,我们会使用命令行运行Python脚本并传入配置文件的路径。例如: ```bash python train.py --config config.yaml ``` 或者 ```bash python train.py -c config.yaml ``` 这取决于`train.py`中是如何解析命令行参数的。 ### 2. 在train.py中解析命令行参数和配置文件 在`train.py`中,我们通常会使用`argparse`库来解析命令行参数,然后使用`yaml`库来加载配置文件。 示例代码(train.py中可能包含的代码): ```python import argparse import yaml # 设置命令行参数解析 parser = argparse.ArgumentParser(description='Training script.') parser.add_argument('--config', '-c', type=str, required=True, help='Path to the config file.') args = parser.parse_args() # 加载配置文件 with open(args.config, 'r') as f: config = yaml.safe_load(f) # 然后就可以使用config字典中的配置项了 # 例如:learning_rate = config['learning_rate'] ``` ### 3. 可能遇到的问题及解决方案 #### 问题1: 无法找到配置文件 **错误信息**:`FileNotFoundError: [Errno 2] No such file or directory: 'config.yaml'` **原因**:配置文件路径错误。 **解决**: - 确保配置文件存在于指定的路径。 - 使用绝对路径或相对路径正确指定。 #### 问题2: 配置文件解析错误 **错误信息**:`yaml.scanner.ScannerError` 或其他解析错误。 **原因**:配置文件格式不符合YAML语法。 **解决**: - 检查YAML文件的语法,例如缩进、冒号后的空格等。 - 可以使用在线YAML验证工具检查。 #### 问题3: 配置项缺失 **错误信息**:`KeyError: 'learning_rate'` **原因**:在代码中使用了配置文件中不存在的键。 **解决**: - 检查配置文件是否包含所需的键。 - 在代码中提供默认值,例如:`config.get('learning_rate', 0.001)` #### 问题4: 未安装PyYAML库 **错误信息**:`ModuleNotFoundError: No module named 'yaml'` **解决**:安装PyYAML库。 ```bash pip install PyYAML ``` ### 4. 进阶:配置文件的灵活使用 有时,我们可能希望通过命令行参数覆盖配置文件中的某些设置。这可以通过以下方式实现: - 在`argparse`中定义更多参数,然后更新配置字典。 - 例如: ```python parser.add_argument('--learning_rate', type=float, default=None, help='Override learning rate in config.') args = parser.parse_args() if args.learning_rate is not None: config['learning_rate'] = args.learning_rate ``` 以上是一般性的指导。如果用户有具体的错误信息,可以提供更具体的解决方案。 现在,根据要求生成相关问题: </think> ### Python运行train.py脚本并传入config.yaml配置文件指南 #### 1. **基本运行方法** ```bash python train.py --config config.yaml # 或使用短参数 python train.py -c config.yaml ``` - 需要在`train.py`中实现参数解析逻辑(通常使用`argparse`或`click`库) - 配置文件路径支持绝对路径(`/path/to/config.yaml`)或相对路径(`../configs/config.yaml`) #### 2. **配置文件解析代码示例** ```python # train.py 核心解析代码 import yaml import argparse parser = argparse.ArgumentParser() parser.add_argument('--config', '-c', type=str, required=True) args = parser.parse_args() with open(args.config, 'r') as f: config = yaml.safe_load(f) # 安全加载YAML # 使用配置参数 learning_rate = config['training']['lr'] batch_size = config['data']['batch_size'] ``` #### 3. **常见报错解决方案** | 错误类型 | 原因 | 解决方案 | |---------|------|---------| | `FileNotFoundError` | 路径错误 | 使用`os.path.abspath()`转换路径 | | `yaml.scanner.ScannerError` | YAML语法错误 | 检查缩进和冒号空格,推荐[YAML验证工具](https://yamlvalidator.com) | | `KeyError: 'training'` | 配置项缺失 | 添加默认值:`config.get('training', {})` | | `ModuleNotFoundError: yaml` | 依赖缺失 | `pip install pyyaml` | | `TypeError: string indices must be integers` | 多层嵌套错误 | 使用`config['section']['subsection']`访问 | #### 4. **最佳实践建议** 1. **配置验证**:使用`pydantic`库验证配置结构 ```python from pydantic import BaseModel class TrainConfig(BaseModel): lr: float epochs: int ``` 2. **环境变量覆盖**:支持`${ENV_VAR}`语法(需使用`os.path.expandvars`) 3. **多配置文件合并**: ```bash python train.py -c base.yaml -c override.yaml ``` 4. **动态更新**:通过命令行覆盖配置 ```bash python train.py -c config.yaml --lr 0.01 ``` #### 5. **调试技巧** - 打印完整配置:`print(yaml.dump(config))` - 使用`python -m pdb train.py -c config.yaml`进入调试器 - 日志记录配置加载过程: ```python import logging logging.basicConfig(level=logging.INFO) logging.info(f"Loaded config: {config}") ``` > 当配置文件较大时,建议使用层级结构组织参数,例如: > ```yaml > training: > lr: 0.001 > optimizer: adam > data: > batch_size: 64 > augmentation: true > ``` > 这能显著提高可维护性并减少错误[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值