




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
FoundationsofMachineLearning
Regression2023/11/4FoundationsofMachineLearningRegressionSimplelinearregression(簡(jiǎn)單線性回歸)EvaluatingthemodelMultiplelinearregression(多元線性回歸)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ì)于一元線性回歸模型,
假設(shè)從總體中獲取了n組觀察值(X1,Y1),(X2,Y2),
…,(Xn,Yn)。對(duì)于平面中的這n個(gè)點(diǎn),可以使用無(wú)數(shù)條曲線來(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)益歸上傳用戶所有。
- 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ì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 農(nóng)戶經(jīng)營(yíng)貸款管理辦法
- 消防安全管理人的消防安全職責(zé)
- ?;钒踩?guī)范
- 當(dāng)一日安全員心得體會(huì)50字
- 安全生產(chǎn)自查表
- 防水工程安全措施
- 虛擬社群凝聚力測(cè)量-洞察及研究
- 機(jī)修工崗位安全生產(chǎn)責(zé)任制
- 無(wú)票作業(yè)事故心得體會(huì)
- 派出所民警工作職責(zé)
- 滅火器維修與報(bào)廢規(guī)程
- JJF 1183-2007溫度變送器校準(zhǔn)規(guī)范
- GB/T 41051-2021全斷面隧道掘進(jìn)機(jī)巖石隧道掘進(jìn)機(jī)安全要求
- GB/T 37787-2019金屬材料顯微疏松的測(cè)定熒光法
- Unit2 Section B(1a-1e)作業(yè)設(shè)計(jì)教案 人教版英語(yǔ)八年級(jí)上冊(cè)
- GA/T 1169-2014警用電子封控設(shè)備技術(shù)規(guī)范
- 第十二篇 糖尿病患者生活常識(shí)
- 污水處理站安全培訓(xùn)課件
- 2015高考全國(guó)新課標(biāo)1地理試題及答案
- GB 27954-2020 黏膜消毒劑通用要求
- (完整版)ECRS培訓(xùn)課件
評(píng)論
0/150
提交評(píng)論