Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to compute regression line/curve(1-4D).
#! /usr/local/bin/python3.6
"""
Regression curve
"""
import random
import sys
import traceback
import numpy as np
import matplotlib.pyplot as plt
class RegressionCurve:
def __init__(self, xs, ys):
self.xs, self.ys = xs, ys
def exec(self):
""" Execution """
try:
self.__scatter() # Scatter given points
self.__plot_1() # Plot regression line
self.__plot_2() # Plot regression curve(2-D)
self.__plot_3() # Plot regression curve(3-D)
self.__plot_4() # Plot regression curve(4-D)
self.__show() # Graph showing
except Exception as e:
raise
def __scatter(self):
""" Scatter given points """
try:
print("x={}\ny={}".format(self.xs, self.ys))
plt.scatter(self.xs, self.ys, c='#cc0000', label="Points")
except Exception as e:
raise
def __plot_1(self):
""" Plot regression line """
try:
a, b = np.polyfit(self.xs, self.ys, 1)
print("a={:.4f}, b={:.4f}".format(a, b))
fs = [a * x + b for x in self.xs]
plt.plot(self.xs, fs, label="1-D")
except Exception as e:
raise
def __plot_2(self):
""" Plot regression curve (2-D) """
try:
a, b, c = np.polyfit(self.xs, self.ys, 2)
print("a={:.4f}, b={:.4f}, c={:.4f}".format(a, b, c))
fs = [x * (x * a + b) + c for x in self.xs]
plt.plot(self.xs, fs, label="2-D")
except Exception as e:
raise
def __plot_3(self):
""" Plot regression curve (3-D) """
try:
a, b, c, d = np.polyfit(self.xs, self.ys, 3)
print("a={:.4f}, b={:.4f}, c={:.4f}, d={:.4f}".format(a, b, c, d))
fs = [x * (x * (x * a + b) + c) + d for x in self.xs]
plt.plot(self.xs, fs, label="3-D")
except Exception as e:
raise
def __plot_4(self):
""" Plot regression curve (4-D) """
try:
a, b, c, d, e = np.polyfit(self.xs, self.ys, 4)
print("a={:.4f}, b={:.4f}, c={:.4f}, d={:.4f}, e={:.4f}"
.format(a, b, c, d, e))
fs = [x * (x * (x * (x * a + b) + c) + d) + e for x in self.xs]
plt.plot(self.xs, fs, label="4-D")
except Exception as e:
raise
def __show(self):
""" Graph showing """
try:
plt.title("Regression Line/Curve (1-4D)")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc=2)
plt.grid()
plt.show()
except Exception as e:
raise
if __name__ == '__main__':
try:
random.seed(1)
xs = list(range(0, 50))
ys = [random.randint(0, 1000) for _ in range(50)]
obj = RegressionCurve(xs, ys)
obj.exec()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.