- 在线时间
- 0 小时
- 最后登录
- 2023-8-26
- 注册时间
- 2023-8-26
- 听众数
- 1
- 收听数
- 0
- 能力
- 0 分
- 体力
- 5 点
- 威望
- 0 点
- 阅读权限
- 10
- 积分
- 3
- 相册
- 0
- 日志
- 0
- 记录
- 1
- 帖子
- 3
- 主题
- 1
- 精华
- 0
- 分享
- 0
- 好友
- 0
升级   60% 该用户从未签到
 |
import numpy as np
' m2 G: p$ X, P% ?from sklearn.linear_model import LinearRegression3 R0 e# J0 I) ~0 Y
import matplotlib.pyplot as plt
" @- x5 \9 U. g, M' c+ C' D% u2 g3 U
. P$ S- W- i7 U; s# 生成一些示例数据
, k# y% a9 C9 L7 d1 [6 Wnp.random.seed(0)8 R0 \0 D* b2 Z) O9 m
X = 2 * np.random.rand(100, 1)) x: a" R0 X8 I+ j* ]8 K
y = 3 + 4 * X + np.random.randn(100, 1)
; u. G f9 s) c3 V2 p/ K
- G6 T/ [# S, b3 x; Z# 创建线性回归模型$ u7 f# _8 q# S
model = LinearRegression()
' |) O6 s% S0 |6 m( Q( I0 K' _* ^1 L3 J7 S
# 训练模型 ~4 Y! s6 `( }' g" K
model.fit(X, y)
- R7 v" J+ V& M8 l
) i) q) @, e- G# 打印模型的参数; g/ i9 f0 q+ ^1 s
print("Intercept:", model.intercept_)1 g, f+ M: L& R3 R) o5 }
print("Coefficient:", model.coef_[0])% \ {9 _. r8 ~2 s
- V% ]0 U( N8 f* K* U
# 预测新数据点# a' G" `4 Z0 b; v, ^- |
new_X = np.array([[1.5]]) # 输入一个新的 X 值进行预测' ]7 w" \$ H2 M. M0 d6 b3 k
predicted_y = model.predict(new_X)8 a- O9 a$ r" F+ W8 o8 R% l
print("Predicted y:", predicted_y)* r3 z$ d" P" P
/ p# |! n. G& n( `5 R9 _+ S; [6 R# 绘制数据和拟合线
]& s/ z ^5 M" K+ e& Q+ Qplt.scatter(X, y, color='blue')
/ o9 J4 C$ a+ U& M; T# x. ~plt.plot(X, model.predict(X), color='red')
! L) F; N e; `9 w6 bplt.xlabel('X')
" ?0 c y) O# |) g; I8 kplt.ylabel('y')
0 n5 i& K, }4 ~- r8 bplt.title('Linear Regression')
7 Z4 h! f1 _ q, o& T4 V; Jplt.show()
! y2 H. w8 R( i# y3 d
4 u5 g8 j# H4 W! m
# P0 u5 F' _) \ |
zan
|