生成一个线性回归的python代码
时间: 2023-03-15 19:59:57 浏览: 60
import numpy as np
from sklearn.linear_model import LinearRegression # 设置自变量和因变量
x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([5, 20, 14, 32, 22, 38]) # 创建并训练模型
model = LinearRegression().fit(x, y) # 获取预测结果
r_sq = model.score(x, y)
intercept, coefficients = model.intercept_, model.coef_
y_pred = model.predict(x) # 打印输出
print('coefficient of determination:', r_sq)
print('intercept:', intercept)
print('coefficients:', coefficients)
print('predicted response:', y_pred, sep='\n')
相关问题
写一个线性回归python代码
以下是一个基本的线性回归Python代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(0)
x = np.random.rand(100, 1)
y = 2 + 3 * x + np.random.rand(100, 1)
# 绘制散点图
plt.scatter(x, y, s=10)
plt.xlabel('x')
plt.ylabel('y')
# 计算参数
x_mean = np.mean(x)
y_mean = np.mean(y)
numerator = 0
denominator = 0
for i in range(len(x)):
numerator += (x[i] - x_mean) * (y[i] - y_mean)
denominator += (x[i] - x_mean) ** 2
beta = numerator / denominator
alpha = y_mean - beta * x_mean
# 绘制线性回归线
x_plot = np.linspace(0, 1, 2)
y_plot = alpha + beta * x_plot
plt.plot(x_plot, y_plot, color='r')
plt.show()
```
运行代码后,将生成一个随机数据的散点图和线性回归线。其中,代码首先生成了随机数据,然后计算出了线性回归的参数,最后绘制了散点图和线性回归线。
线性回归 Python代码
下面是一个简单的线性回归 Python 代码示例:
```python
import numpy as np
from sklearn.linear_model import LinearRegression
# 生成数据
np.random.seed(0)
X = np.random.rand(100, 1)
y = 2 + 3 * X + np.random.rand(100, 1)
# 建立模型
model = LinearRegression()
model.fit(X, y)
# 预测
x_new = np.array([[0.5]])
y_new = model.predict(x_new)
# 输出结果
print(y_new)
```
在这个示例中,我们使用 `numpy` 生成了随机数据,然后使用 `LinearRegression` 类从 `sklearn.linear_model` 模块中创建了一个线性回归模型。我们使用 `fit` 方法拟合模型,并使用 `predict` 方法预测新的输入数据。最后,我们使用 `print` 函数输出预测结果。