Home
Locate
CS 101
CS 496
Login
Tutors
Marks
About
Send
Close
Add comments:
(status displays here)
Got it!
This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.
nbsp; Note: This appears on each machine/browser from which this site is accessed.
Matplotlib: Linear regression
by RS
admin@ycp.powersoftwo.org
c
go
java
js
lua
py
vbs
rkt
scm
pro
1. Matplotlib: Linear regression
2. Linear regression
Here is an example of linear regression using numpy, sklearn and matplotlib.
3. Data
Here is the data to be used as an example.
x y 1 2 2 1 3 4 4 3 5 6 6 5 7 8
Here is the Python code.
import matplotlib.pyplot as plt import rsPlot import numpy as np from sklearn.linear_model import LinearRegression dataList1 = [ [1,2], [2,1], [3,4], [4,3], [5,6], [6,5], [7,8], ] xData0 = [] yData0 = [] for x1, y1 in dataList1: xData0.append(x1) yData0.append(y1) xData1 = np.array(xData0).reshape(-1, 1) yData1 = np.array(yData0).reshape(-1, 1) reg1 = LinearRegression() reg1.fit(xData1,yData1) slope1 = float(reg1.coef_) coef1 = float(reg1.coef_) intercept1 = float(reg1.intercept_) equation1 = "y == {0:1.1f} * x + {1:0.2f}".format(slope1,intercept1) print("") print("Regression line:") print("") print("\t{0:s}".format(equation1)) print("") print("\tSlope: {0:0.2f}".format(slope1)) print("\tIntercept: {0:0.2f}".format(intercept1)) print("\tCorrelation coefficient: {0:0.2f}".format(coef1)) print("") print("Predictions:") print("") print("\t{0:>5} {1:>5} {2:>5}-actual".format("x", "y", "y")) for x1, y1 in dataList1: y1 = slope1 * x1 + intercept1 print("\t{0:5.1f} {1:5.1f} {2:5.1f}".format(x1,y1,y1)) print("") yPredict1 = reg1.predict(xData1) plot1 = rsPlot.plot("regr21-1") ax1 = plot1.ax1 plt.title("data : x vs. y") plt.xlabel("x") plt.ylabel("y") ax1.scatter(xData1,yData1,color="#990099") ax1.plot(xData1,yPredict1,color="#000099",label=equation1) ax1.legend(fontsize=10) plot1.save()
Here is the output of the Python code.
(module rsPlot imported) Regression line: y == 1.0 * x + 0.14 Slope: 1.00 Intercept: 0.14 Correlation coefficient: 1.00 Predictions: x y y-actual 1.0 1.1 1.1 2.0 2.1 2.1 3.0 3.1 3.1 4.0 4.1 4.1 5.0 5.1 5.1 6.0 6.1 6.1 7.0 7.1 7.1 ./regr21-1-01.png : 559 x 462 , 21,634 bytes
4. Regression chart
5. End of page
by RS
admin@ycp.powersoftwo.org