数学建模社区-数学中国

标题: 线性回归代码 [打印本页]

作者: 2841097014    时间: 2023-8-26 18:08
标题: 线性回归代码
import numpy as np, U% ~) o3 k1 j9 r; q# {- G" x
from sklearn.linear_model import LinearRegression% s; y" k/ m5 x  c- y$ Y
import matplotlib.pyplot as plt" J  T! `7 ]( C% `2 Q) Z( H

6 Z7 f8 ^4 e$ W0 i2 z" b8 d# 生成一些示例数据
, s% x8 {& W8 |np.random.seed(0)
1 p7 f# V3 E7 \/ F$ `& GX = 2 * np.random.rand(100, 1)
, ]  |; d- k+ ?: d, x$ Cy = 3 + 4 * X + np.random.randn(100, 1)
0 L0 D6 K8 `7 x, J
  a6 Z; d4 T* A/ P# 创建线性回归模型+ w: t' X* G, a5 M( |6 A
model = LinearRegression()
4 w8 \$ F) N# t  C+ j
7 D7 J9 Y% `5 w8 x# 训练模型
) L3 p9 s3 p9 m- N2 D- \model.fit(X, y)
3 [3 o' d2 C& O; j' f
' l; i* a# L8 ^  O# 打印模型的参数
1 W/ n1 V/ f- Zprint("Intercept:", model.intercept_)
1 q' L' J# B7 b5 s0 {5 zprint("Coefficient:", model.coef_[0])
! z8 F( G: p! _! x0 e% Q0 W* V
  L2 L0 }, l; j' T5 ?8 r# x: P& f# 预测新数据点
8 q( j! W" t: i4 Z# C0 ynew_X = np.array([[1.5]])  # 输入一个新的 X 值进行预测  A1 M5 t" ?* @* t
predicted_y = model.predict(new_X)+ B" @. v4 G9 g, L
print("Predicted y:", predicted_y)3 y* I" u6 ?, z* H2 V! Q
4 f, H7 [9 ]5 w2 r9 q6 v/ `* N3 g
# 绘制数据和拟合线
6 h* h+ _0 d; q& lplt.scatter(X, y, color='blue')* F7 l7 D# ^* k) |' Q
plt.plot(X, model.predict(X), color='red')5 h; |0 ?+ U! _7 P" j' S
plt.xlabel('X')
% [% A; c% X# R. j2 W* [5 mplt.ylabel('y')
6 R: y7 C; ^! gplt.title('Linear Regression')
2 X) {8 m$ Y5 h& V! C' Fplt.show()1 u+ \0 h- c! E/ i
  ]. L7 @5 [; r5 c+ e% z. D

: ]: {8 Q3 P% l% J9 g; b3 Q




欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5