1. 程式人生 > 實用技巧 >【優達學城測評】sklearn-線性迴歸

【優達學城測評】sklearn-線性迴歸

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

個人覺得這是最最簡單的,套直線方程就可以。

同時,這個擬合的程式碼似乎在後續監督學習中可以套用,未完待續。先貼這段程式碼。

def studentReg(ages_train, net_worths_train):
### import the sklearn regression module, create, and train your regression
### name your regression reg

### your code goes here!

from sklearn.linear_model import LinearRegression

reg=LinearRegression()
reg.fit(ages_train,net_worths_train)

return reg

print"Katie's net worth prediction:", reg.predict([27])
print"slope:",reg.coef_
print"intercept:",reg.intercept_

print"\n ##########stats on test dataset #########\n"
print"r-squared score:", reg.score(ages_test,net_worths_test)

print"\n ##########stats on training dataset ##########\n"
print"r-squared score:", reg.score(ages_train,net_worths_train)

打印出的預測結果並不精確,所以後續需要學習迴歸會出現的誤差型別,以及R平方指標,如果過度擬合,那麼這個指標就會很低

#!/usr/bin/python

import numpy
import matplotlib
matplotlib.use('agg')

import matplotlib.pyplot as plt

from studentRegression import studentReg
from class_vis import prettyPicture, output_image

from ages_net_worths import ageNetWorthData

ages_train, ages_test, net_worths_train, net_worths_test = ageNetWorthData()

reg = studentReg(ages_train, net_worths_train)


plt.clf()
plt.scatter(ages_train, net_worths_train, color="b", label="train data")
plt.scatter(ages_test, net_worths_test, color="r", label="test data")
plt.plot(ages_test, reg.predict(ages_test), color="black")
plt.legend(loc=2)
plt.xlabel("ages")
plt.ylabel("net worths")


plt.savefig("test.png")
output_image("test.png", "png", open("test.png", "rb").read())

轉載於:https://my.oschina.net/Bettyty/blog/754145