這是被問及其他地方的一個不同的軟件包,但是Scikit有沒有一種方法學習包括所有變量或所有變量減去R中的某個指定數?將模型擬合到Python中的所有變量(Scikit學習)
舉一個我的意思的例子,說我有一個迴歸y = x1 + x2 + x3 + x4。在R I可以通過運行評估這個迴歸:
result = lm(y ~ ., data=DF)
summary(result)
我會想象有一個類似的方式凝結在Python中的公式,因爲寫出所有的變量更大的數據集將是一種愚蠢的。
這是被問及其他地方的一個不同的軟件包,但是Scikit有沒有一種方法學習包括所有變量或所有變量減去R中的某個指定數?將模型擬合到Python中的所有變量(Scikit學習)
舉一個我的意思的例子,說我有一個迴歸y = x1 + x2 + x3 + x4。在R I可以通過運行評估這個迴歸:
result = lm(y ~ ., data=DF)
summary(result)
我會想象有一個類似的方式凝結在Python中的公式,因爲寫出所有的變量更大的數據集將是一種愚蠢的。
我們可以嘗試以下解決方法(我們使用iris
數據集和數字標籤species
,適合線性迴歸模型,看看如何使用這兩種在R
和python sklearn
的獨立預測指標):
就R
summary(lm(as.numeric(Species)~., iris))[c('coefficients', 'r.squared')]
$coefficients
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.18649525 0.20484104 5.792273 4.150495e-08
Sepal.Length -0.11190585 0.05764674 -1.941235 5.416918e-02
Sepal.Width -0.04007949 0.05968881 -0.671474 5.029869e-01
Petal.Length 0.22864503 0.05685036 4.021874 9.255215e-05
Petal.Width 0.60925205 0.09445750 6.450013 1.564180e-09
$r.squared
[1] 0.9303939
在Python(sklearn與糊狀)
from sklearn.datasets import load_iris
import pandas as pd
from patsy import dmatrices
iris = load_iris()
names = [f_name.replace(" ", "_").strip("_(cm)") for f_name in iris.feature_names]
iris_df = pd.DataFrame(iris.data, columns=names)
iris_df['species'] = iris.target
# pasty does not support '.' at least in windows python 2.7, so here is the workaround
y, X = dmatrices('species ~ ' + '+'.join(iris_df.columns - ['species']),
iris_df, return_type="dataframe")
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X, y)
print model.score(X,y)
# 0.930422367533
print model.intercept_, model.coef_
# [ 0.19208399] [[0.22700138 0.60989412 -0.10974146 -0.04424045]]
正如我們所看到的,在R
和Python
中學習的模型與pasty
是相似的(係數的順序是不同的)。
'statsmodels'原生支持'patsy' forumals ...可能值得一提... http://statsmodels.sourceforge.net/0.6.0/examples/notebooks/generated/formulas.html –
Scikit有沒有辦法學會包括所有變量或所有變量減去一些指定的數字?
是的,sklearn +熊貓,以適應使用除此之外的所有變量,並用它作爲一個標籤,你可以做簡單的
model.fit(df.drop('y', axis=1), df['y'])
,這將適用於大多數sklearn
車型。
這將是pandas
+ sklearn
等效的r ~
和-
符號的,如果不使用pasty
。
要排除多個變量,你可以做
df.drop(['v1', 'v2'], axis=1)
我不這麼認爲,這裏是sklearn [這裏](http://scikit-learn.org/stable/auto_examples/linear_model爲例/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py) – cdeterman
@lmo我用兩個標記了它,因爲我認爲R用戶和Scikit用戶之間可能會有重疊。 – 114
@ 114你究竟在做什麼?你能舉一個玩具的例子嗎? –