矢量化线性模型
Vectorized liner model
在 R 中使用 lm() 我可以执行以下操作
fit <- lm(organ_volumes~sex+genotype, data=factors)
其中器官体积是一个矩阵,其中每一列都是不同的变量。每列依次适合线性模型,如 lm 文档中所述:
If response is a matrix a linear model is fitted separately by least-squares to each column of the matrix.
有什么方法可以使用 statsmodels 在 Python 中做类似的事情,而不必遍历每一列,这比 R 方法慢得多?
您可以在 scikit 中尝试以下操作,请注意有时对于相关因变量,输出与 R 不同:
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data= iris['data'],
columns= iris['feature_names'] )
from sklearn import linear_model
clf = linear_model.LinearRegression()
X = df[['sepal length (cm)','sepal width (cm)']]
Y = df[['petal length (cm)','petal width (cm)']]
clf.fit(X,Y)
clf.coef_
array([[ 1.77559255, -1.33862329],
[ 0.723292 , -0.47872132]])
在 R 中:
data = as.matrix(iris[,-5])
lm(data[,c(1,3)] ~ data[,c(2,4)])
Call:
lm(formula = data[, c(1, 3)] ~ data[, c(2, 4)])
Coefficients:
Sepal.Length Petal.Length
(Intercept) 3.4573 2.2582
data[, c(2, 4)]Sepal.Width 0.3991 -0.3550
data[, c(2, 4)]Petal.Width 0.9721 2.1556
在 R 中使用 lm() 我可以执行以下操作
fit <- lm(organ_volumes~sex+genotype, data=factors)
其中器官体积是一个矩阵,其中每一列都是不同的变量。每列依次适合线性模型,如 lm 文档中所述:
If response is a matrix a linear model is fitted separately by least-squares to each column of the matrix.
有什么方法可以使用 statsmodels 在 Python 中做类似的事情,而不必遍历每一列,这比 R 方法慢得多?
您可以在 scikit 中尝试以下操作,请注意有时对于相关因变量,输出与 R 不同:
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data= iris['data'],
columns= iris['feature_names'] )
from sklearn import linear_model
clf = linear_model.LinearRegression()
X = df[['sepal length (cm)','sepal width (cm)']]
Y = df[['petal length (cm)','petal width (cm)']]
clf.fit(X,Y)
clf.coef_
array([[ 1.77559255, -1.33862329],
[ 0.723292 , -0.47872132]])
在 R 中:
data = as.matrix(iris[,-5])
lm(data[,c(1,3)] ~ data[,c(2,4)])
Call:
lm(formula = data[, c(1, 3)] ~ data[, c(2, 4)])
Coefficients:
Sepal.Length Petal.Length
(Intercept) 3.4573 2.2582
data[, c(2, 4)]Sepal.Width 0.3991 -0.3550
data[, c(2, 4)]Petal.Width 0.9721 2.1556