哈喽勾引 户外,我是小白~ 今儿我们一齐来望望时期序列分析算法。 时期序列分析循序很珍惜,主要由于: 趋势识别:匡助我们识别数据中的永久趋势和季节性变化,为掂量改日趋势提供依据。异常检测:约略检测数据中的异常值和异常步地,实时发现潜在问题。决议撑执:为政策制定和计谋贪图提供数据驱动的细察,匡助优化决议经由。是以,基于它的珍惜性,我们一齐来看今天共享的有: 自转头转移平均自转头滑动平均自转头积分滑动平均季节性自转头积分滑动平均向量自转头向量自转头滑动平均诟谇期追念蚁集Prophet变分自编码器一齐来望望~ 1. 自转头 (AR, Autoregressive Model)自转头模子假定面前值 是往时些许时代值的线性组合。 旨趣模子左右前 p 个时期点的数据掂量面前时期点的数据。 中枢公式其中: 是常数项, 是自转头悉数, 是白噪声罪戾。自转头模子的推导不错通过对时期序列数据进行线性转头得到,即: 使用最小二乘法求解悉数 。 中枢案例案例中,使用了股票价钱数据,展示如何拟合AR模子并进行掂量,并生成两个以上的数据分析图形。 使用一个股票价钱的时期序列数据,率先对数据进行预处理,然后拟合一个自转头模子,终末勾引 户外生成几个图形,包括时期序列图、ACF图、PACF图和掂量图。 使用 yfinance 库来赢得股票价钱数据。 import yfinance as yfimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.ar_model import AutoRegfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 下载数据ticker = 'AAPL' # 以苹果公司股票为例start_date = '2020-01-01'end_date = '2023-01-01'data = yf.download(ticker, start=start_date, end=end_date)close_prices = data['Close']# 绘图时期序列图plt.figure(figsize=(14, 7))plt.plot(close_prices, label='Close Price')plt.title('Apple Stock Close Prices')plt.xlabel('Date')plt.ylabel('Close Price')plt.legend()plt.show()# ACF和PACF图fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 10))plot_acf(close_prices, ax=ax1, lags=50)plot_pacf(close_prices, ax=ax2, lags=50)plt.show()# 拟合自转头模子lags = 30model = AutoReg(close_prices, lags=lags)model_fit = model.fit()# 模子掂量pred_start = len(close_prices)pred_end = pred_start 50predictions = model_fit.predict(start=pred_start, end=pred_end)# 绘图掂量终端plt.figure(figsize=(14, 7))plt.plot(close_prices, label='Observed')plt.plot(predictions, label='Forecast', linestyle='--')plt.title('Apple Stock Close Price Forecast')plt.xlabel('Date')plt.ylabel('Close Price')plt.legend()plt.show()时期序列图:展示了苹果公司股票的逐日收盘价。ACF和PACF图:用于查验时期序列的自干系性和部分自干系性,匡助驯服AR模子的阶数。掂量图:展示了拟合AR模子后的改日50天的股票价钱掂量。图片 2. 转移平均 (MA, Moving Average Model)转移平均模子假定面前值 是往时些许时代罪戾的线性组合。 旨趣模子左右前 q 个时期点的罪戾掂量面前时期点的数据。 中枢公式其中: 是常数项, 是转移平均悉数, 是白噪声罪戾。通过假定罪戾项 是孤独同散播的白噪声,不错用最小二乘法或极大似然料到法求解悉数 。 中枢案例假定我们有一个月度的销售数据,该数据包含一些季节性和随即波动。我们将使用转移平均模子来平滑数据,并相比平滑后的数据与原始数据。此外,我们还将计较并绘图残差。 人体艺术照import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom statsmodels.tsa.arima.model import ARIMAfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 生成模拟的时期序列数据np.random.seed(42)n_periods = 120date_range = pd.date_range(start='2010-01', periods=n_periods, freq='M')seasonal_pattern = np.sin(2 * np.pi * date_range.month / 12)random_noise = np.random.normal(scale=0.5, size=n_periods)sales = 10 seasonal_pattern random_noise# 创建数据框data = pd.DataFrame({'Date': date_range, 'Sales': sales})data.set_index('Date', inplace=True)# 绘图原始数据plt.figure(figsize=(14, 6))plt.plot(data.index, data['Sales'], label='Original Sales Data')plt.title('Monthly Sales Data')plt.xlabel('Date')plt.ylabel('Sales')plt.legend()plt.show()# 使用转移平均模子进行平滑window_size = 12data['Sales_MA'] = data['Sales'].rolling(window=window_size).mean()# 绘图平滑后的数据plt.figure(figsize=(14, 6))plt.plot(data.index, data['Sales'], label='Original Sales Data')plt.plot(data.index, data['Sales_MA'], label=f'{window_size}-month Moving Average', color='red')plt.title('Monthly Sales Data with Moving Average')plt.xlabel('Date')plt.ylabel('Sales')plt.legend()plt.show()# 计较残差data['Residual'] = data['Sales'] - data['Sales_MA']# 绘图残差plt.figure(figsize=(14, 6))plt.plot(data.index, data['Residual'], label='Residuals', color='green')plt.title('Residuals from Moving Average Model')plt.xlabel('Date')plt.ylabel('Residual')plt.legend()plt.show()# 绘图自干系图和偏自干系图fig, axes = plt.subplots(1, 2, figsize=(16, 6))plot_acf(data['Residual'].dropna(), ax=axes[0], lags=40)plot_pacf(data['Residual'].dropna(), ax=axes[1], lags=40)axes[0].set_title('ACF of Residuals')axes[1].set_title('PACF of Residuals')plt.show()生成时期序列数据:使用正弦函数生成季节性步地,并添加随即噪声。绘图原始数据:绘图原始的月度销售数据。计较转移平均:使用周折窗口循序计较转移平均。绘图平滑后的数据:相比平滑后的数据与原始数据。计较并绘图残差:计较残差并绘图残差时期序列。绘图自干系图和偏自干系图:分析残差的自干系性和偏自干系性。 图片 3. 自转头滑动平均 (ARMA, Autoregressive Moving Average Model)ARMA模子招引了自转头和转移平均模子。 旨趣模子左右前 p 个时期点的数据和前 q 个时期点的罪戾掂量面前时期点的数据。 中枢公式ARMA模子是将自转头模子和转移平均模子招引,左右两者的推导循序,对两个模子的参数进行联络料到。 中枢案例代码中,我们使用Python中的 statsmodels 库来进行ARMA建模和分析,并使用 matplotlib 来绘图图形。 import numpy as npimport matplotlib.pyplot as pltimport pandas as pdfrom statsmodels.tsa.arima.model import ARIMAfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 生成示例时期序列数据np.random.seed(42)n = 200ar_params = np.array([0.75, -0.25])ma_params = np.array([0.65, 0.35])ar = np.r_[1, -ar_params] # add zero-lag and negatema = np.r_[1, ma_params] # add zero-lagy = np.random.normal(size=n)x = np.convolve(y, ma)[:n] np.random.normal(size=n)time_series = pd.Series(x)# 绘图原始时期序列数据plt.figure(figsize=(12, 6))plt.plot(time_series, label='Original Time Series')plt.title('Original Time Series')plt.xlabel('Time')plt.ylabel('Value')plt.legend()plt.show()# 绘图自干系图 (ACF) 和偏自干系图 (PACF)fig, axes = plt.subplots(1, 2, figsize=(16, 6))plot_acf(time_series, ax=axes[0], title='Autocorrelation Function (ACF)')plot_pacf(time_series, ax=axes[1], title='Partial Autocorrelation Function (PACF)')plt.show()# 修复并拟合ARMA模子model = ARIMA(time_series, order=(2, 0, 2))arma_result = model.fit()# 打印模子选录print(arma_result.summary())# 绘图拟合后的时期序列和残差图plt.figure(figsize=(12, 6))plt.plot(time_series, label='Original Time Series')plt.plot(arma_result.fittedvalues, color='red', label='Fitted Values')plt.title('Original and Fitted Time Series')plt.xlabel('Time')plt.ylabel('Value')plt.legend()plt.show()# 绘图残差图residuals = arma_result.residplt.figure(figsize=(12, 6))plt.plot(residuals, label='Residuals')plt.title('Residuals of ARMA Model')plt.xlabel('Time')plt.ylabel('Residual')plt.legend()plt.show()生成示例时期序列数据:我们生成一个包含200个数据点的时期序列,使用自转头参数 ar_params 和转移平均参数 ma_params。绘图原始时期序列数据:使用 matplotlib 绘图原始时期序列数据。绘图ACF和PACF图:使用 statsmodels 库的 plot_acf 和 plot_pacf 函数绘图自干系函数 (ACF) 和偏自干系函数 (PACF) 图。修复并拟合ARMA模子:使用 statsmodels 库中的 ARIMA 函数修复ARMA模子并进行拟合。打印模子选录:打印拟合终端的选录,包含模子参数和统计信息。绘图拟合后的时期序列和残差图:绘图原始时期序列与模子拟合值的对比图,以及模子残差图。图片 4. 自转头积分滑动平均 (ARIMA, Autoregressive Integrated Moving Average Model)ARIMA模子扩张了ARMA模子,适用于非沉着时期序列。 旨趣模子通过对数据进行差分处理,使其沉着,然后再应用ARMA模子。 中枢公式其中: 是滞后算子, 是差分次数。通过对原始序列 进行 d 次差分,使其变为沉着序列 ,然后对沉着序列应用ARMA模子进行参数料到。 中枢案例虽然不错!底下是一个对于时期序列分析的案例,使用 ARIMA 模子来分析和掂量数据。我们将使用 Python 的 pandas、numpy、matplotlib 和 statsmodels 库来完成这项任务。具体案例为模拟一个经济数据的时期序列,举例股票价钱或经济计算。 案例详尽创建一个模拟的时期序列数据,应用 ARIMA 模子进行建模和掂量,并画出原始数据、ACF (自干系函数) 图和掂量终端图。 import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport statsmodels.api as smfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf# 1. 创建模拟时期序列数据np.random.seed(42)n = 200time = np.arange(n)data = np.sin(0.1 * time) 0.5 * np.random.randn(n)# 治愈为 Pandas DataFramedf = pd.DataFrame(data, columns=['Value'])df.index = pd.date_range(start='2020-01-01', periods=n, freq='D')# 2. 绘图原始时期序列图plt.figure(figsize=(14, 7))plt.subplot(3, 1, 1)plt.plot(df.index, df['Value'], label='Original Data')plt.title('Original Time Series')plt.xlabel('Date')plt.ylabel('Value')plt.legend()# 3. 绘图自干系函数 (ACF) 和偏自干系函数 (PACF) 图plt.subplot(3, 1, 2)plot_acf(df['Value'], ax=plt.gca(), lags=30)plt.title('ACF of Time Series')plt.subplot(3, 1, 3)plot_pacf(df['Value'], ax=plt.gca(), lags=30)plt.title('PACF of Time Series')plt.tight_layout()plt.show()# 4. 应用 ARIMA 模子from statsmodels.tsa.arima.model import ARIMA# 拟合 ARIMA 模子model = ARIMA(df['Value'], order=(5, 0, 0)) # (p, d, q) 这里 d=0 是因为数据莫得差分model_fit = model.fit()# 打印模子选录print(model_fit.summary())# 5. 掂量改日 20 个时期点forecast = model_fit.forecast(steps=20)# 创建掂量数据的时期序列forecast_index = pd.date_range(start=df.index[-1] pd.Timedelta(days=1), periods=20, freq='D')forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=['Forecast'])# 6. 绘图掂量终端图plt.figure(figsize=(14, 7))plt.plot(df.index, df['Value'], label='Original Data')plt.plot(forecast_df.index, forecast_df['Forecast'], color='red', linestyle='--', label='Forecast')plt.title('Forecast using ARIMA Model')plt.xlabel('Date')plt.ylabel('Value')plt.legend()plt.show()数据生成: 使用正弦函数加上随即噪声生成模拟时期序列数据。图形展示:原始时期序列图:展示生成的时期序列数据。自干系函数 (ACF) 图和偏自干系函数 (PACF) 图:用于驯服 ARIMA 模子的参数。ARIMA 模子:使用 ARIMA 类来拟合模子并进行掂量。打印模子选录以稽查拟合终端。掂量终端图: 展示 ARIMA 模子的掂量终端与原始数据。 图片 5. 季节性自转头积分滑动平均 (SARIMA, Seasonal ARIMA)SARIMA模子扩张了ARIMA模子,适用于季节性时期序列。 旨趣模子招引了季节性自转头、季节性差分和季节性转移平均因素。 中枢公式其中: 是季节周期, 是季节差分次数。将季节性因素加入到ARIMA模子中,招引季节性自转头、季节性差分和季节性转移平均,对模子进行参数料到。 中枢案例以下是一个对于月度航空乘客数目数据的案例分析,该数据集包含1949年1月到1960年12月之间的月度航空乘客数目。我们使用SARIMA模子对该数据进行建模,并绘图干系的图形进行数据分析。 import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.stattools import adfuller, acf, pacf# 加载航空乘客数据集file = 'airline-passengers.csv'data = pd.read_csv(file, index_col='Month', parse_dates=True)data.index.freq = 'MS'# 绘图原始数据plt.figure(figsize=(10, 6))plt.plot(data, label='Monthly Airline Passengers')plt.title('Monthly Airline Passengers from 1949 to 1960')plt.xlabel('Date')plt.ylabel('Number of Passengers')plt.legend()plt.show()# 进行ADF老师adf_result = adfuller(data['Passengers'])print(f'ADF Statistic: {adf_result[0]}')print(f'p-value: {adf_result[1]}')# 绘图ACF和PACF图lag_acf = acf(data['Passengers'], nlags=40)lag_pacf = pacf(data['Passengers'], nlags=40, method='ols')plt.figure(figsize=(12, 6))plt.subplot(121)plt.stem(range(len(lag_acf)), lag_acf, linefmt='b-', markerfmt='bo', basefmt='r-')plt.axhline(y=0, linestyle='--', color='gray')plt.axhline(y=-1.96/np.sqrt(len(data)), linestyle='--', color='gray')plt.axhline(y=1.96/np.sqrt(len(data)), linestyle='--', color='gray')plt.title('Autocorrelation Function')plt.subplot(122)plt.stem(range(len(lag_pacf)), lag_pacf, linefmt='b-', markerfmt='bo', basefmt='r-')plt.axhline(y=0, linestyle='--', color='gray')plt.axhline(y=-1.96/np.sqrt(len(data)), linestyle='--', color='gray')plt.axhline(y=1.96/np.sqrt(len(data)), linestyle='--', color='gray')plt.title('Partial Autocorrelation Function')plt.tight_layout()plt.show()# 拟合SARIMA模子model = SARIMAX(data['Passengers'], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))results = model.fit()# 打印模子总结print(results.summary())# 绘图掂量终端data['forecast'] = results.predict(start=120, end=144, dynamic=True)plt.figure(figsize=(10, 6))plt.plot(data['Passengers'], label='Actual Passengers')plt.plot(data['forecast'], label='Forecasted Passengers', color='red')plt.title('Actual vs Forecasted Passengers')plt.xlabel('Date')plt.ylabel('Number of Passengers')plt.legend()plt.show()加载并绘图月度航空乘客数据的原始数据图。使用ADF老师查验数据的沉着性。绘图自干系函数(ACF)和偏自干系函数(PACF)图,以匡助驯服模子的阶数。使用SARIMA模子拟合数据并打印模子总结。绘图本色数据与掂量数据的对比图。图片 6. 向量自转头 (VAR, Vector Autoregression)VAR模子是自转头模子的多变量扩张,适用于多变量时期序列。 旨趣模子左右多个时期序列的历史数据进行联络掂量。 中枢公式其中: 是多变量时期序列向量, 是悉数矩阵。对多变量时期序列进行线性转头,使用最小二乘法求解悉数矩阵 。 中枢案例使用好意思国经济时期序列数据集,该数据集包括了破费、收入和投资的月度数据。这个数据集不错在 statsmodels 库中找到。 import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom statsmodels.tsa.api import VAR# 加载数据集from statsmodels.datasets.macrodata import load_pandasdata = load_pandas().data# 聘用感趣味的变量df = data[['realgdp', 'realcons', 'realinv']]# 建立时期索引dates = pd.date_range(start='1959Q1', periods=len(df), freq='Q')df.index = dates# 绘图原始数据的时期序列图fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))df.plot(subplots=True, ax=axes)plt.tight_layout()plt.show()# 计较一阶差分df_diff = df.diff().dropna()# 绘图差分后的数据fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))df_diff.plot(subplots=True, ax=axes)plt.tight_layout()plt.show()# 构建并老师VAR模子model = VAR(df_diff)results = model.fit(maxlags=15, ic='aic')# 打印模子选录print(results.summary())# 绘图模子残差的时期序列图fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))for i, column in enumerate(df_diff.columns): axes[i].plot(results.resid[:, i]) axes[i].set_title(f'Residuals of {column}')plt.tight_layout()plt.show()# 掂量改日的时期序列lag_order = results.k_arforecast = results.forecast(df_diff.values[-lag_order:], steps=10)forecast_index = pd.date_range(start=df.index[-1], periods=10, freq='Q')forecast_df = pd.DataFrame(forecast, index=forecast_index, columns=df.columns)# 绘图掂量终端fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(10, 8))for i, column in enumerate(df.columns): axes[i].plot(df.index, df[column], label='Original') axes[i].plot(forecast_df.index, forecast_df[column], label='Forecast') axes[i].set_title(f'{column} - Original vs Forecast') axes[i].legend()plt.tight_layout()plt.show()加载了包含好意思国经济数据的宏不雅经济数据集。聘用了本色GDP、本色破费和本色投资行为分析变量。绘图了原始数据和一阶差分后的数据的时期序列图。构建并老师了VAR模子,并打印了模子选录。绘图了模子残差的时期序列图。掂量了改日10个季度的时期序列,并绘图了掂量终端与原始数据的对比图。 图片 7. 向量自转头滑动平均 (VARMA, Vector Autoregressive Moving Average)VARMA模子招引了向量自转头和转移平均模子。 旨趣模子左右多个时期序列的历史数据和罪戾进行联络掂量。 中枢公式其中: 是罪戾悉数矩阵。招引VAR模子和MA模子的推导循序,对两个模子的参数进行联络料到。 中枢案例时期序列分析中的向量自转头滑动平均(VARMA)模子时时用于分析多个干系联的时期序列变量之间的动态关系。 假定我们有两个变量,区别是销售量和告白支拨,我们思分析它们之间的动态关系。我们将构建一个VARMA(1,1)模子来讲明。 import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom statsmodels.tsa.statespace.varmax import VARMAXfrom statsmodels.tsa.vector_ar.var_model import VAR# 生成模拟数据np.random.seed(42)n_obs = 100sales = np.random.normal(loc=100, scale=15, size=n_obs)advertising = np.random.normal(loc=50, scale=10, size=n_obs)# 创建DataFramedata = pd.DataFrame({'Sales': sales, 'Advertising': advertising})# 拆分数据为老师集和测试集train = data.iloc[:80]test = data.iloc[80:]# 拟合VARMA模子model = VARMAX(train, order=(1, 1))results = model.fit(maxiter=1000, disp=False)print(results.summary())# 掂量改日值forecast = results.forecast(steps=len(test))# 绘图销售量和告白支拨的时期序列及掂量终端plt.figure(figsize=(14, 7))plt.subplot(2, 1, 1)plt.plot(train['Sales'], label='Actual Sales (Train)')plt.plot(test.index, forecast['Sales'], label='Forecasted Sales')plt.title('Sales Forecast using VARMA(1,1)')plt.legend()plt.subplot(2, 1, 2)plt.plot(train['Advertising'], label='Actual Advertising (Train)')plt.plot(test.index, forecast['Advertising'], label='Forecasted Advertising')plt.title('Advertising Forecast using VARMA(1,1)')plt.legend()plt.tight_layout()plt.show()我们率先生成了模拟数据,模拟了销售量和告白支拨的时期序列。将数据分为老师集和测试集。使用VARMAX模子拟合了VARMA(1,1)模子。对测试集进行掂量,并绘图了销售量和告白支拨的本色数据以及掂量终端的时期序列图。图片 8. 诟谇期追念蚁集 (LSTM, Long Short-Term Memory)LSTM是一种出奇的递归神经蚁集(RNN),适用于捕捉万古期依赖关系。 旨趣LSTM通过引入追念单位和门控机制,灵验料理了RNN的梯度隐没问题。 中枢公式LSTM通过追念单位 和三个门控单位(淡忘门 ,输初学 和输外出 )进行信息收敛。推导经由不错通过反向传播算法进行参数优化。 中枢案例使用Keras来构建和老师LSTM模子,并使用Matplotlib来绘图数据分析图形。我们使用一个粗拙的模拟时期序列数据来演示LSTM模子的应用。该数据代表某种时期序列,举例逐日温度变化。 import numpy as npimport matplotlib.pyplot as plt# 生成模拟时期序列数据np.random.seed(0)time_steps = 100data = np.sin(np.linspace(0, 10 * np.pi, time_steps)) np.random.normal(0, 0.5, time_steps)# 绘图原始数据plt.figure(figsize=(14, 6))plt.plot(data, label='Original Data')plt.title('Simulated Time Series Data')plt.xlabel('Time Step')plt.ylabel('Value')plt.legend()plt.show()# 构建LSTM模子import tensorflow as tffrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import LSTM, Dense# 准备老师数据def create_dataset(data, look_back=1): X, y = [], [] for i in range(len(data) - look_back): X.append(data[i:(i look_back)]) y.append(data[i look_back]) return np.array(X), np.array(y)look_back = 3X, y = create_dataset(data, look_back)X = X.reshape(X.shape[0], X.shape[1], 1) # LSTM 需要 3D 输入# 构建 LSTM 模子model = Sequential()model.add(LSTM(50, input_shape=(look_back, 1)))model.add(Dense(1))model.compile(loss='mean_squared_error', optimizer='adam')# 老师模子model.fit(X, y, epochs=100, batch_size=1, verbose=2)# 掂量并绘图终端train_predict = model.predict(X)train_predict_plot = np.empty_like(data)train_predict_plot[:] = np.nantrain_predict_plot[look_back:len(train_predict) look_back] = train_predict.flatten()# 绘图原始数据与掂量数据对比图plt.figure(figsize=(14, 6))plt.plot(data, label='Original Data')plt.plot(train_predict_plot, label='LSTM Prediction')plt.title('LSTM Prediction vs Original Data')plt.xlabel('Time Step')plt.ylabel('Value')plt.legend()plt.show()# 绘图蚀本函数变化图history = model.historyloss = history.history['loss']plt.figure(figsize=(14, 6))plt.plot(loss, label='Training Loss')plt.title('Model Training Loss Over Epochs')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()plt.show() 两个数据分析图形:一个是原始数据与LSTM掂量数据的对比图,另一个是老师经由中蚀本函数的变化图。 图片 9. ProphetProphet是由Facebook设备的时期序列掂量器用,适用于包含节沐日效应、趋势变化和周期性变化的数据。 旨趣模子将时期序列判辨为趋势、季节性和节沐日效应部分。 中枢公式其中: 示意趋势部分, 示意季节性部分, 示意节沐日效应。通过对各部分进行孤独建模和参数料到,最终招引各部分得到掂量终端。 中枢案例底下是一个使用 Facebook 的 Prophet 库进行时期序列分析的案例。在这个案例中,我们将使用 Prophet 对一个时期序列进行建模和掂量,并绘图多个图形来展示数据分析的终端。 我们将使用一个示例数据集,该数据集包含了某网站逐日的造访量。我们将进行以下门径: 导入数据并预处理。使用 Prophet 进行建模和掂量。绘图原始数据及掂量终端。绘图掂量中的趋势和季节性因素。import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom prophet import Prophet# 生成示例数据dates = pd.date_range(start='2020-01-01', periods=730, freq='D')data = np.random.poisson(lam=200, size=730) np.linspace(0, 100, 730)df = pd.DataFrame({'ds': dates, 'y': data})# 启动化并老师Prophet模子model = Prophet(yearly_seasonality=True, daily_seasonality=False)model.fit(df)# 创建改日的数据框架并进行掂量future = model.make_future_dataframe(periods=365)forecast = model.predict(future)# 绘图原始数据及掂量终端fig1 = model.plot(forecast)plt.title('Original Data and Forecast')plt.xlabel('Date')plt.ylabel('Website Traffic')# 绘图趋势和季节性因素fig2 = model.plot_components(forecast)plt.show()# 绘图本色数据与掂量值的对比plt.figure(figsize=(10, 6))plt.plot(df['ds'], df['y'], label='Actual')plt.plot(forecast['ds'], forecast['yhat'], label='Forecast', linestyle='--')plt.fill_between(forecast['ds'], forecast['yhat_lower'], forecast['yhat_upper'], color='gray', alpha=0.2)plt.title('Actual vs Forecast')plt.xlabel('Date')plt.ylabel('Website Traffic')plt.legend()plt.show()# 绘图残差图residuals = df['y'] - forecast['yhat'][:len(df)]plt.figure(figsize=(10, 6))plt.plot(df['ds'], residuals)plt.axhline(0, linestyle='--', color='red')plt.title('Residuals')plt.xlabel('Date')plt.ylabel('Residual')plt.show()数据生成和预处理:使用 pandas 生成了从 2020 年 1 月 1 日入手的 730 天的日历范围。生成了一个示例数据集,模拟了网站的逐日造访量。 模子老师:启动化 Prophet 模子,并建立年度季节性为真,逐日季节性为假。使用示例数据集老师模子。 掂量:创建一个包含改日 365 天的日历的数据框架,并使用老师好的模子进行掂量。绘图原始数据及掂量终端图,展示了本色数据与掂量值的对比。 趋势和季节性因素:绘图趋势和季节性因素图,展示了掂量中的永久趋势和季节性波动。 本色数据与掂量值的对比:将本色数据与掂量值进行对比,展示了掂量模子的拟合效用。 残差图:计较残差(本色值减去掂量值),并绘图残差图,展示了模子的掂量罪戾。 图片 图片 10. 变分自编码器 (VAE, Variational Autoencoders)VAE是一种生成模子,适用于捕捉复杂时期序列数据的潜在结构。 旨趣VAE通过变分推断,将复杂的时期序列数据映射到潜在空间,然后再从潜在空间重构数据。 中枢公式VAE使用变分推断的循序,最大化对数似然函数: 其中: 是Kullback-Leibler散度。VAE通过神经蚁集来参数化 和 ,使用反向传播算法进行优化。 这些循序各自有其适用的场景和优迤逦,聘用顺应的循序取决于具体的数据特征和分析需求。 中枢案例这里,是一个使用变分自编码器(VAE)进行时期序列分析的案例: 生成正弦波时期序列数据。构建和老师变分自编码器(VAE)。使用VAE对时期序列数据进行编码妥协码。绘图原始时期序列与重构时期序列的对比图。绘图VAE潜在空间的可视化图。import numpy as npimport matplotlib.pyplot as pltimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import DataLoader, Dataset# 生成正弦波时期序列数据def generate_sine_wave(seq_length, num_samples): x = np.linspace(0, np.pi * 2 * num_samples, seq_length * num_samples) y = np.sin(x) data = y.reshape(num_samples, seq_length, 1) return dataseq_length = 50num_samples = 1000data = generate_sine_wave(seq_length, num_samples)# 数据集类class TimeSeriesDataset(Dataset): def __init__(self, data): self.data = torch.tensor(data, dtype=torch.float32) def __len__(self): return len(self.data) def __getitem__(self, idx): return self.data[idx]dataset = TimeSeriesDataset(data)dataloader = DataLoader(dataset, batch_size=32, shuffle=True)# 界说VAE模子:class VAE(nn.Module): def __init__(self, input_dim, hidden_dim, latent_dim): super(VAE, self).__init__() # 编码器 self.encoder = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, latent_dim * 2) # 输出mean和logvar ) # 解码器 self.decoder = nn.Sequential( nn.Linear(latent_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, input_dim), nn.Sigmoid() ) def reparameterize(self, mean, logvar): std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return mean eps * std def forward(self, x): x = x.view(x.size(0), -1) mean_logvar = self.encoder(x) mean, logvar = mean_logvar[:, :latent_dim], mean_logvar[:, latent_dim:] z = self.reparameterize(mean, logvar) x_recon = self.decoder(z) return x_recon, mean, logvar# 老师VAE模子:input_dim = seq_lengthhidden_dim = 128latent_dim = 16num_epochs = 50learning_rate = 0.001vae = VAE(input_dim, hidden_dim, latent_dim)optimizer = optim.Adam(vae.parameters(), lr=learning_rate)criterion = nn.MSELoss()def loss_function(recon_x, x, mean, logvar): recon_loss = criterion(recon_x, x) kld_loss = -0.5 * torch.sum(1 logvar - mean.pow(2) - logvar.exp()) return recon_loss kld_lossfor epoch in range(num_epochs): vae.train() train_loss = 0 for batch in dataloader: optimizer.zero_grad() recon_batch, mean, logvar = vae(batch) loss = loss_function(recon_batch, batch.view(-1, input_dim), mean, logvar) loss.backward() train_loss = loss.item() optimizer.step() print(f'Epoch {epoch 1}, Loss: {train_loss / len(dataloader.dataset)}')# 绘图原始时期序列与重构时期序列的对比图vae.eval()with torch.no_grad(): for batch in dataloader: recon_batch, mean, logvar = vae(batch) breakrecon_batch = recon_batch.view(-1, seq_length).numpy()original_batch = batch.numpy()plt.figure(figsize=(12, 6))plt.plot(original_batch[0], label='Original')plt.plot(recon_batch[0], label='Reconstructed')plt.legend()plt.title('Original vs Reconstructed Time Series')plt.show()# 绘图VAE潜在空间的可视化图latent_vectors = []vae.eval()with torch.no_grad(): for batch in dataloader: _, mean, _ = vae(batch) latent_vectors.append(mean.numpy())latent_vectors = np.concatenate(latent_vectors, axis=0)plt.figure(figsize=(10, 8))plt.scatter(latent_vectors[:, 0], latent_vectors[:, 1], alpha=0.5)plt.title('Latent Space Visualization')plt.xlabel('Latent Dimension 1')plt.ylabel('Latent Dimension 2')plt.show() 图片 终末 以上即是今天悉数的内容了。淌若对你来说相比有用,牢记点赞、保藏,逐渐学习~下期会有更多干货等着你!~ 本站仅提供存储业绩,悉数内容均由用户发布,如发现存害或侵权内容,请点击举报。 |