FAFU機(jī)器學(xué)習(xí)03-2 Linear Regression課件_第1頁(yè)
FAFU機(jī)器學(xué)習(xí)03-2 Linear Regression課件_第2頁(yè)
FAFU機(jī)器學(xué)習(xí)03-2 Linear Regression課件_第3頁(yè)
FAFU機(jī)器學(xué)習(xí)03-2 Linear Regression課件_第4頁(yè)
FAFU機(jī)器學(xué)習(xí)03-2 Linear Regression課件_第5頁(yè)
已閱讀5頁(yè),還剩57頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

FoundationsofMachineLearning

Regression2023/11/4FoundationsofMachineLearningRegressionSimplelinearregression(簡(jiǎn)單線(xiàn)性回歸)EvaluatingthemodelMultiplelinearregression(多元線(xiàn)性回歸)Polynomialregression(多項(xiàng)式回歸)Regularization(正則化)ApplyinglinearregressionFittingmodelswithgradientdescent(梯度下降)2023/11/4LinearRegressionLesson3-2SimplelinearregressionSimplelinearregressioncanbeusedtomodelalinearrelationshipbetweenoneresponsevariableandoneexplanatoryvariable.Supposeyouwishtoknowthepriceofapizza.2023/11/4LinearRegressionLesson3-3Observethedata2023/11/4LinearRegressionLesson3-4importmatplotlib.pyplotaspltX=[[6],[8],[10],[14],[18]]y=[[7],[9],[13],[17.5],[18]]plt.figure()plt.title('Pizzapriceplottedagainstdiameter')plt.xlabel('Diameterininches')plt.ylabel('Priceindollars')plt.plot(X,y,'k.')plt.axis([0,25,0,25])plt.grid(True)plt.show()Sklearn.linear_model.LinearRegression2023/11/4LinearRegressionLesson3-5#importsklearnfromsklearn.linear_modelimportLinearRegression#TrainingdataX=[[6],[8],[10],[14],[18]]y=[[7],[9],[13],[17.5],[18]]#Createandfitthemodelmodel=LinearRegression()model.fit(X,y)print('A12"pizzashouldcost:$%.2f'%model.predict([12])[0])#A12"pizzashouldcost:$13.68Sklearn.linear_model.LinearRegressionThesklearn.linear_model.LinearRegressionclassisanestimator.Estimatorspredictavaluebasedontheobserveddata.Inscikit-learn,allestimatorsimplementthefit()andpredict()methods.Theformermethodisusedtolearntheparametersofamodel,andthelattermethodisusedtopredictthevalueofaresponsevariableforanexplanatoryvariableusingthelearnedparameters.Itiseasytoexperimentwithdifferentmodelsusingscikit-learnbecauseallestimatorsimplementthefitandpredictmethods.2023/11/4LinearRegressionLesson3-6Results2023/11/4LinearRegressionLesson3-7print((ercept_,model.coef_))Z=model.predict(X)plt.scatter(X,y)plt.plot(X,Z,color='red')plt.title('Pizzapriceplottedagainstdiameter')plt.xlabel('Diameterininches')plt.ylabel('Priceindollars')plt.show()#(array([1.96551743]),array([[0.9762931]]))EvaluatingthefitnessofamodelRegressionlinesproducedbyseveralsetsofparametervaluesareplottedinthefollowingfigure.Howcanweassesswhichparametersproducedthebest-fittingregressionline?2023/11/4LinearRegressionLesson3-8costfunctionAcostfunction,alsocalledalossfunction,isusedtodefineandmeasuretheerrorofamodel.Thedifferencesbetweenthepricespredictedbythemodelandtheobservedpricesofthepizzasinthetrainingsetarecalledresidualsortrainingerrors.Later,wewillevaluateamodelonaseparatesetoftestdata;thedifferencesbetweenthepredictedandobservedvaluesinthetestdataarecalledpredictionerrorsortesterrors.Theresidualsforourmodelareindicatedbytheverticallinesbetweenthepointsforthetraininginstancesandregressionhyperplaneinthefollowingplot:2023/11/4LinearRegressionLesson3-9Wecanproducethebestpizza-pricepredictorbyminimizingthesumoftheresiduals.Thatis,ourmodelfitsifthevaluesitpredictsfortheresponsevariableareclosetotheobservedvaluesforallofthetrainingexamples.Thismeasureofthemodel'sfitnessiscalledtheresidualsumofsquarescostfunction.2023/11/4LinearRegressionLesson3-10importnumpyasnprss=np.sum((model.predict(X)-y)**2)print('Residualsumofsquares:%.2f'%(rss,))#Residualsumofsquares:8.75Solvingordinaryleastsquaresforsimplelinearregression對(duì)于一元線(xiàn)性回歸模型,

假設(shè)從總體中獲取了n組觀察值(X1,Y1),(X2,Y2),

…,(Xn,Yn)。對(duì)于平面中的這n個(gè)點(diǎn),可以使用無(wú)數(shù)條曲線(xiàn)來(lái)擬合。要求樣本回歸函數(shù)盡可能好地?cái)M合這組值,最常用的是普通最小二乘法(

Ordinary

LeastSquare,OLS):所選擇的回歸模型應(yīng)該使所有觀察值的殘差平方和達(dá)到最小。2023/11/4LinearRegressionLesson3-11varianceofx>>>importnumpyasnp>>>printnp.var([6,8,10,14,18],ddof=1)covarianceofxandy>>>importnumpyasnp>>>printnp.cov([6,8,10,14,18],[7,9,13,17.5,18])[0][1]2023/11/4LinearRegressionLesson3-12Nowthatwehavecalculatedthevarianceofourexplanatoryvariableandthecovarianceoftheresponseandexplanatoryvariables,wecansolveusingthefollowingformula:Havingsolvedβ,wecansolveαusingthefollowingformula:2023/11/4LinearRegressionLesson3-13EvaluatingthemodelWehaveusedalearningalgorithmtoestimateamodel'sparametersfromthetrainingdata.Howcanweassesswhetherourmodelisagoodrepresentationoftherealrelationship?2023/11/4LinearRegressionLesson3-14R-squaredSeveralmeasurescanbeusedtoassessourmodel'spredictivecapabilities.Wewillevaluateourpizza-pricepredictorusingr-squared.R-squaredmeasureshowwelltheobservedvaluesoftheresponsevariablesarepredictedbythemodel.Moreconcretely,r-squaredistheproportionofthevarianceintheresponsevariablethatisexplainedbythemodel.Anr-squaredscoreofoneindicatesthattheresponsevariablecanbepredictedwithoutanyerrorusingthemodel.Anr-squaredscoreofonehalfindicatesthathalfofthevarianceintheresponsevariablecanbepredictedusingthemodel.Thereareseveralmethodstocalculater-squared.Inthecaseofsimplelinearregression,r-squaredisequaltothesquareofthePearsonproductmomentcorrelationcoefficient,orPearson'sr.2023/11/4LinearRegressionLesson3-15

2023/11/4LinearRegressionLesson3-16MultiplelinearregressionFormally,multiplelinearregressionisthefollowingmodel:Let'supdateourpizzatrainingdatatoincludethenumberoftoppingswiththefollowingvalues:2023/11/4LinearRegressionLesson3-17MultiplelinearregressionFormally,multiplelinearregressionisthefollowingmodel:2023/11/4LinearRegressionLesson3-18MultiplelinearregressionFormally,multiplelinearregressionisthefollowingmodel:Let'supdateourpizzatrainingdatatoincludethenumberoftoppingswiththefollowingvalues:Wemustalsoupdateourtestdatatoincludethesecondexplanatoryvariable,asfollows:2023/11/4LinearRegressionLesson3-19WewillmultiplyXbyitstransposetoyieldasquarematrixthatcanbeinverted.DenotedwithasuperscriptT,thetransposeofamatrixisformedbyturningtherowsofthematrixintocolumnsandviceversa,asfollows:2023/11/4LinearRegressionLesson3-20>>>fromnumpy.linalgimportinv>>>fromnumpyimportdot,transpose>>>X=[[1,6,2],[1,8,1],[1,10,0],[1,14,2],[1,18,0]]>>>y=[[7],[9],[13],[17.5],[18]]>>>printdot(inv(dot(transpose(X),X)),dot(transpose(X),y))[[1.1875][1.01041667][0.39583333]]2023/11/4LinearRegressionLesson3-21NumPyalsoprovidesaleastsquaresfunctionthatcansolvethevaluesoftheparametersmorecompactly:>>>fromnumpy.linalgimportlstsq>>>X=[[1,6,2],[1,8,1],[1,10,0],[1,14,2],[1,18,0]]>>>y=[[7],[9],[13],[17.5],[18]]>>>printlstsq(X,y)[0][[1.1875][1.01041667][0.39583333]]2023/11/4LinearRegressionLesson3-22sklearn.linear_model.LinearRegression2023/11/4LinearRegressionLesson3-23PolynomialregressionInthepreviousexamples,weassumedthattherealrelationshipbetweentheexplanatoryvariablesandtheresponsevariableislinear.Thisassumptionisnotalwaystrue.Inthissection,wewillusepolynomialregression,aspecialcaseofmultiplelinearregressionthataddstermswithdegreesgreaterthanonetothemodel.Thereal-worldcurvilinearrelationshipiscapturedwhenyoutransformthetrainingdatabyaddingpolynomialterms,whicharethenfitinthesamemannerasinmultiplelinearregression.Foreaseofvisualization,wewillagainuseonlyoneexplanatoryvariable,thepizza'sdiameter.Let'scomparelinearregressionwithpolynomialregressionusingthefollowingdatasets:2023/11/4LinearRegressionLesson3-24Quadraticregression,orregressionwithasecondorderpolynomial,isgivenbythefollowingformula:Weareusingonlyoneexplanatoryvariable,butthemodelnowhasthreetermsinsteadoftwo.Theexplanatoryvariablehasbeentransformedandaddedasathirdtermtothemodeltocapturethecurvilinearrelationship.Also,notethattheequationforpolynomialregressionisthesameastheequationformultiplelinearregressioninvectornotation.ThePolynomialFeaturestransformercanbeusedtoeasilyaddpolynomialfeaturestoafeaturerepresentation.Let‘sfitamodeltothesefeatures,andcompareittothesimplelinearregressionmodel.2023/11/4LinearRegressionLesson3-252023/11/4LinearRegressionLesson3-262023/11/4LinearRegressionLesson3-27Now,let'stryanevenhigher-orderpolynomial.Theplotinthefollowingfigureshowsaregressioncurvecreatedbyaninth-degreepolynomial:2023/11/4LinearRegressionLesson3-28Theninth-degreepolynomialregressionmodelfitsthetrainingdataalmostexactly!Themodel'sr-squaredscore,however,is-0.09.Wecreatedanextremelycomplexmodelthatfitsthetrainingdataexactly,butfailstoapproximatetherealrelationship.Thisproblemiscalledover-fitting.Themodelshouldinduceageneralruletomapinputstooutputs;instead,ithasmemorizedtheinputsandoutputsfromthetrainingdata.Asaresult,themodelperformspoorlyontestdata.Itpredictsthata16inchpizzashouldcostlessthan$10,andan18inchpizzashouldcostmorethan$30.Thismodelexactlyfitsthetrainingdata,butfailstolearntherealrelationshipbetweensizeandprice.2023/11/4LinearRegressionLesson3-29RegularizationRegularizationisacollectionoftechniquesthatcanbeusedtopreventover-fitting.Regularizationaddsinformationtoaproblem,oftenintheformofapenaltyagainstcomplexity,toaproblem.Occam‘srazor(奧卡姆剃刀定律)statesthatahypothesiswiththefewestassumptionsisthebest.Accordingly,regularizationattemptstofindthesimplestmodelthatexplainsthedata.2023/11/4LinearRegressionLesson3-30

2023/11/4LinearRegressionLesson3-31

2023/11/4LinearRegressionLesson3-32

2023/11/4LinearRegressionLesson3-33ApplyinglinearregressionAssumethatyouareataparty,andthatyouwishtodrinkthebestwinethatisavailable.Youcouldaskyourfriendsforrecommendations,butyoususpectthattheywilldrinkanywine,regardlessofitsprovenance.Fortunately,youhavebroughtpHteststripsandothertoolstomeasurevariousphysicochemicalpropertiesofwine—itis,afterall,aparty.Wewillusemachinelearningtopredictthequalityofthewinebasedonitsphysicochemicalattributes.2023/11/4LinearRegressionLesson3-34TheUCIMachineLearningRepository'sWinedatasetmeasureselevenphysicochemicalattributes,includingthepHandalcoholcontent,of1,599differentredwines.Eachwine'squalityhasbeenscoredbyhumanjudges.Thescoresrangefromzerototen;zeroistheworstqualityandtenisthebestquality.Thedatasetcanbedownloadedfrom/ml/datasets/Wine.Wewillapproachthisproblemasaregressiontaskandregressthewine'squalityontooneormorephysicochemicalattributes.Theresponsevariableinthisproblemtakesonlyintegervaluesbetween0and10;wecouldviewtheseasdiscretevaluesandapproachtheproblemasamulticlassclassificationtask.Inthischapter,however,wewillviewtheresponsevariableasacontinuousvalue.2023/11/4LinearRegressionLesson3-35Exploringthedatafixedacidity非揮發(fā)性酸,volatileacidity揮發(fā)性酸,citricacid檸檬酸,residualsugar剩余糖分,chlorides氯化物,freesulfurdioxide游離二氧化硫,totalsulfurdioxide總二氧化硫,density密度,pH酸堿性,sulphates硫酸鹽,alcohol酒精,quality質(zhì)量2023/11/4LinearRegressionLesson3-36First,wewillloadthedatasetandreviewsomebasicsummarystatisticsforthevariables.Thedataisprovidedasa.csvfile.Notethatthefieldsareseparatedbysemicolonsratherthancommas):2023/11/4LinearRegressionLesson3-37Visualizingthedatacanhelpindicateifrelationshipsexistbetweentheresponsevariableandtheexplanatoryvariables.Let'susematplotlibtocreatesomescatterplots.Considerthefollowingcodesnippet:2023/11/4LinearRegressionLesson3-382023/11/4LinearRegressionLesson3-39Theseplotssuggestthattheresponsevariabledependsonmultipleexplanatoryvariables;let'smodeltherelationshipwithmultiplelinearregression.Howcanwedecidewhichexplanatoryvariablestoincludeinthemodel?Dataframe.corr()calculatesapairwisecorrelationmatrix.Thecorrelationmatrixconfirmsthatthestrongestpositivecorrelationisbetweenthealcoholandquality,andthatqualityisnegativelycorrelatedwithvolatileacidity,anattributethatcancausewinetotastelikevinegar.Tosummarize,wehavehypothesizedthatgoodwineshavehighalcoholcontentanddonottastelikevinegar.Thishypothesisseemssensible,thoughitsuggeststhatwineaficionadosmayhavelesssophisticatedpalatesthantheyclaim2023/11/4LinearRegressionLesson3-40Fittingandevaluatingthemodel2023/11/4LinearRegressionLesson3-41Ther-squaredscoreof0.35indicatesthat35percentofthevarianceinthetestsetisexplainedbythemodel.Theperformancemightchangeifadifferent75percentofthedataispartitionedtothetrainingset.Wecanusecross-validationtoproduceabetterestimateoftheestimator'sperformance.Recallfromchapteronethateachcross-validationroundtrainsandtestsdifferentpartitionsofthedatatoreducevariability:2023/11/4LinearRegressionLesson3-42Thefollowingfigureshowstheoutputoftheprecedingcode:2023/11/4LinearRegressionLesson3-43FittingmodelswithgradientdescentIntheexamplesinthischapter,weanalyticallysolvedthevaluesofthemodel‘sparametersthatminimizethecostfunctionwiththefollowingequation:RecallthatXisthematrixofthevaluesoftheexplanatoryvariablesforeachtrainingexample.ThedotproductofXTXresultsinasquarematrixwithdimensionsn×n,wherenisequaltothenumberofexplanatoryvariables.Thecomputationalcomplexityofinvertingthissquarematrixisnearlycubicinthenumberofexplanatoryvariables.Furthermore,XTXcannotbeinvertedifitsdeterminantisequaltozero.2023/11/4LinearRegressionLesson3-44GradientdescentInthissection,wewilldiscussanothermethodtoefficientlyestimatetheoptimalvaluesofthemodel'sparameterscalledgradientdescent.Notethatourdefinitionofagoodfithasnotchanged;wewillstillusegradientdescenttoestimatethevaluesofthemodel‘sparametersthatminimizethevalueofthecostfunction.Gradientdescentissometimesdescribedbytheanalogyofablindfoldedmanwhoistryingtofindhiswayfromsomewhereonamountainsidetothelowestpointofthevalley.2023/11/4LinearRegressionLesson3-45Formally,gradientdescentisanoptimizationalgorithmthatcanbeusedtoestimatethelocalminimumofafunction.Recallthatweareusingtheresidualsumofsquarescostfunction,whichisgivenbythefollowingequation:Wecanusegradientdescenttofindthevaluesofthemodel'sparametersthatminimizethevalueofthecostfunction.Gradientdescentiterativelyupdatesthevaluesofthemodel'sparametersbycalculatingthepartialderivativeofthecostfunctionateachstep.2023/11/4LinearRegressionLesson3-46Itisimportanttonotethatgradientdescentestimatesthelocalminimumofafunction.Athree-dimensionalplotofthevaluesofaconvexcostfunctionforallpossiblevaluesoftheparameterslookslikeabowl.Thebottomofthebowlisthesolelocalminimum.Non-convexcostfunctionscanhavemanylocalminima,thatis,theplotsofthevaluesoftheircostfunctionscanhavemanypeaksandvalleys.Gradientdescentisonlyguaranteedtofindthelocalminimum;itwillfindavalley,butwillnotnecessarilyfindthelowestvalley.Fortunately,theresidualsumofthesquarescostfunctionisconvex.2023/11/4LinearRegressionLesson3-47Typesof

GradientdescentGradientdescentcanvaryintermsofthenumberoftrainingpatternsusedtocalculateerror;thatisinturnusedtoupdatethemodel.Thenumberofpatternsusedtocalculatetheerrorincludeshowstablethegradientisthatisusedtoupdatethemodel.Wewillseethatthereisatensioningradientdescentconfigurationsofcomputationalefficiencyandthefidelityoftheerrorgradient.Thethreemainflavorsofgradientdescentarebatch,stochastic,andmini-batch.2023/11/4LinearRegressionLesson3-48StochasticGradientDescentStochasticgradientdescent,oftenabbreviatedSGD,isavariationofthegradientdescentalgorithmthatcalculatestheerrorandupdatesthemodelforeachexampleinthetrainingdataset.Theupdateofthemodelforeachtrainingexamplemeansthatstochasticgradientdescentisoftencalledanonlinemachinelearningalgorithm.2023/11/4LinearRegressionLesson3-49StochasticGradientDescentUpsidesThefrequentupdatesimmediatelygiveaninsightintotheperformanceofthemodelandtherateofimprovement.Thisvariantofgradientdescentmaybethesimplesttounderstandandimplement,especiallyforbeginners.Theincreasedmodelupdatefrequencycanresultinfasterlearningonsomeproblems.Thenoisyupdateprocesscanallowthemodeltoavoidlocalminima(e.g.prematureconvergence).2023/11/4LinearRegressionLesson3-50StochasticGradientDescentUpsidesDownsidesUpdatingthemodelsofrequentlyismorecomputationallyexpensivethanotherconfigurationsofgradientdescent,takingsignificantlylongertotrainmodelsonlargedatasets.Thefrequentupdatescanresultinanoisygradientsignal,whichmaycausethemodelparametersandinturnthemodelerrortojumparound(haveahighervarianceovertrainingepochs).Thenoisylearningprocessdowntheerrorgradientcanalsomakeithardforthealgorithmtosettleonanerrorminimumforthemodel.2023/11/4LinearRegressionLesson3-51BatchGradientDescentBatchgradientdescentisavariationofthegradientdescentalgorithmthatcalculatestheerrorforeachexampleinthetrainingdataset,butonlyupdatesthemodelafteralltrainingexampleshavebeenevaluated.Onecyclethroughtheentiretrainingdatasetiscalledatrainingepoch.Therefore,itisoftensaidthatbatchgradientdescentperformsmodelupdatesattheendofeachtrainingepoch.2023/11/4LinearRegressionLesson3-52BatchGradientDescentUpsidesFewerupdatestothemodelmeansthisvariantofgradientdescentismorecomputationallyefficientthanstochasticgradientdescent.Thedecreasedupdatefrequencyresultsinamorestableerrorgradientandmayresultinamorestableconvergenceonsomeproblems.Theseparationofthecalculationofpredictionerrorsandthemodelupdatelendsthealgorithmtoparallelprocessingbasedimplementations.2023/11/4LinearRegressionLesson3-53BatchGradientDescentUpsidesDownsidesThemorestableerrorgradientmayresultinprematureconvergenceofthemodeltoalessoptimalsetofparameters.Theupdatesattheendofthetrainingepochrequiretheadditionalcomplexityofaccumulatingpredictionerrorsacrossalltrainingexamples.Commonly,batchgradientdescentisimplementedinsuchawaythatitrequirestheentiretrainingdatasetinmemoryandavailabletothealgorithm.Modelupdates,andinturntrainingspeed,maybecomeveryslowforlargedatasets2023/11/4LinearRegressionLesson3-54Mini-BatchGradientDescentMini-batchgradientdescentisavariationofthegradientdescentalgorithmthatsplitsthetrainingdatasetintosmallbatchesthatareusedtocalculatemodelerrorandupdatemodelcoefficients.Implementationsmaychoosetosumthegradientoverthemini-batchwhichfurtherreducesthevarianceofthegradient.Mini-batchgradientdescentseekstofindabalancebetweentherobustnessofstochasticgradientdescentandtheefficiencyofbatchgradientdescent.Itisthemostcommonimplementationofgradien

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論