This code demonstrates how a simple linear regression model can be trained and used to make predictions in Python using the sci-kit-learn library. The LinearRegression class from the sklearn.linear_model module in sci-kit-learn is used to build and train linear regression models in Python.
Linear Regression is a supervised machine learning algorithm used for regression problems. In regression problems, the goal is to predict a continuous target variable based on one or more input variables. The linear regression algorithm fits a linear equation to the observed data between the dependent (target) and independent (predictor) variables. The equation is represented by a line that best captures the relationship between the variables.
The model.predict() method in sci-kit-learn's LinearRegression class is used to make predictions for new data based on a trained linear regression model.
Linear Regression is widely used for many applications, including forecasting, modeling, and understanding the relationship between variables.
Preview of the output that you will get on running this code from your IDE
In this solution we have used LinearRegression
import numpy as np from sklearn.linear_model import LinearRegression # sample dummy data # independent variables time = np.arange(1,36) price = np.random.randint(1,100,35) ads = np.random.randint(1,10,35) # dependent variable y = np.random.randn(35) # Reshape it into 35X3 where each row is an observation train_X = np.vstack([time, price, ads]).T # Fit the model model = LinearRegression().fit(train_X, y) # Sample observations for which # forecast of dependent variable has to be made time1 = np.arange(37, 47) price1 = np.array(*len(time1)) ads1 = np.array(*len(time1)) # Reshape such that each row is an observation test_X = np.vstack([time1, price1, ads1]).T # make the predictions print (model.predict(test_X))' array([0.22189608, 0.2269302 , 0.23196433, 0.23699845, 0.24203257, 0.24706669, 0.25210081, 0.25713494, 0.26216906, 0.26720318])
- Copy the code using the "Copy" button above, and paste it in a Python file in your IDE.
- Run the file to get the output
I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.
I found this code snippet by searching for "use .predict() method in python for Linear regression" in kandi. You can try any such use case!
I tested this solution in the following versions. Be mindful of changes when working with other versions.
- The solution is created in Python 3.7.15 version
- The solution is tested on sci-kit-learn 1.0.2 version
- The solution is tested on numpy 1.21.6 version
Using this solution, we are able going to learn how to predict a simple linear regression model using Scikit learn library in Python with simple steps. This process also facilities an easy-to-use, hassle-free method to create a hands-on working version of code which would help use the .predict() method in python for Linear regression in Python.