- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我尝试使用 sklearn 线性回归模型同时预测多个独立的时间序列,但我似乎无法正确预测。
我的数据组织如下:Xn
是一个矩阵,其中每一行包含一个包含 4 个观测值的预测窗口,yn
是 每一行的目标值>Xn
.
import numpy as np
# training data
X1=np.array([[-0.31994,-0.32648,-0.33264,-0.33844],[-0.32648,-0.33264,-0.33844,-0.34393],[-0.33264,-0.33844,-0.34393,-0.34913],[-0.33844,-0.34393,-0.34913,-0.35406],[-0.34393,-0.34913,-.35406,-0.35873],[-0.34913,-0.35406,-0.35873,-0.36318],[-0.35406,-0.35873,-0.36318,-0.36741],[-0.35873,-0.36318,-0.36741,-0.37144],[-0.36318,-0.36741,-0.37144,-0.37529],[-0.36741,-.37144,-0.37529,-0.37896],[-0.37144,-0.37529,-0.37896,-0.38069],[-0.37529,-0.37896,-0.38069,-0.38214],[-0.37896,-0.38069,-0.38214,-0.38349],[-0.38069,-0.38214,-0.38349,-0.38475],[-.38214,-0.38349,-0.38475,-0.38593],[-0.38349,-0.38475,-0.38593,-0.38887]])
X2=np.array([[-0.39265,-0.3929,-0.39326,-0.39361],[-0.3929,-0.39326,-0.39361,-0.3931],[-0.39326,-0.39361,-0.3931,-0.39265],[-0.39361,-0.3931,-0.39265,-0.39226],[-0.3931,-0.39265,-0.39226,-0.39193],[-0.39265,-0.39226,-0.39193,-0.39165],[-0.39226,-0.39193,-0.39165,-0.39143],[-0.39193,-0.39165,-0.39143,-0.39127],[-0.39165,-0.39143,-0.39127,-0.39116],[-0.39143,-0.39127,-0.39116,-0.39051],[-0.39127,-0.39116,-0.39051,-0.3893],[-0.39116,-0.39051,-0.3893,-0.39163],[-0.39051,-0.3893,-0.39163,-0.39407],[-0.3893,-0.39163,-0.39407,-0.39662],[-0.39163,-0.39407,-0.39662,-0.39929],[-0.39407,-0.39662,-0.39929,-0.4021]])
# target values
y1=np.array([-0.34393,-0.34913,-0.35406,-0.35873,-0.36318,-0.36741,-0.37144,-0.37529,-0.37896,-0.38069,-0.38214,-0.38349,-0.38475,-0.38593,-0.38887,-0.39184])
y2=np.array([-0.3931,-0.39265,-0.39226,-0.39193,-0.39165,-0.39143,-0.39127,-0.39116,-0.39051,-0.3893,-0.39163,-0.39407,-0.39662,-0.39929,-0.4021,-0.40506])
按预期工作的单个时间序列的正常过程如下:
from sklearn.linear_model import LinearRegression
# train the 1st half, predict the 2nd half
half = len(y1)/2 # or y2 as they have the same length
LR = LinearRegression()
LR.fit(X1[:half], y1[:half])
pred = LR.predict(X1[half:])
r_2 = LR.score(X1[half:],y1[half:])
但是如何将线性回归模型同时应用于多个独立的时间序列呢?我尝试了以下方法:
y_stack = np.vstack((y1[None],y2[None]))
X_stack = np.vstack((X1[None],X2[None]))
print 'y1 shape:',y1.shape, 'X1 shape:',X1.shape
print 'y_stack shape:',y_stack.shape, 'X_stack:',X_stack.shape
y1 shape: (16,) X1 shape: (16, 4)
y_stack shape: (2, 16) X_stack: (2, 16, 4)
但是线性模型的拟合失败如下:
LR.fit(X_stack[:,half:],y_stack[:,half:])
声明维数高于预期:
C:\Python27\lib\site-packages\sklearn\utils\validation.pyc in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
394 if not allow_nd and array.ndim >= 3:
395 raise ValueError("Found array with dim %d. %s expected <= 2."
--> 396 % (array.ndim, estimator_name))
397 if force_all_finite:
398 _assert_all_finite(array)
ValueError: Found array with dim 3. Estimator expected <= 2.
非常感谢任何建议或提示。
更新
我可以使用 for 循环,但由于 n
实际上是 10000 或更多,我希望找到包含数组操作的解决方案,因为这些是 numpy 的显式功能, scipy 并希望 sklearn
最佳答案
@ali_m 我不认为这是一个重复的问题,但它们部分相关。当然,可以使用类似于 sklearn 的线性回归模型同时应用和预测时间序列:
我创建了一个新类 LinearRegression_Multi
:
class LinearRegression_Multi:
def stacked_lstsq(self, L, b, rcond=1e-10):
"""
Solve L x = b, via SVD least squares cutting of small singular values
L is an array of shape (..., M, N) and b of shape (..., M).
Returns x of shape (..., N)
"""
u, s, v = np.linalg.svd(L, full_matrices=False)
s_max = s.max(axis=-1, keepdims=True)
s_min = rcond*s_max
inv_s = np.zeros_like(s)
inv_s[s >= s_min] = 1/s[s>=s_min]
x = np.einsum('...ji,...j->...i', v,
inv_s * np.einsum('...ji,...j->...i', u, b.conj()))
return np.conj(x, x)
def center_data(self, X, y):
""" Centers data to have mean zero along axis 0.
"""
# center X
X_mean = np.average(X,axis=1)
X_std = np.ones(X.shape[0::2])
X = X - X_mean[:,None,:]
# center y
y_mean = np.average(y,axis=1)
y = y - y_mean[:,None]
return X, y, X_mean, y_mean, X_std
def set_intercept(self, X_mean, y_mean, X_std):
""" Calculate the intercept_
"""
self.coef_ = self.coef_ / X_std # not really necessary
self.intercept_ = y_mean - np.einsum('ij,ij->i',X_mean,self.coef_)
def scores(self, y_pred, y_true ):
"""
The coefficient R^2 is defined as (1 - u/v), where u is the regression
sum of squares ((y_true - y_pred) ** 2).sum() and v is the residual
sum of squares ((y_true - y_true.mean()) ** 2).sum().
"""
u = ((y_true - y_pred) ** 2).sum(axis=-1)
v = ((y_true - y_true.mean(axis=-1)[None].T) ** 2).sum(axis=-1)
r_2 = 1 - u/v
return r_2
def fit(self,X, y):
""" Fit linear model.
"""
# get coefficients by applying linear regression on stack
X_, y, X_mean, y_mean, X_std = self.center_data(X, y)
self.coef_ = self.stacked_lstsq(X_, y)
self.set_intercept(X_mean, y_mean, X_std)
def predict(self, X):
"""Predict using the linear model
"""
return np.einsum('ijx,ix->ij',X,self.coef_) + self.intercept_[None].T
可以按如下方式应用,使用与问题中相同的声明变量:
LR_Multi = LinearRegression_Multi()
LR_Multi.fit(X_stack[:,:half], y_stack[:,:half])
y_stack_pred = LR_Multi.predict(X_stack[:,half:])
R2 = LR_Multi.scores(y_stack_pred, y_stack[:,half:])
多个时间序列的 R^2 是:
array([ 0.91262442, 0.67247516])
这确实和标准的sklearn线性回归的预测方法很相似:
from sklearn.linear_model import LinearRegression
LR = LinearRegression()
LR.fit(X1[:half], y1[:half])
R2_1 = LR.score(X1[half:],y1[half:])
LR.fit(X2[:half], y2[:half])
R2_2 = LR.score(X2[half:],y2[half:])
print R2_1, R2_2
0.912624422097 0.67247516054
关于python - 如何使用scikit线性回归模型同时求解多个独立的时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436828/
我正在使用混合效应模型,并且由于我的方法的特殊性我需要解决下面模型的积分,然后制作图表获得的估计值。 换句话说,我需要求解下面的积分: 其中,di^2 是我模型中的 Var3,dh 是混合效应模型对应
我有一个方程组,我想用数值方法求解它。给定起始种子,我想得到一个接近的解决方案。让我解释。 我有一个常量向量,X,值: X <- (c(1,-2,3,4)) 和一个向量 W 的权重: W <- (c(
假设我有以下方程组: a * b = 5 sqrt(a * b^2) = 10 如何求解 R 中 a 和 b 的这些方程? 我想这个问题可以说是一个优化问题,具有以下功能......? fn <- f
我在 R 中有一个简单的通量模型。它归结为两个微分方程,对模型中的两个状态变量进行建模,我们将它们称为 A和 B .它们被计算为四个分量通量的简单差分方程 flux1-flux4 , 5 个参数 p1
R有什么办法吗?求解给定单变量函数的反函数?动机是我以后告诉R使用值向量作为反函数的输入,以便它可以吐出反函数值。 例如,我有函数 y(x) = x^2 ,逆是 y = sqrt(x) .有没有办法R
我在字符串中有以下方程 y = 18774x + 82795 求解x我会这样做:- x = (y-82795) / 18774 我知道y的值 但是方程一直在变化,并且始终采用字符串格式 是否可以简单地
如果我用 diophantine(2*x+3*y-5*z-77) 我收到了这个结果。 {(t_0, -9*t_0 - 5*t_1 + 154, -5*t_0 - 3*t_1 + 77)} 到目前为止还
我正在尝试求解仅限于正解的 ODE,即: dx/dt=f(x) x>=0。 在 MATLAB 中这很容易实现。 R 是否有任何变通方法或包来将解决方案空间限制为仅正值? 这对我来说非常重要,不幸的是没
下面的 ANTLR 文法中的 'expr' 规则显然是相互左递归的。作为一个 ANTLR 新手,我很难解决这个问题。我已经阅读了 ANTLR 引用书中的“解决非 LL(*) 冲突”,但我仍然没有看到解
我有一个关于在 R 中求解函数的可能性的非常基本的问题,但知道答案确实有助于更好地理解 R。 我有以下等式: 0=-100/(1+r)+(100-50)/(1+r)^2+(100-50)/(1+r)^
我正在编写使用递归回溯来解决 8 个皇后问题的代码(将 n 个国际象棋皇后放在 n × n 的棋盘上,这样皇后就不会互相攻击)。 我的任务是创建两个方法:编写一个公共(public)solveQuee
我不知道在以下情况下如何进行,因为最后一个方程没有所有 4 个变量。所以使用了等式下面的代码,但这是错误的......有谁知道如何进行? 方程: 3a + 4b - 5c + d = 10 2a +
假设我们有这个递归关系,它出现在 AVL 树的分析中: F1 = 1 F2 = 2 Fn = Fn - 1 + Fn - 2 + 1(其中 n ≥ 3) 你将如何解决这个递归以获得 F(n) 的封闭形
在Maple中,有谁知道是否存在一个函数来求解变量?例如,我正在尝试求解 r 的 solve4r=(M-x^y)*(r^(-1)) mod (p-1)。所以我知道 M、x、y 和 p 的值,但不知道
我也问过这个here在声音设计论坛上,但问题是沉重的计算机科学/数学,所以它实际上可能属于这个论坛: 因此,通过读取文件中的二进制文件,我能够成功地找到关于 WAV 文件的所有信息,除了 big si
我有以下问题: 设 a 和 b 为 boolean 变量。是否可以设置 a 和 b 的值以使以下表达式的计算结果为 false? b or (((not a) or (not a)) or (a or
我需要用 C 求解这个超越方程: x = 2.0 - 0.5sen(x) 我试过这个: double x, newx, delta; x = 2.0 - 0.5; newx = sin(x); del
我在 Windows 上使用 OpenCV 3.1。 一段代码: RNG rng; // random number generator cv::Mat rVec = (cv::Mat_(3, 1)
我正在尝试求解一个包含 3 个变量和数量可变的方程的方程组。 基本上,系统的长度在 5 到 12 个方程之间,无论有多少个方程,我都试图求解 3 个变量。 看起来像这样: (x-A)**2 + (y-
我正在尝试为有限差分法设计一种算法,但我有点困惑。所讨论的 ODE 是 y''-5y'+10y = 10x,其中 y(0)=0 且 y(1)=100。所以我需要一种方法来以某种方式获得将从关系中乘以“
我是一名优秀的程序员,十分优秀!