TEXT   44

Hemant SETA

Guest on 21st August 2024 07:23:51 AM

  1. import matplotlib.pyplot as plt
  2.  
  3. # Given dataset
  4. features = [2, 4, 5, 6]
  5. animal_types = [6, 5, 9, 10]
  6.  
  7. # Step 1: Calculate the means of the features and animal types
  8. mean_x = sum(features) / len(features)
  9. mean_y = sum(animal_types) / len(animal_types)
  10.  
  11. # Step 2: Calculate the slope (m) and intercept (b) manually
  12. numerator = sum([(features[i] - mean_x) * (animal_types[i] - mean_y) for i in range(len(features))])
  13. denominator = sum([(features[i] - mean_x) ** 2 for i in range(len(features))])
  14. slope = numerator / denominator
  15. intercept = mean_y - (slope * mean_x)
  16.  
  17. # Step 3: Predict the animal type for feature = 8
  18. feature_to_predict = 8
  19. predicted_animal_type = slope * feature_to_predict + intercept
  20.  
  21. # Step 4: Plot the data points and the regression line
  22. plt.scatter(features, animal_types, color='blue', label='Data points')
  23. plt.plot(features, [slope * x + intercept for x in features], color='red', label='Regression line')
  24. plt.scatter([feature_to_predict], [predicted_animal_type], color='green', label=f'Prediction for feature={feature_to_predict}\nPredicted type={predicted_animal_type:.2f}')
  25. plt.xlabel('Feature')
  26. plt.ylabel('Animal Type')
  27. plt.legend()
  28. plt.title('Linear Regression: Feature vs Animal Type')
  29. plt.grid(True)
  30. plt.show()
  31.  
  32. # Output the slope, intercept, and predicted value
  33. print(f"Slope (m): {slope}")
  34. print(f"Intercept (b): {intercept}")
  35. print(f"Predicted Animal Type for Feature = {feature_to_predict}: {predicted_animal_type}")

Raw Paste


Login or Register to edit or fork this paste. It's free.