python写个线性回归
时间: 2024-01-10 07:21:53 浏览: 15
以下是使用Python进行线性回归的示例代码:
```python
import numpy as np
from sklearn.linear_model import LinearRegression
# 创建训练数据
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
y = np.dot(X, np.array([1, 2])) + 3
# 创建线性回归模型
model = LinearRegression()
# 拟合模型
model.fit(X, y)
# 预测新数据
new_data = np.array([[3, 5], [4, 6]])
predictions = model.predict(new_data)
# 打印预测结果
for i, prediction in enumerate(predictions):
print(f"预测结果 {i+1}: {prediction}")
```
这段代码使用了`numpy`库来创建训练数据和新数据,并使用`sklearn`库中的`LinearRegression`类来创建线性回归模型。首先,我们创建了一个包含特征的训练数据`X`和对应的目标变量`y`。然后,我们使用`fit`方法拟合模型。最后,我们使用训练好的模型对新数据进行预测,并打印预测结果。
相关问题
python,写线性回归
好的,下面是一个简单的 Python 代码实现线性回归模型:
```python
import numpy as np
class LinearRegression:
def __init__(self, lr=0.01, n_iters=1000):
self.lr = lr
self.n_iters = n_iters
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
# 初始化参数
self.weights = np.zeros(n_features)
self.bias = 0
# 梯度下降
for _ in range(self.n_iters):
y_pred = np.dot(X, self.weights) + self.bias
dw = (1 / n_samples) * np.dot(X.T, (y_pred - y))
db = (1 / n_samples) * np.sum(y_pred - y)
self.weights -= self.lr * dw
self.bias -= self.lr * db
def predict(self, X):
y_pred = np.dot(X, self.weights) + self.bias
return y_pred
```
其中,`LinearRegression` 是我们定义的线性回归类,包含三个函数:
- `__init__(self, lr=0.01, n_iters=1000)`:初始化函数,初始化学习率和迭代次数等参数。
- `fit(self, X, y)`:训练函数,输入数据 `X` 和标签 `y`,通过梯度下降算法更新参数,得到最优的权重和偏置。
- `predict(self, X)`:预测函数,输入数据 `X`,通过训练得到的权重和偏置预测其对应的标签。
使用该类,我们可以这样进行线性回归:
```python
# 构造数据
X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
y = np.array([3, 6, 9])
# 初始化模型
lr = LinearRegression(lr=0.01, n_iters=1000)
# 训练模型
lr.fit(X, y)
# 预测结果
y_pred = lr.predict(X)
print(y_pred)
```
输出结果为:
```
[3. 6. 9.]
```
说明模型预测结果与真实标签非常接近。
用python写一个线性回归
我可以帮你写一个简单的线性回归程序,你可以参考以下代码:
import numpy as np
x = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
# y = 1 * x_0 + 2 * x_1 + 3
y = np.dot(x, np.array([1, 2])) + 3
# 拟合一个线性模型
model = np.linalg.lstsq(x, y)[0]
print(model) # 输出结果为 [1. 2. 3.]