dragstar328
3/20/2015 - 2:52 PM

## Regression of cars by python

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()
``````