数学建模社区-数学中国
标题:
线性回归代码
[打印本页]
作者:
2841097014
时间:
2023-8-26 18:08
标题:
线性回归代码
import numpy as np
. j( Q& y- b% [: k
from sklearn.linear_model import LinearRegression
. H/ E. A$ A2 ~) N
import matplotlib.pyplot as plt
4 R" \$ E+ L" Z6 Q. H7 C
9 Q2 I3 Q0 }" \/ A8 s% @, O$ M+ Z
# 生成一些示例数据
' W' s1 h# T1 [" Y( C6 e* Q
np.random.seed(0)
! }; P; N. w- L# C3 F
X = 2 * np.random.rand(100, 1)
3 \$ a+ U% A1 E' O: D
y = 3 + 4 * X + np.random.randn(100, 1)
7 G/ i7 O1 {) L$ Q0 u
7 n$ v/ u' f8 g
# 创建线性回归模型
1 w% W# m* j0 J' O
model = LinearRegression()
4 x( q: l+ ?+ _' \
@3 w/ t, s! Y- P) q2 R6 x9 a
# 训练模型
1 L9 W( Y. Y; d2 c2 }* J/ @
model.fit(X, y)
4 T6 n- S* y8 ]! k% k
8 b$ _7 g6 |0 v- B) V
# 打印模型的参数
* U& c l* ~5 u. |) m5 H6 ^
print("Intercept:", model.intercept_)
& r' R: o+ {4 e3 e: Q4 C
print("Coefficient:", model.coef_[0])
( v1 a5 B9 X7 d. K4 c( N* g7 n! K
6 c- D/ e# `+ @$ U' A: o! U8 d
# 预测新数据点
- ]; \/ {1 |0 y6 D
new_X = np.array([[1.5]]) # 输入一个新的 X 值进行预测
& v) o' L4 F. {- r, m
predicted_y = model.predict(new_X)
0 z# l. u$ N- c3 W
print("Predicted y:", predicted_y)
4 f0 J6 Z9 d: b% q" F4 X; c" C9 R
' B/ W$ T6 y8 j; e+ o5 f
# 绘制数据和拟合线
& ?- Q. O% A0 W) B$ Q
plt.scatter(X, y, color='blue')
" J4 g5 Y8 v$ e0 d; ^1 a; A0 Y
plt.plot(X, model.predict(X), color='red')
/ {4 ~' ~- o$ ]# _/ j% d
plt.xlabel('X')
& S: N/ |3 p9 O: `+ [
plt.ylabel('y')
" o' q+ p1 w$ l% ^: L9 M
plt.title('Linear Regression')
* L' s0 u* O* K+ n" M" g P
plt.show()
' t4 r$ q+ x7 y4 T$ ~
5 S8 \' N f4 Q! z9 q1 E
6 W1 a: @/ x$ V0 O6 q: D5 ^9 E8 I
欢迎光临 数学建模社区-数学中国 (http://www.madio.net/)
Powered by Discuz! X2.5