import numpy as np) R. P2 a. Y0 q- w0 a9 M
from sklearn.linear_model import LinearRegression0 ~5 N& y T6 y: \7 R0 }& A
import matplotlib.pyplot as plt! U& z7 a4 R+ v3 q
/ n8 N/ ]9 U( b G: B# 生成一些示例数据 + B) X. }5 b3 w+ S+ `3 Wnp.random.seed(0)# s4 ]1 y5 s% H" y
X = 2 * np.random.rand(100, 1) . N# F+ C) j$ H8 U: wy = 3 + 4 * X + np.random.randn(100, 1) 1 d3 B( P0 v+ B; ` s, Q$ `6 U0 l$ z" V* \: T( r: A- ~
# 创建线性回归模型6 H/ P. w! Q( N0 P3 r) j" l$ M
model = LinearRegression() 4 @# f/ t/ G2 A! L/ U7 ^0 g4 N+ s6 Y# t
# 训练模型$ h6 [7 b: F4 j! n" E
model.fit(X, y)( B4 r1 e' a h9 ^- G8 }
4 i7 [0 Q( j0 l% z# d& F7 l2 z: z4 e- R# 打印模型的参数 3 |9 j. o* z1 H% \! G. ~print("Intercept:", model.intercept_)$ [! n% p' e1 R( f
print("Coefficient:", model.coef_[0]), d; B% G7 M1 Q5 ~. S3 k0 W, b
" X( L- \, b% }* L. p# 预测新数据点 " j4 T4 L, u, Wnew_X = np.array([[1.5]]) # 输入一个新的 X 值进行预测 9 s; v7 r e( Y5 ^9 Spredicted_y = model.predict(new_X), M6 [$ O! X. E! ~* }/ d4 }3 L
print("Predicted y:", predicted_y): K5 O; N$ k% p! s4 M0 {
; d: g8 u1 A( M" c' i
# 绘制数据和拟合线 5 m) |! n& l/ n( S% nplt.scatter(X, y, color='blue') 0 A8 u% Y, a$ A. Cplt.plot(X, model.predict(X), color='red') 7 W2 L0 `# E k) ?+ d0 n. eplt.xlabel('X') ; H0 g) Y# ?2 f, n4 `5 r3 E' \plt.ylabel('y') $ i& O8 H+ B" ]( w7 Wplt.title('Linear Regression') 4 y5 R; J7 Z! t! a+ Oplt.show()" _0 f+ e2 l v' b0 `
+ u; z8 J. B+ a