1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error
np.random.seed(42) X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred) print(f'Mean Squared Error: {mse}')
plt.scatter(X_train, y_train, label='Training Data') plt.scatter(X_test, y_test, color='red', label='Test Data') plt.plot(X_test, y_pred, color='blue', linewidth=3, label='Regression Line') plt.xlabel('X') plt.ylabel('y') plt.legend() plt.show()
|