1.連續(xù)輸出
本課關(guān)于連續(xù)(變量)的監(jiān)督式學(xué)習(xí)
The output variable has been constrained to binary values in our previous setup.
This output is called discrete
但在很多學(xué)習(xí)問題中,輸出也可以是連續(xù)的

2. 連續(xù)
continuous supervised learning
continuous--output
3. 年齡:連續(xù)還是離散?
連續(xù)輸出 離散輸出
4. 天氣:連續(xù)還是離散?
我們視為離散的多數(shù)事物其實(shí)在某種程度上是連續(xù)的
7. 收入:連續(xù)還是離散?
我們將一個變量看成連續(xù)時,我們其實(shí)暗示其有一定的次序,即可以比較大小
8.連續(xù)特征
分類通常意味著離散輸出,在我們的地形分類問題中,輸出變量是快速/慢速,如果將輸出推廣為連續(xù)輸出,最好的辦法是speed in mile
9.斜率和截距(回歸線性方程)
目標(biāo)變量/嘗試預(yù)測的變量/輸出 = 斜率(slope)*輸入變量+截距(intercept)
slope -- define how steep the curve goes up 定義了曲線上升的陡度
a larger slope makes it go up faster
in the situation of negative slope,the graph would go down
截距:與縱軸交點(diǎn)的坐標(biāo)
17. 線性回歸編碼
from sklearn import linear_model
clf = linear_model.LinearRegression()
clf.fit([[0,0],[1,1],[2,2]],[0,1,2])
clf.coef_ #讀取系數(shù) 斜率
數(shù)據(jù)集(年齡-凈資產(chǎn)) →(分拆)訓(xùn)練集&測試集
在數(shù)據(jù)中加入噪音,這樣就不是完美的關(guān)系
用訓(xùn)練集擬合直線,得到的就是回歸的結(jié)果,再用這條線預(yù)測年齡在25-60間任何人的凈資產(chǎn)
18. sklearn中的年齡/凈值回歸
#!/usr/bin/python studentMain.py
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())
#!/usr/bin/python studentRegression.py
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 import linear_model
reg = linear_model.LinearRegression()
reg.fit(ages_train,net_worths_train)
return reg
19. 通過sklearn提取信息
print "katie's net worth prediction: ", reg.predict([27]) #預(yù)測結(jié)果
print "slope:", reg.coef_ #獲取斜率
print "intercept:" ,reg.intercept_ #獲取截距
20. 通過 sklearn 提取分?jǐn)?shù)數(shù)據(jù)
評估回歸的指標(biāo):r2,sum of errors
r2: 越大,回歸性能越好 max=1
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)
21. 現(xiàn)在你練習(xí)提取信息
#!/usr/bin/python regressionQuiz.py
import numpy
import matplotlib.pyplot as plt
from ages_net_worths import ageNetWorthData
ages_train, ages_test, net_worths_train, net_worths_test = ageNetWorthData()
from sklearn.linear_model import LinearRegression
reg = LinearRegression()
reg.fit(ages_train, net_worths_train)
### get Katie's net worth (she's 27)
### sklearn predictions are returned in an array, so you'll want to index into
### the output to get what you want, e.g. net_worth = predict([[27]])[0][0] (not
### exact syntax, the point is the [0] at the end). In addition, make sure the
### argument to your prediction function is in the expected format - if you get
### a warning about needing a 2d array for your data, a list of lists will be
### interpreted by sklearn as such (e.g. [[27]]).
km_net_worth = reg.predict([[27]]) ### fill in the line of code to get the right value
### get the slope
### again, you'll get a 2-D array, so stick the [0][0] at the end
slope = reg.coef_ ### fill in the line of code to get the right value
### get the intercept
### here you get a 1-D array, so stick [0] on the end to access
### the info we want
intercept = reg.intercept_ ### fill in the line of code to get the right value
### get the score on test data
test_score = reg.score(ages_test,net_worths_test) ### fill in the line of code to get the right value
### get the score on the training data
training_score = reg.score(ages_train,net_worths_train) ### fill in the line of code to get the right value
def submitFit():
# all of the values in the returned dictionary are expected to be
# numbers for the purpose of the grader.
return {"networth":km_net_worth,
"slope":slope,
"intercept":intercept,
"stats on test":test_score,
"stats on training": training_score}
#!/usr/bin/python ages_net_worths.py
import numpy
import random
def ageNetWorthData():
random.seed(42)
numpy.random.seed(42)
ages = []
for ii in range(100):
ages.append( random.randint(20,65) )
net_worths = [ii * 6.25 + numpy.random.normal(scale=40.) for ii in ages]
### need massage list into a 2d numpy array to get it to work in LinearRegression
ages = numpy.reshape( numpy.array(ages), (len(ages), 1))
net_worths = numpy.reshape( numpy.array(net_worths), (len(net_worths), 1))
from sklearn.cross_validation import train_test_split
ages_train, ages_test, net_worths_train, net_worths_test = train_test_split(ages, net_worths)
return ages_train, ages_test, net_worths_train, net_worths_test
22. 線性回歸誤差
評估線性回歸:
- 可視化:將回歸的結(jié)果放在散點(diǎn)圖上
-
查看線性回歸產(chǎn)生的誤差
線性擬合會有關(guān)聯(lián)性的誤差
誤差=實(shí)際結(jié)果-輸出的預(yù)測結(jié)果
image.png
24. 誤差和擬合質(zhì)量
一個好的擬合可以將以下兩種誤差最小化:
- 所有誤差的絕對值的和
- 所有誤差的平方和
25. 最小化誤差平方和
當(dāng)執(zhí)行線性回歸時,要做的是最大程度地降低誤差平方和
這意味著,最佳回歸是最小化誤差平方和的回歸、
因此我們要做的是找到能夠使得誤差平方和最小的m和b

26. 最小化誤差平方和的算法
*ordinary least squares(OLS) 普通最小二乘法
used in sklearn LinearRegression
*gradient descent 梯度下降法
28. 最小化絕對誤差的問題
there can be multiple lines that minimize Σ|error|,but only one line will minimize Σerror2
use sum of squared error also makes implementation much easier.
使用最小化誤差平方和時,更容易找到回歸線
29. 肉眼評估回歸
哪一個回歸能更好地擬合數(shù)據(jù)集?

這兩條線基本上都恰當(dāng)?shù)貙D形和數(shù)據(jù)進(jìn)行了描述
30.SSE的問題

上面圖中的兩個線性回歸都很好地擬合了數(shù)據(jù),兩個擬合結(jié)果間沒有太大差異
但是右邊的擬合會產(chǎn)生更大的誤差平方和
通常來講,更大的誤差平方和意味著擬合得更差
因此這是誤差平方和的一個不足之處 ,因?yàn)樘砑拥臄?shù)據(jù)越多,誤差平方和幾乎必定會增加,但并不代表擬合得不好,誤差平方和會因?yàn)樗褂玫臄?shù)據(jù)點(diǎn)的數(shù)量出現(xiàn)偏差,盡管擬合不存在太大問題,下面介紹評估回歸的另一個指標(biāo)r2.
31. 回歸的 R 平方指標(biāo)
r2 of a regression
描述線性回歸的擬合良好度
-- is a number that effectively ask the question:
how much of my change in the output(y) is explained by the change in my input(x)
-- 0.0<r2 <1.0
-- the number is small,means that your regression line isn't doing a good job of capturing the trend in the data
--the number is large ,close to 1,means your regression line is doing a good job of describing the relationship between your input (x) and your output (y)
--優(yōu)點(diǎn)在于與訓(xùn)練集的數(shù)量無關(guān),即不受數(shù)據(jù)集中數(shù)據(jù)數(shù)量的影響
--比誤差平方和更可靠一些,尤其是在數(shù)據(jù)集中的數(shù)據(jù)數(shù)量可能會改變的情況下
32. sklearn中r2
如果我們能夠整合其他特征中的信息,就能更好地進(jìn)行預(yù)測,即獲得更高的r2
from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit(ages_train,net_worths_train)
print "katie's net worth prediction:" , reg.predict([27])
print "r-squared score:",reg.score(ages_test,net_worths_test)
print "slope:",reg.coef_
print "intercept:",reg.intercept_
33.可視化回歸
plt.scatter(ages,net_worths)
plt.plot(ages,reg.predict(ages),color='blue',linewidth=3)
plt.xlabel('ages')
plt.ylabel('net_worths')
plt.show()
34.什么數(shù)據(jù)適用于線性回歸
可以使用線性回歸的意思是,可以寫出y=mx+b,這個等式可以很好地描述數(shù)據(jù)中的趨勢

對于右下角的拋物線形狀,可以通過使用特征轉(zhuǎn)換擬合非線性關(guān)系。例如,添加平方 x 項(xiàng)作為功能會得到多項(xiàng)式回歸,這可以視為多元線性回歸的特殊情況,
35. 比較分類與回歸

輸出類型
監(jiān)督分類:類標(biāo)簽的形式是離散的
回歸:輸出是連續(xù)的真正嘗試查找的東西:
監(jiān)督分類:
-- 決策邊界
-- 根據(jù)點(diǎn)相對于決策邊界的位置,可為其賦予一個類標(biāo)簽
-- 描述數(shù)據(jù)的邊界
回歸:
-- 最優(yōu)擬合線
-- 擬合數(shù)據(jù)的線條評估
監(jiān)督分類:
-- 準(zhǔn)確率 accuracy
回歸:
-- 誤差平方和 sum of squared error
-- r的平方 r2
36.多元回歸/多變量回歸/multi-variable regression
有很多不同的輸入變量來預(yù)測輸出

38.回歸迷你項(xiàng)目簡介
通過工資預(yù)測獎金
異常值:在我們的模式以外很遠(yuǎn)的一個點(diǎn)
異常值如何影響通過回歸得到的結(jié)果
在此項(xiàng)目中,你將使用回歸來預(yù)測安然雇員和合伙人的財務(wù)數(shù)據(jù)。一旦你知道某位雇員的財務(wù)數(shù)據(jù),比如工資,你是否會預(yù)測他們獎金的數(shù)額?
40.獎金目標(biāo)和特征
運(yùn)行在 regression/finance_regression.py 中找到的初始代碼。這將繪制出一個散點(diǎn)圖,其中有所有的數(shù)據(jù)點(diǎn)。你嘗試預(yù)測什么目標(biāo)?用來預(yù)測目標(biāo)的輸入特征是什么?
在腦海中描繪出你大致預(yù)測的回歸線(如果打印散點(diǎn)圖并用紙筆來描繪,效果會更好)。

input:salary
output:bonus
41. 可視化回歸數(shù)據(jù)
就像在分類中一樣,你需要在回歸中訓(xùn)練和測試數(shù)據(jù)。這在初始代碼中已被設(shè)定。將 test_color 的值從“b”改為“r”(針對“red”),然后重新運(yùn)行。
注意:對于將 Python 2 代碼轉(zhuǎn)換至 Python 3 的學(xué)員,請參見以下關(guān)于兼容性的重要備注。
你將僅使用藍(lán)色(訓(xùn)練)點(diǎn)來擬合回歸。(你可能已經(jīng)注意到,我們放入測試集的是 50% 的數(shù)據(jù)而非標(biāo)準(zhǔn)的 10%—因?yàn)樵诘?5 部分中,我們將改變訓(xùn)練和測試數(shù)據(jù)集,并且平均分割數(shù)據(jù)使這種做法更加簡單。)
從 Python 3.3 版本開始,字典的鍵值順序有所改變,在每次代碼運(yùn)行時,字典的鍵值皆為隨機(jī)排序。這會讓我們在 Python 2.7 環(huán)境下工作的評分者遭遇一些兼容性的問題。為了避免這個問題,請在 finance_regression.py 文件的第26行 featureFormat 調(diào)用時添加一個參數(shù)
sort_keys = '../tools/python2_lesson06_keys.pkl'
它會打開 tools 文件夾中帶有 Python 2 鍵值順序的數(shù)據(jù)文件。
42.提取斜率和截距
from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit(feature_train,target_train)
print reg.coef_ #5.448
print reg.intercept_ #-102360.54
43. 回歸分?jǐn)?shù):訓(xùn)練數(shù)據(jù)
假設(shè)你是一名悟性不太高的機(jī)器學(xué)習(xí)者,你沒有在測試集上進(jìn)行測試,而是在你用來訓(xùn)練的相同數(shù)據(jù)上進(jìn)行了測試,并且用到的方法是將回歸預(yù)測值與訓(xùn)練數(shù)據(jù)中的目標(biāo)值(比如:獎金)做對比。
你找到的分?jǐn)?shù)是多少?你可能對“良好”分?jǐn)?shù)還沒有概念;此分?jǐn)?shù)不是非常好(但卻非常糟糕)。
···
print reg.score(feature_train,target_train) #0.0455
···
44. 回歸分?jǐn)?shù):測試數(shù)據(jù)
現(xiàn)在,在測試數(shù)據(jù)上計算回歸的分?jǐn)?shù)。
測試數(shù)據(jù)的分?jǐn)?shù)是多少?如果只是錯誤地在訓(xùn)練數(shù)據(jù)上進(jìn)行評估,你是否會高估或低估回歸的性能?
print reg.score(feature_test,target_test) #-1.48
45. 根據(jù) LTI 回歸獎金
我們有許多可用的財務(wù)特征,就預(yù)測個人獎金而言,其中一些特征可能比余下的特征更為強(qiáng)大。例如,假設(shè)你對數(shù)據(jù)做出了思考,并且推測出“l(fā)ong_term_incentive”特征(為公司長期的健康發(fā)展做出貢獻(xiàn)的雇員應(yīng)該得到這份獎勵)可能與獎金而非工資的關(guān)系更密切。
證明你的假設(shè)是正確的一種方式是根據(jù)長期激勵回歸獎金,然后看看回歸是否顯著高于根據(jù)工資回歸獎金。根據(jù)長期獎勵回歸獎金—測試數(shù)據(jù)的分?jǐn)?shù)是多少?
import sys
import pickle
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
dictionary = pickle.load( open("../final_project/final_project_dataset_modified.pkl", "r") )
### list the features you want to look at--first item in the
### list will be the "target" feature
features_list = ["bonus", "long_term_incentive"]
data = featureFormat( dictionary, features_list, remove_any_zeroes=True)
target, features = targetFeatureSplit( data )
### training-testing split needed in regression, just like classification
from sklearn.cross_validation import train_test_split
feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size=0.5, random_state=42)
train_color = "b"
test_color = "r"
### Your regression goes here!
### Please name it reg, so that the plotting code below picks it up and
### plots it correctly. Don't forget to change the test_color above from "b" to
### "r" to differentiate training points from test points.
from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit(feature_train,target_train)
print reg.coef_
print reg.intercept_
print reg.score(feature_test,target_test) #-0.59
### draw the scatterplot, with color-coded training and testing points
import matplotlib.pyplot as plt
for feature, target in zip(feature_test, target_test):
plt.scatter( feature, target, color=test_color )
for feature, target in zip(feature_train, target_train):
plt.scatter( feature, target, color=train_color )
### labels for the legend
plt.scatter(feature_test[0], target_test[0], color=test_color, label="test")
plt.scatter(feature_test[0], target_test[0], color=train_color, label="train")
### draw the regression line, once it's coded
try:
plt.plot( feature_test, reg.predict(feature_test) )
except NameError:
pass
plt.xlabel(features_list[1])
plt.ylabel(features_list[0])
plt.legend()
plt.show()
46. 工資與預(yù)測獎金的 LTI
如果你需要預(yù)測某人的獎金,你是通過他們的工資還是長期獎金來進(jìn)行預(yù)測呢?
long_term_incentive
47.異常值破壞回歸
這是下節(jié)課的內(nèi)容簡介,關(guān)于異常值的識別和刪除。返回至之前的一個設(shè)置,你在其中使用工資預(yù)測獎金,并且重新運(yùn)行代碼來回顧數(shù)據(jù)。你可能注意到,少量數(shù)據(jù)點(diǎn)落在了主趨勢之外,即某人拿到高工資(超過 1 百萬美元!)卻拿到相對較少的獎金。此為異常值的一個示例,我們將在下節(jié)課中重點(diǎn)講述它們。
類似的這種點(diǎn)可以對回歸造成很大的影響:如果它落在訓(xùn)練集內(nèi),它可能顯著影響斜率/截距。如果它落在測試集內(nèi),它可能比落在測試集外要使分?jǐn)?shù)低得多。就目前情況來看,此點(diǎn)落在測試集內(nèi)(而且最終很可能降低分?jǐn)?shù))。讓我們做一些處理,看看它落在訓(xùn)練集內(nèi)會發(fā)生什么。在 finance_regression.py 底部附近并且在 plt.xlabel(features_list[1]) 之前添加這兩行代碼:
reg.fit(feature_test, target_test)
plt.plot(feature_train, reg.predict(feature_train), color="b")
現(xiàn)在,我們將繪制兩條回歸線,一條在測試數(shù)據(jù)上擬合(有異常值),一條在訓(xùn)練數(shù)據(jù)上擬合(無異常值)。來看看現(xiàn)在的圖形,有很大差別,對吧?單一的異常值會引起很大的差異。
新的回歸線斜率是多少?
(你會發(fā)現(xiàn)差異很大,多數(shù)情況下由異常值引起。下一節(jié)課將詳細(xì)介紹異常值,這樣你就有工具來檢測和處理它們了。)
reg.fit(feature_test, target_test)
print reg.coef_ #2.27
plt.plot(feature_train, reg.predict(feature_train), color="b")
