Linear regression is a statistical method used to model the relationship
between one or more independent variables and a dependent variable. The goal
of linear regression is to find a linear relationship between the independent
and dependent variables.
Linear regression is widely used in many disciplines, including business,
science, and engineering. It can predict future trends and outcomes based on
historical data and identify relationships between variables.
In this article, we are gonna to see the linear regression in Python:
Load the diabetes datasetimport numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score
Use only one feature for simplicity (e.g., BMI)diabetes = load_diabetes()
Split the data into training and testing setsX = diabetes.data[:, np.newaxis, 2]
Create a linear regression objectX_train = X[:-20] X_test = X[-20:] y_train = diabetes.target[:-20] y_test = diabetes.target[-20:]
Train the model using the training setsmodel = LinearRegression()
Make predictions using the testing setmodel.fit(X_train, y_train)
Calculate accuracy measuresy_pred = model.predict(X_test)
Plot the resultsmse = mean_squared_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) print("Mean squared error:", mse) print("R-squared:", r2)
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.xlabel("BMI")
plt.ylabel("Disease Progression")
plt.title("Linear Regression - Diabetes Dataset")
plt.show()
The diabetes inbuilt dataset is imported from the 'sklearn.datasets. The data preprocessing, creating a linear regression object, fitting the model to the data, and making predictions using the test dataset. After these, the coefficients and intercept and the mean squared error and R - Squared value are used to evaluate the model's accuracy.
Finally, we plot the data points and the regression line. You can replace 'data.csv' with the actual name of your dataset file.
Post a Comment
The more you ask questions, that will enrich the answer, so whats your question?