Search code examples
scikit-learnregressiondata-sciencelinear-regression

Visualizing multiple linear regression predictions using a heatmap


I am using multiple linear regression to predict the temperature in every region of a field where wireless sensors are deployed, the sensors are as follows : 42 sensors deployed in a 1000x600 m² surface and collecting the temperature in each of these 42 locations per hour, see picture: Sensors placement

We have here two features ( the location aka : x and y ), and the output which is the temperature, so i fit my model according to 70% of the dataset, for the sake of later accuracy computations, however after fitting my model I want to have the temperatures prediction over all the surface, specifically a heat map that gives me the temperature as a function of x and y ( see picture : Heatmap)

I am stuck in the part of visualization, as my dataset contains the 42 known locations and their respective temperatures, how can i plot predictions for every x in [0,1000] and y in [0,600]

Do i have to make an nx2 matrix iterating over all the values of x and y and then feeding it my fitted model ? or is there a simpler way


Solution

  • You can use np.meshgrid to create a grid of points, then use your model to predict on this grid of points.

    import numpy as np
    import matplotlib.pyplot as plt
    
    grid_x, grid_y = np.meshgrid(np.linspace(0, 1000, 100),
                                 np.linspace(0, 600, 60))
    X = np.stack([grid_x.ravel(), grid_y.ravel()]).T
    
    y_pred = model.predict(X)  # use your scikit-learn model here
    image = np.reshape(y_pred, grid_x.shape)
    
    plt.imshow(image, origin="lower")
    plt.colorbar()
    plt.show()