将 R 线性模型重写为 Python

rewrite R linear model to Python

帮助将R线性模型重写为Python。 R代码:

x <- rnorm(10)
y <- 1+x+rnorm(10)
model <- lm(y~x)
res = summary(model)$r.squared
print(res)

Python 代码引发错误 - 'setting an array element with a sequence'。好像少了什么,看不懂

x = np.random.normal(0, 1, 10)
y = [1 + np.random.normal() + v for v in x]
new_list = [x, y]
array = np.array(new_list)
df = pd.DataFrame({'x': [x], 'y': [y]})
model = LinearRegression()
X, y = df[['x', 'y']], df
model.fit(X, y)

statsmodels 库提供了一个简单的线性回归实现,其摘要与 R 类似 table。您可以找到文档 here.

Python:

import numpy as np
import statsmodels.api as sm

x = np.random.normal(0, 1, 10)
y = [1 + np.random.normal() + v for v in x]

#add intercept to x
x = sm.add_constant(x)

#statsmodels ordinary linear regression
model = sm.OLS(y, x)
results = model.fit()

print(results.summary())