0% found this document useful (0 votes)
33 views37 pages

Machine Learning with Python Guide

This document provides an introduction to machine learning and Python. It discusses that machine learning teaches machines how to carry out tasks by providing examples, and the complexity arises from the details. It then summarizes that NumPy provides optimized multi-dimensional arrays as the basic data structure for machine learning algorithms, SciPy uses these arrays to provide numerical methods, and Matplotlib is useful for plotting graphs. The document also provides some basic examples of using NumPy arrays and indexing capabilities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views37 pages

Machine Learning with Python Guide

This document provides an introduction to machine learning and Python. It discusses that machine learning teaches machines how to carry out tasks by providing examples, and the complexity arises from the details. It then summarizes that NumPy provides optimized multi-dimensional arrays as the basic data structure for machine learning algorithms, SciPy uses these arrays to provide numerical methods, and Matplotlib is useful for plotting graphs. The document also provides some basic examples of using NumPy arrays and indexing capabilities.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

UNIT I

MACHINE LEARNING AND PYTHON:

Machine learning (ML) teaches machines how to carry out tasks


by [Link] is that [Link] complexity comes with the
details ,and that is most likely the reason you are reading this
book.
Maybeyouhavetoomuchdataandtoolittleinsight,andyouhopedthatu
[Link]
[Link]
puzzled:which of the myriad of algorithms should you actually
choose?
Ormaybeyouarebroadlyinterestedinmachinelearningandhavebeenreading
a few blog sand articles about it for
[Link], so you started
your exploration and fed some toy data into a decision tree ora
support vector machine. But after you successfully applied it to
some other data,youwondered,wasthewholesettingright?
Didyougettheoptimalresults?Andhow do you know there are no
better algorithms? Or whether your data was "the right one"?
Welcome to the club! We, the authors, were at those stages once
upon a time,looking for information that tells the real story behind
the theoretical text books on machine learning. It turned out that
much of that information was "black
art",[Link],inasense,wewrotethis
booktoour
youngerselves;abookthatnotonlygivesaquickintroductiontomachinel
earning,but also teaches you lessons that we have learned along the
way. We hope that itwill also give you, the reader, a smoother entry
into one of the most exciting fieldsinComputerScience.
Machine learning and Python –the
dream team
The goal of machine learning is to teach machines (software) to
carry out
tasksbyprovidingthemwithacoupleofexamples(howtodoornotdoat
ask).Letusassume that each morning when you turn on your
computer, you perform thesame task of moving e-mails around so
that only those e-mails belonging to a particular topic end up in
the same folder. After some time, you feel bored and think of
automating this chore. One way would be to start analyzing your
brainandwritingdownalltherulesyourbrainprocesseswhileyouaresh
ufflingyour
e-mails. However, this will be quite cumbersome and always
imperfect. While you will miss some rules, you will over-specify
others. A better and more future-
proofwaywouldbetoautomatethisprocessbychoosingasetofe-
mailmetainformationandbody/
foldernamepairsandletanalgorithmcomeupwiththebestruleset.
Thepairswouldbeyourtrainingdata,andtheresultingruleset(alsocalled
model)could then be applied to future e-mails that we have not yet
seen. This is machine learning in its simplest form.
Of course, machine learning (often also referred to as data mining
or
predictiveanalysis)[Link],itss
uccessoverrecentyears can be attributed to the pragmatic way of
using rock-solid techniques andinsights from other successful
fields; for example, statistics. There, the purpose
isforushumanstogetinsightsintothedatabylearningmoreabouttheunde
rlying
[Link]
licationsofmachinelearning([Link],have
n'tyou? ),youwillseethatappliedstatisticsisacommonfieldamongmachi
nelearningexperts.
As you will see later, the process of coming up with a decent ML
approach is nevera waterfall-like process. Instead, you will see
yourself going back and forth in your analysis, trying out different
versions of your input data on diverse sets of ML algorithms. It is
this explorative nature that lends itself perfectly to Python. Beingan
interpreted high-level programming language, it may seem that
Python
wasdesignedspecificallyfortheprocessoftryingoutdifferentthings.W
hatismore,
it does this very fast. Sure enough, it is slower than C or similar
statically-
typedprogramminglanguages;nevertheless,withamyriadofeasy-to-
uselibrariesthatareoftenwritteninC,youdon'thavetosacrificespeedfo
ragility.

INTRODUCTION TO NumPY , SciPy , AND Matplotlib

Luckily,forallthemajoroperatingsystems,namelyWindows,Mac,andL
inux,therearetargetedinstallersforNumPy,SciPy,[Link]
areunsureabouttheinstallationprocess,youmightwanttoinstallEnthou
ghtPythonDistribution([Link]
epd_free.php)orPython(x,y)([Link]
wiki/
Downloads),whichcomewithalltheearliermentionedpackagesinclude
d.
Before we can talk about concrete machine learning algorithms, we
have to talkabout how best to store the data we will chew through.
This is important as themost advanced learning algorithm will not
be of any help to us if they will neverfinish. This may be simply
because accessing the data is too slow. Or maybe
[Link]
hatPythonis an interpreted language (a highly optimized one,
though) that is slow for manynumerically heavy algorithms
compared to C or Fortran. So we might ask why
onearthsomanyscientistsandcompaniesarebettingtheirfortuneonPyt
honeveninthehighlycomputation-intensiveareas?
TheansweristhatinPython,itisveryeasytooffloadnumber-crunchingtasksto
[Link]
PyandSciPydo([Link]
[Link]).Inthistandem,NumPyprovidesthesupportofhighlyoptimized
multidimensionalarrays,whicharethebasicdatastructure of most state-of-
the-art algorithms. SciPy uses those arrays to provide a set offast
numerical recipes. Finally, Matplotlib ([Link] is
probably themostconvenientandfeature-richlibrarytoplothigh-
qualitygraphsusingPython.

Installing Python

ChewingdataefficientlywithNumPyand
intelligently with SciPy
Let us quickly walk through some basic NumPy examples and then
take a look atwhat [Link],
wewillgetourfeetwetwithplottingusingthemarvelousMatplotlibpacka
ge.
YouwillfindmoreinterestingexamplesofwhatNumPycanofferathttp://
[Link]/Tentative_NumPy_Tutorial.
You will also find the book NumPy Beginner's Guide - Second
Edition, Ivan Idris,Packt Publishing very valuable. Additional
tutorial style guides are at [Link] you
may also visit the official SciPy tutorial
at[Link]
Inthisbook,wewilluseNumPyVersion1.6.2andSciPyVersion0.11.0.

LearningNumPy
[Link],weneedtostartthePythoninter
activeshell.
>>>importnumpy
>>>[Link].full_versio
n1.6.2
Aswedonotwanttopolluteournamespace,wecertainlyshouldnotdothefollo
wing:
>>>fromnumpyimport*
[Link]
udedin standard Python. Instead, we will usethe following
convenient shortcut:
>>>importnumpyasnp
>>>a=[Link]([0,1,2,3,4,5])
>>>a
array([0,1,2,3,4,5])
>>>[Link]
1
>>>[Link](
6,)
We just created an array in a similar way to how we would create a
list in [Link], NumPy arrays have additional information
about the shape. In this case,itisaone-
[Link].
Wecannowtransformthisarrayintoa2Dmatrix.
>>>b=[Link]((3,2))
>>>b
array([[0,1],
[2,3],
[4,5]])
>>>[Link]
2
>>>[Link](
3,2)
The funny thing starts when we realize just how much the
NumPy package
[Link],itavoidscopieswhereverpossible.
>>>b[1][0]=77
>>>b
array([[0,1],
[77,3],
[4,5]])
>>>a
array([0,1,77,3,4,5])
Inthiscase,wehavemodifiedthevalue2to77inb,andwecanimmediatelys
[Link]
edatruecopy.
>>>c=[Link]((3,2)).copy()
>>>c
array([[0,1],
[77,3],
[4,5]])
>>>c[0][0]=-99
>>>a
array([0,1,77,3,4,5])
>>>c
array([[-99, 1],
[77, 3],
[4, 5]])
Here,candaaretotallyindependentcopies.
AnotherbigadvantageofNumPyarraysisthattheoperationsareprop
agatedtotheindividualelements.
>>>a*2
array([2,4,6,8,10])
>>>a**2
array([1,4,9,16,25])
ContrastthattoordinaryPythonlists:
>>>[1,2,3,4,5]*2
[1,2,3,4,5,1,2,3,4,5]
>>>[1,2,3,4,5]**2
Traceback (most recent call
last):File"<stdin>",line1,in<module
>
TypeError:unsupportedoperandtype(s)for**orpow():'list'and'int'
Ofcourse,[Link]
mpleoperationslikeaddingorremovingareabitcomplexforNumPyarrays.
Luckily,wehavebothatourdisposal,andwewillusetherightoneforthetaska
thand.

Indexing
PartofthepowerofNumPycomesfromtheversatilewaysinwhichitsarrays
canbeaccessed.
Inadditiontonormallistindexing,itallowsustousearraysthemselvesasindice
s.
>>>a[[Link]([2,3,4])]a
rray([77,3,4])
Inadditiontothefactthatconditionsarenowpropagatedtotheindividualel
ements,wegainaveryconvenientwaytoaccessourdata.
>>>a>4
array([False,False,True,False,False,True],dtype=bool)
>>>a[a>4]
array([77,5])
Thiscanalsobeusedtotrimoutliers.
>>>a[a>4]=4
>>>a
array([0,1,4,3,4,4])
Asthisisafrequentusecase,thereisaspecialclipfunctionforit,clippingthe
valuesatbothendsofanintervalwithonefunctioncallasfollows:
>>>[Link](0,4)
array([0,1,4,3,4,4])

Handlingnon-existingvalues
The power of NumPy's indexing capabilities comes in handy when
preprocessingdata that we have just read in from a text file. It will
most likely contain
invalidvalues,[Link]
Nasfollows:
c=[Link]([1,2,[Link],3,4])#let'spretendwehavereadthisfromatex
tfile
>>>c
array([1., 2.,nan, 3., 4.])
>>>[Link](c)
array([False,False,True,False,False],dtype=bool)
>>>c[~[Link](c)]
array([1.,2.,3.,4.])
>>>
[Link](c[~[Link](c)])2.5

Comparingruntimebehaviors
[Link]
hefollowingcode,wewillcalculatethesumofallsquarednumbersof1to100
0andseehowmuchtimethecalculationwilltake.Wedoit10000timesandre
portthetotaltimesothatourmeasurementisaccurateenough.
importtimeit
normal_py_sec=[Link]('sum(x*xforxinxrange(1000))',
number=1000
0)naive_np_sec=[Link]('sum(na*na)',
setup="importnumpyasnp;na=np.
arange(1000)",
number=10000)
good_np_sec=[Link]('[Link](na)',
setup="importnumpyasnp;na=np.
arange(1000)",
number=10000)

print("NormalPython:
%fsec"%normal_py_sec)print("Naive
NumPy: %f
sec"%naive_np_sec)print("GoodNumPy:
%fsec"%good_np_sec)

NormalPython:1.157467sec
Naive NumPy: 4.061293
secGoodNumPy:0.033419s
ec
We make two interesting observations. First, just using NumPy as
data storage(Naive NumPy) takes 3.5 times longer, which is
surprising since we believe it
[Link]
heaccessof
[Link]
etoapplyalgorithms inside the optimized extension code do we get
speed improvements, andtremendous ones at that: using the dot()
function of NumPy, we are more than 25times faster. In summary, in
every algorithm we are about to implement, we
shouldalwayslookathowwecanmoveloopsoverindividualelementsfro
mPythontosomeofthehighlyoptimizedNumPyorSciPyextensionfuncti
ons.
However, the speed comes ata price. Using NumPyarrays, we no
longer
havetheincredibleflexibilityofPythonlists,whichcanholdbasicallyan
[Link].
>>>a=[Link]([1,2,3])
>>>
[Link]('i
nt64')
Ifwetrytouseelementsofdifferenttypes,NumPywilldoitsbesttocoercethe
mtothemostreasonablecommondatatype:
>>> [Link]([1,
"stringy"])array(['1','stringy'],dtype=
'|S8')
>>> [Link]([1, "stringy",
set([1,2,3])])array([1,stringy,set([1,2,3])],dtype=
object)

Learning SciPy
OntopoftheefficientdatastructuresofNumPy,SciPyoffersamagnitude
[Link]-
heavyalgorithmyoutakefromcurrentbooksonnumericalrecipes,youw
[Link]
ritismatrixmanipulation,linearalgebra,optimization,clustering,spatia
loperations,orevenFastFouriertransformation,thetoolboxisreadilyfill
[Link],itisagoodhabittoalwaysinspectthescipymodulebeforeyo
ustartimplementinganumericalalgorithm.
Forconvenience,thecompletenamespaceofNumPyisalsoaccessible
[Link],fromnowon,wewilluseNumPy'smachineryviatheSciP
[Link]
encesofanybasefunction;forexample:
>>>importscipy,numpy
>>>[Link].full_version
0.11.0
>>>[Link]
True
Thediversealgorithmsaregroupedintothefollowingtoolboxes:

SciPypackage Functionality

cluster Hierarchicalclustering([Link])

Vectorquantization/K-Means([Link])
SciPypackage Functionality

constants Physicalandmathematicalconstants
Conversion methods
fftpack DiscreteFouriertransformalgorithms

integrate Integrationroutines

interpolate Interpolation(linear,cubic,andsoon)

io Datainputandoutput

linalg Linearalgebraroutinesusingtheoptimized
BLASandLAPACKlibraries
maxentropy Functionsforfittingmaximumentropymodels

ndimage n-dimensionalimagepackage

odr Orthogonal

distanceregressionoptimize

Optimization(findingminimaandroots)signal

Signalprocessing

sparse Sparsematrices

spatial Spatialdatastructuresandalgorithms

special
SpecialmathematicalfunctionssuchasBess
elorJacobian
stats Statisticstoolkit

[Link],[Link]
olate,[Link],[Link],wewillbriefly
exploresomefeaturesofthestatspackageandleavetheotherstobeexplaine
dwhentheyshowupinthechapters.
Ourfirst(tiny)machine learning
application
Letusgetourhandsdirtyandhavealookatourhypotheticalwebstartup,MLA
AS,whichsellstheserviceofprovidingmachinelearningalgorithmsviaHTT
[Link],thedemandforbetterinfrastru
[Link]'t
[Link]
d,wewilllosemoneyifwehavenotreservedenoughresourcesforservingallin
[Link],whenwillwehitthelimitofourcurrenti
nfrastructure,whichweestimatedbeing100,[Link]
liketoknowinadvancewhenwehavetorequestadditionalserversinthecloudt
oservealltheincomingrequestssuccessfullywithoutpayingforunusedones.

Readinginthedata
Wehavecollectedthewebstatsforthelastmonthandaggregatedtheminch01/
data/web_traffic.tsv (tsv because it contains tab separated values). They
[Link]
ndthenumberofwebhitsinthathour.
Thefirstfewlineslooklikethefollowing:
UsingSciPy'sgenfromtxt(),wecaneasilyreadinthedata.
importscipyassp
data=[Link]("web_traffic.tsv",delimiter="\t")
Wehavetospecifytabasthedelimitersothatthecolumnsarecorrectlydete
[Link].

>>>print(data[:10])
[[1.00000000e+00

2.27200000e+03][2.00000000e+00
nan]
[3.00000000e+00

1.38600000e+03][4.00000000e+00

1.36500000e+03][5.00000000e+00

1.48800000e+03][6.00000000e+00

1.33700000e+03][7.00000000e+00

1.88300000e+03][8.00000000e+00

2.28300000e+03][9.00000000e+00

1.33500000e+03][1.00000000e+01

1.02500000e+03]]
>>>print([Link])
(743,2)
Wehave743datapointswithtwodimensions.

Preprocessingandcleaningthedata
ItismoreconvenientforSciPytoseparatethedimensionsintotwovecto
rs,[Link],x,willcontainthehoursandtheother
,y,willcontainthe web hits in that particular hour. This splitting is
done using the special
indexnotationofSciPy,usingwhichwecanchoosethecolumnsindivid
ually.
x=data[:,0]
y=data[:,1]

There is much more to the way data can be selected


from a SciPy [Link] out
[Link]
redetailsonindexing,slicing,anditerating.

Onecaveatisthatwestillhavesomevaluesinythatcontaininvalidvalues,na
[Link],whatcanwedowiththem?
Letuscheckhowmanyhourscontaininvaliddata.
>>>[Link]([Link](y))
8
Wearemissingonly8outof743entries,[Link]
emberthat we can index a SciPy array with another array. [Link](y)
returns an array
[Link]~,welogically
negatethat array so that we choose only those elements from x and y
where y does containvalidnumbers.
x=x[~[Link](y)]y
=y[~[Link](y)]
Togetafirstimpressionofourdata,letusplotthedatainascatterplotusingMa
[Link],whichtriestomimicMatla
b'sinterface—averyconvenientandeasy-to-
useone(youwillfindmoretutorialsonplottingat[Link]
users/pyplot_tutorial.html).
[Link]
.scatter(x,y)
[Link]("Webtrafficoverthelastmonth")[Link]("Time")
[Link]("Hits/
hour")[Link]([w*7*24forwinrange(1
0)],
['week
%i'%wforwinrange(10)])[Link]
ale(tight=True)[Link]()
[Link]()
Intheresultingchart,wecanseethatwhileinthefirstweeksthetrafficstayedmore
orlessthesame,thelastweekshowsasteepincrease:
Choosingtherightmodelandlearningalgorithm
Nowthatwehaveafirstimpressionofthedata,wereturntotheinitialquestion:ho
w
longwillourserverhandletheincomingwebtraffic?Toanswerthiswehaveto:
• Findtherealmodelbehindthenoisydatapoints
• Usethemodeltoextrapolateintothefuturetofindthepointintime
whereourinfrastructurehastobeextended

Beforebuildingourfirstmodel
When we talk about models, you can think of them as simplified
theoreticalapproximations of the complex reality. As such there is
always some inferiorityinvolved, also called the approximation
error. This error will guide us in
[Link]
willbecalculatedas the squared distance of the model's prediction to
the real data. That is, for
alearnedmodelfunction,f,theerroriscalculatedasfollows:
deferror(f,x,y):
[Link]((f(x)-y)**2)
Thevectorsxandycontainthewebstatsdatathatwehaveextractedbefore.I
tisthebeautyofSciPy'svectorizedfunctionsthatweexploitherewithf(x).
Thetrainedmodelisassumedtotakeavectorandreturntheresultsagainasa
vectorofthesamesizesothatwecanuseittocalculatethedifferencetoy.

Startingwithasimplestraightline
Let us assume for a second that the underlying model is a straight
line. Thechallenge then is how to best put that line into the chart
so that it results in
[Link]'spolyfit()functiondoesexactlytha
[Link](straightlinehaso
rder1),
itfindsthemodelfunctionthatminimizestheerrorfunctiondefinedearlier.
fp1,residuals,rank,sv,rcond=[Link](x,y,1,full=True)
Thepolyfit()functionreturnstheparametersofthefittedmodelfunction,
fp1;andbysettingfulltoTrue,wealsogetadditionalbackgroundinformatio
[Link],onlyresidualsareofinterest,whichisexactly
theerroroftheapproximation.
>>>print("Modelparameters:%s"%fp1)
Modelparameters:[ 2.59619213989.02487106]
>>>print(res)
[3.17389767e+08]
Thismeansthatthebeststraightlinefitisthefollowingfunction:
f(x)=2.59619213*x+989.02487106.
Wethenusepoly1d()tocreateamodelfunctionfromthemodelparameters.
>>>f1=sp.poly1d(fp1)
>>>print(error(f1,x,y))317
389767.34
Wehaveusedfull=[Link],
wewouldnotneedit,inwhichcaseonlythemodelparameterswouldbereturne
d.

Infact,[Link]
doutmoreaboutitonWikipediabygoingtohttp://
[Link]/wiki/Curve_fitting.

Wecannowusef1()[Link]
lottinginstructions,wesimplyaddthefollowing:
fx=[Link](0,x[-1],1000)#generateX-
[Link](fx,f1(fx),linewidth=4)
[Link](["d=%i"%[Link]],loc="upperleft")
The following graph shows our first trained model:
It seems like the first four weeks are not that far off, although we
clearly see
thatthereissomethingwrongwithourinitialassumptionthattheunderly
[Link],howgoodorbadactuallyistheerrorof31
7,389,767.34?
The absolute value of the error is seldom of use in isolation.
However, whencomparing two competing models, we can use their
errors to judge which one ofthem is better. Although our first model
clearly is not the one we would use,
itservesaveryimportantpurposeintheworkflow:wewilluseitasourbasel
ineuntilwe find a better one. Whatever model we will come up with
in the future, we willcompareitagainstthecurrentbaseline.

Towards some advanced stuff


Letusnowfitamorecomplexmodel,apolynomialofdegree2,toseewhetherit
better"understands"ourdata:
>>>f2p=[Link](x,y,2)
>>>print(f2p)
array([1.05322215e-02,-5.26545650e+00, 1.97476082e+03])
>>>f2=sp.poly1d(f2p)
>>>print(error(f2,x,y))179
983507.878
Thefollowingchartshowsthemodelwetrainedbefore(straightlineofon
edegree)withour newly trained,more complex model withtwo
degrees (dashed):
Theerroris179,983,507.878,whichisalmosthalftheerrorofthestraight-
[Link];however,[Link]
complexfunction,meaning that we have one more parameter to tune
inside polyfit(). The fittedpolynomialisasfollows:
f(x)=0.0105322215*x**2-5.26545650*x+1974.76082
So,ifmorecomplexitygivesbetterresults,whynotincreasethecomplexityeve
n
more?Let'stryitfordegree3,10,and100.

Themorecomplexthedatagets,[Link]
errorsseemtotellthesamestory.
Errord=1:317,389,767.339778
Errord=2:179,983,507.878179
Errord=3:139,350,144.031725
Errord=10:121,942,326.363461
Errord=100:109,318,004.475556
However, taking a closer look at the fitted curves, we start to
wonder
[Link]
meddifferently,do our models correctly represent the underlying
mass behavior of customersvisiting our website? Looking at the
polynomial of degree 10 and 100, we seewildly oscillating
behavior. It seems that the models are fitted too much to
[Link]
[Link].
Atthispoint,wehavethefollowingchoices:
• Selectingoneofthefittedpolynomialmodels.
• Switchingtoanothermorecomplexmodelclass;splines?
• Thinkingdifferentlyaboutthedataandstartingagain.
Ofthefivefittedmodels,thefirst-
ordermodelclearlyistoosimple,andthemodelsoforder10and100arecle
[Link]-andthird-
[Link],ifweextrapolat
ethematbothborders,weseethemgoingberserk.
Switching to a more complex class also seems to be the wrong way
to go about [Link]?
Atthispoint,werealizethatweprobablyhavenotcompletelyunderstoodo
urdata.

Stepping back to go forward – another look atour data


So,[Link]
[Link]
ngweek3.5asaseparationpoint.Wetrainthefirstlinewiththedatauptoweek3,
andthesecondlinewiththeremainingdata.
inflection=3.5*7*24#calculatetheinflectionpointinhoursxa=x[:
inflection]#databeforetheinflectionpoint
ya=y[:inflection]
xb=x[inflection:]#data
afteryb=y[inflection:]

fa=sp.poly1d([Link](xa,ya,1))fb=s
p.poly1d([Link](xb,yb,1))

fa_error=error(fa,xa,ya)fb_e
rror=error(fb,xb,yb)
print("Errorinflection=%f"%
(fa+fb_error))Errorinflection=156,639,407.7015
23
Plotting thet wo models forth etwo data ranges gives the following chart:
Clearly, the combination of these two lines seems to be a much better
fit to the
[Link],thecombinederrorishi
[Link]?
Askeddifferently,whydowetrustthestraightlinefittedonlyatthelastwee
kofourdatamorethananyofthemorecomplexmodels?
[Link]
delsintothefuture,weseehowrightweare(d=1isagainourinitiallystraigh
tline).
Themodelsofdegree10and100don'tseemtoexpectabrightfutureforoursta
[Link]
[Link],thel
ower-
[Link]
scalledunderfitting.
Soletusplayfairtothemodelsofdegree2andaboveandtryouthowtheybe
haveif we fit them only to the data of the last week. After all, we
believe that the
[Link]
eeninthefollowing psychedelic chart, which shows even more
clearly how bad the problem of over fittingis:

Still,judgingfromtheerrorsofthemodelswhentrainedonlyonthedatafromwe
ek
3.5andafter,weshouldstillchoosethemostcomplexone.
Erro d=1: 22143941.107
r 618
Erro d=2: 19768846.989
r 176
Erro d=3: 19766452.361
r 027
Erro d=10: 18949339.348
r 539
Erro d=10 16915159.603
r 0: 877

Training and testing


If only we had some data from the future that we could use to
measure
ourmodelsagainst,weshouldbeabletojudgeourmodelchoiceonlyonth
eresultingapproximationerror.
Althoughwecannotlookintothefuture,wecanandshouldsimulateasimilaref
[Link],forinstance,acertainpercen
[Link]-
[Link]
d-
outdata,weshouldgetamorerealisticpictureofhowthemodelwillbehaveinth
efuture.
Thetesterrorsforthemodelstrainedonlyonthetimeaftertheinflectionpointnow
show a completely different picture.
Erro d=1: 7,917,335.8311
r 22
Erro d=2: 6,993,880.3488
r 70
Erro d=3: 7,137,471.1773
r 63
Erro d=10: 8,805,551.1897
r 38
Erro d=10 10,877,646.621
r 0: 984
Theresultcanbeseeninthefollowingchart:

It seems we finally have a clear winner. The model with degree 2


has the
lowesttesterror,whichistheerrorwhenmeasuredusingdatathatthemod
[Link]'tgetb
adsurpriseswhenfuturedataarrives.
Answeringourinitialquestion
Chapter1
Finally,wehavearrivedatamodelthatwethinkrepresentstheunderlyingproc
essbest;itisnowasimpletaskoffindingoutwhenourinfrastructurewillreach
100,[Link]
hesthevalue100,000.
Having a polynomial ofdegree 2, we couldsimply compute the
inverseof
thefunctionandcalculateitsvalueat100,[Link],wewouldlik
etohaveanapproachthatisapplicabletoanymodelfunctioneasily.
Thiscanbedonebysubtracting100,000fromthepolynomial,whichresult
sinanotherpolynomial,[Link]'soptimizemodule
hasthefsolvefunctiontoachievethiswhenprovidinganinitialstartingpos
ition.Letfbt2bethewinningpolynomialofdegree2:
>>>print(fbt2)
2
0.08844x-97.31x+2.853e+04
>>>print(fbt2-100000)
2
0.08844x-97.31x-7.147e+04

>>>[Link]
>>>reached_max=fsolve(fbt2-100000,800)/(7*24)
>>>print("100,000hits/hourexpectedatweek
%f"%reached_max[0])100,000hits/hourexpectedatweek9.827613
Ourmodeltellsusthatgiventhecurrentuserbehaviorandtractionofourst
artup,itwill takeanother monthuntil wehave reachedour
thresholdcapacity.
Ofcourse,[Link]
therealpicture,youcandrawinmoresophisticatedstatisticstofindoutabo
utthevariancethat we have to expect when looking fartherand further
into the future.
Andthentherearetheuserandunderlyinguserbehaviordynamicsthatwe
[37]
cannotmodel accurately. However, at this point we are fine with the
current [Link] all, we can prepare all the time-consuming
actions now. If we then
monitorourwebtrafficclosely,wewillseeintimewhenwehavetoallocate
newresources.

Common questions

Powered by AI

Python is favored for machine learning because of its interpreted nature and flexibility, allowing rapid prototyping and easy experimentation with different algorithms and data formats . It supports an exploratory approach to machine learning, where users can iteratively test and adjust their models. Despite being slower than C for numerical operations, Python can offload heavy computations to C or Fortran extensions like NumPy and SciPy, which provide optimized array operations and numerical recipes . Moreover, Python’s extensive libraries and community support streamline the implementation of complex machine learning models without sacrificing performance significantly .

NumPy and SciPy enhance computational efficiency in Python by providing advanced data structures and optimized algorithms that are crucial for handling large datasets . NumPy offers multidimensional arrays that are efficiently stored and enable fast element-wise operations. These operations are implemented using highly optimized C and Fortran backend code, allowing complex mathematical computations to be performed much faster than native Python . SciPy builds on NumPy, offering a broad range of numerical algorithms and routines that efficiently use these data structures for operations like linear algebra, optimization, and signal processing . This synergy allows Python to handle computationally intensive tasks more adeptly, rivaling the performance of traditionally faster languages, but with Python's adaptability and ease of use .

Machine learning applications benefit from using SciPy in several ways, particularly for tasks like optimization and signal processing, due to its collection of numerical algorithms that enhance performance and operational efficiency . Optimization techniques are critical in machine learning for tuning model parameters to minimize error functions, and SciPy's optimization library offers methods like gradient descent and Newton's method to perform these tasks efficiently . Regarding signal processing, SciPy provides powerful tools to process and analyze signals, allowing machine learning models to extract relevant features through fourier transforms and filtering techniques . These capabilities make SciPy indispensable for applications involving complex data transformations or requiring high computational precision, directly impacting the effectiveness of machine learning systems .

Overfitting occurs when a model captures not only the underlying pattern but also the noise in the training data, leading to poor generalization to new data . In the context of model complexity, this is often seen when using high-degree polynomials that fit the training data extremely well but fail to perform on unseen data. Overfitting can be identified by comparing the test error—error calculated using unseen data—against the training error. If a complex model shows a low training error but a high test error compared to a simpler model, it indicates overfitting . In the provided example, while higher-degree polynomials returned lower approximation errors on the training set, their errors on test data (held-out data) revealed poor predictive performance, confirming overfitting .

Machine learning offers several advantages over traditional rule-based systems, especially in tasks requiring pattern recognition, such as email organization. Rule-based systems require explicitly programming all possible rules, which can be cumbersome and imperfect, as some rules may be missed while others are over-specified . In contrast, machine learning models can learn from examples through training data and generalize to future, unseen emails. This reduces the need for explicitly defining rules and allows the model to improve over time as more data is available . Additionally, machine learning models are often more adaptable and can handle exceptions and edge cases better than static rule-based systems .

Error functions are crucial for evaluating and comparing the performance of different machine learning models by quantifying how well a model's predictions align with actual observed data . One common approach is to calculate the squared error, which involves summing the squared differences between predicted and observed values to gauge the model's accuracy . Lower error function values generally indicate a model that better approximates the data. When comparing models, the magnitude of their error functions helps determine which model provides a more accurate representation of the underlying data patterns . Crucially, model comparisons often consider both training and test errors to ensure that a selected model generalizes well to new data while avoiding overfitting .

Exploratory Data Analysis (EDA) plays a fundamental role in machine learning model development as it involves examining datasets to discover patterns, spot anomalies, and check assumptions using summary statistics and graphical representations before modeling . Python libraries like Matplotlib support EDA by offering tools to create plots and charts that make it easier to visualize data distributions, correlations, trends over time, and outlier identification . This visualization aids in understanding the data's structure and informing decisions about feature selection, preprocessing needs, and potential model types, ensuring that subsequent modeling is based on a solid understanding of the data . Matplotlib provides functionalities to create a range of visualizations, from basic plots to complex multi-figure plots, facilitating deeper insights during the EDA phase .

Overfitting and underfitting are key considerations in model selection and performance evaluation. Overfitting occurs when a model is too complex and captures the noise rather than the underlying pattern in the data, leading to high variance and poor performance on new data . Underfitting, conversely, happens when a model is too simple, failing to learn the data's patterns, resulting in high bias and suboptimal performance even on training data . Effective model selection thus involves balancing these two, often monitored through validation techniques or maintaining a balance of model complexity that aligns well with the data's inherent complexity . Performance is optimized by choosing models that minimize both bias and variance, ideally using criteria such as cross-validation errors to guide the decision process .

In machine learning, the concept of a "baseline model" serves as a reference point or benchmark to evaluate the performance of more complex models developed subsequently . It represents a simple model, often delivering minimal acceptable performance, against which more complex models can be compared . The baseline's performance sets a standard that new models must meet or exceed to be considered improvements. This iterative improvement process helps in identifying models that provide significant gains in accuracy or efficiency, facilitating systematic verification of progress and guiding model refinements until optimal performance is achieved based on the selected metrics .

The degree of a polynomial in fitting a model greatly influences both its flexibility and capacity to capture trends. A higher polynomial degree allows the model to fit more complex patterns in the data but also increases the risk of overfitting, where the model becomes too tailored to the training data and fails to generalize to new data . This sensitivity makes predictions more volatile and less reliable when extended beyond the scope of the training data. Conversely, a lower degree may underfit the data, missing important trends or patterns, leading to less accurate predictions . Therefore, in trend prediction, selecting the appropriate polynomial degree is crucial for robust model performance, balancing the ability to capture true trends while avoiding the noise-specific intricacies of the dataset .

You might also like