Build the Linear Regression
Here we will learn how to find the intercept and slope for our dataset. For this example, we will use a scientific computation library SciPy
, to import stats
. Using the method stats.lingress()
we can get the most important linear regression parameters for the given dataset (x and y arrays). Pay attention to the first two values (slope and intercept), and other parameters will be analyzed in the following chapters. These two numbers define a straight line. The squares of the residuals of the dataset to points are minimal.
123456789101112131415161718192021222324252627# Import the libraries import matplotlib.pyplot as plt from scipy import stats # Initialize the data x = [8, 10, 9.2, 8.4, 9.1, 9.6, 8, 10.2, 9.3, 9.4, 9.9, 8.7] y = [3.6, 5.4, 4.8, 3.9, 4.2, 5.2, 3.5, 5.5, 4.4, 4.7, 5.1, 3.7] # Get the linear regression parameters slope, intercept, r, p, std_err = stats.linregress(x, y) # The line shows the dependence of the height of cats on their weight def on_weight(x): return slope * x + intercept # Define the line height_on_weight = list(map(on_weight, x)) # Add titles to axes ax = plt.gca() ax.set_xlabel('Cat height (inches)') ax.set_ylabel('Cat weight (kg)') # Visualize our data plt.scatter(x, y) plt.plot(x, height_on_weight) plt.show()
The output of the code execution is identical to your first task. However, now we don't work with predefined values but with a method that returns them to us knowing the dataset.
Swipe to start coding
Getting bigger, cats start to eat more. Let's see how these values are dependent. We have a dataset in which the number of calories the cat eats every day at a certain weight is indicated (array x
- weight, y
- number of calories).
- [Lines #2-3] Import the
matplotlib.pyplot
and also the library SciPy. - [Lines #10-17] Find the slope and the intercept using the method
stats.lingress()
. Add the missing parameter to the functionon_weight
and assign the variablefeed_on_weight
. - [Lines #26-27] Build line on your plot.
Рішення
Дякуємо за ваш відгук!
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат