fork(1) download
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. from sklearn.model_selection import train_test_split
  5. from sklearn.linear_model import LinearRegression
  6. from sklearn.metrics import mean_squared_error, r2_score
  7.  
  8. # Create synthetic dataset
  9. np.random.seed(0)
  10. n_samples = 100
  11. X = np.random.rand(n_samples, 3) # 3 features
  12. y = 3 * X[:, 0] + 2 * X[:, 1] + 5 * X[:, 2] + np.random.randn(n_samples) # Linear equation with noise
  13. data = pd.DataFrame({'Feature1': X[:, 0], 'Feature2': X[:, 1], 'Feature3': X[:, 2], 'Price': y})
  14.  
  15. # Split data into features (X) and target variable (y)
  16. X = data[['Feature1', 'Feature2', 'Feature3']]
  17. y = data['Price']
  18.  
  19. # Split data into training and testing sets
  20. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  21.  
  22. # Create and train the multi-linear regression model
  23. model = LinearRegression()
  24. model.fit(X_train, y_train)
  25.  
  26. # Make predictions
  27. y_pred = model.predict(X_test)
  28.  
  29. # Calculate Mean Squared Error (MSE)
  30. mse = mean_squared_error(y_test, y_pred)
  31.  
  32. # Calculate R-squared (R2) score
  33. r2 = r2_score(y_test, y_pred)
  34.  
  35. print(f"Mean Squared Error (MSE): {mse}")
  36. print(f"R-squared (R2) Score: {r2}")
  37.  
  38. # Scatter plot of actual vs. predicted prices
  39. plt.scatter(y_test, y_pred)
  40. plt.xlabel("Actual Prices")
  41. plt.ylabel("Predicted Prices")
  42. plt.title("Actual Prices vs. Predicted Prices")
  43. plt.show()
  44.  
  45. # Display model coefficients (feature importance)
  46. coefficients = pd.DataFrame({'Feature': X.columns, 'Coefficient': model.coef_})
  47. print(coefficients)
  48.  
Success #stdin #stdout 2.68s 125604KB
stdin
Standard input is empty
stdout
Mean Squared Error (MSE): 1.0964652490522435
R-squared (R2) Score: 0.7406846582262431
    Feature  Coefficient
0  Feature1     2.868760
1  Feature2     1.760078
2  Feature3     5.087117