Skip to content

Instantly share code, notes, and snippets.

@dragstar328
Created March 20, 2015 14:52
Show Gist options
  • Save dragstar328/11587a75125b7a98901c to your computer and use it in GitHub Desktop.
Save dragstar328/11587a75125b7a98901c to your computer and use it in GitHub Desktop.
Regression of cars by python
# coding:utf-8
import numpy as np
from sklearn import linear_model
from matplotlib import pyplot as plt
from matplotlib import lines
data = np.loadtxt("../data/cars.csv", delimiter=",", skiprows=1, usecols=(1, 2))
dest = data[:, 0]
speed = data[:, 1]
dest = dest.reshape(dest.size, 1)
lm = linear_model.LinearRegression()
lm.fit(dest.reshape(dest.size, 1), speed)
coef = lm.coef_
intercept = lm.intercept_
kaiki_shiki = "y = " + str(round(coef[0], 2)) + "x + (" + str(round(intercept, 2)) + ")"
print "coef :" + str(lm.coef_)
print "intercept :" + str(lm.intercept_)
print "R2 :" + str(lm.score(dest, speed))
print "line :" + kaiki_shiki
func = lambda x: x * coef + intercept
line = lines.Line2D([0, 50], [func(0), func(50)], color="red")
ax = plt.figure().add_subplot(111)
ax.set_title("Cars Kaiki")
ax.set_xlabel("speed")
ax.set_ylabel("dest")
ax.grid(True)
plt.plot(dest, speed, "*")
ax.add_line(line)
plt.text(3, 110, kaiki_shiki)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment