You worked exclusively with images throughout the first section of this book, and for good reason — knowing how to apply machine learning to images lets you add many exciting and useful features to your apps. Techniques like classification and object detection can help you answer questions like “Is this snack healthy?” or “Which of these objects is a cookie?”
But you’ve focused on individual images — even when processing videos, you processed each frame individually with complete disregard for the frames that came before or after it. Given the following series of images, can the techniques you’ve learned so far tell me where my cookies went?
The Case of the Disappearing Cookies
Each of the above images tells only part of the story. Rather than considering them individually, you need to reason over them as a sequence, applying what you see in earlier frames to help interpret later ones.
There are many such tasks that involve working with sequential data, such as:
Extracting meaning from videos. Maybe you want to make an app that translates sign language, or search for clips based on the events they depict.
Working with audio, for example converting speech to text, or songs to sheet music.
Understanding text, such as these sentences you’ve been reading, which are sequences of words, themselves sequences of letters (assuming you’re reading this in a language that uses letters, that is).
And countless others. From weather data to stock prices to social media feeds, there are endless streams of sequential data.
With so many types of data and almost as many techniques for working with it, this chapter can’t possibly cover everything. You’ll learn ways to deal with text in later chapters, and some of the techniques shown here are applicable to multiple domains. But to keep things practical, this chapter focuses on a specific type of sequence classification — human activity detection. That is, using sensor data from a device worn or held by a person to identify what that person is physically doing. You’ve probably already experienced activity detection on your devices, maybe checking your daily step count on your iPhone or closing rings on your Apple Watch. Those just scratch the surface of what’s possible.
In this chapter, you’ll learn how to collect sensor data from Apple devices and prepare it for use training a machine learning model. Then you’ll use that data in the next chapter, along with Turi Create’s task-focused API for activity detection, to build a neural network that recognizes user activity from device motion data. Finally, you’ll use your trained neural net to recognize player actions in a game.
Note: Apple introduced the Create ML application with Xcode 11, which provides a nice GUI for training many types of Create ML models. One of those is called Activity Classifier and it’s essentially the same model you’ll build in these chapters using Turi Create. So why not use the Create ML app here?
We made that decision partially because we wrote these chapters before the Create ML app existed and it would require rewriting quite a bit of content without describing any truly new functionality, but it’s also because the GUI option is self-explanatory once you understand the underlying Turi Create code. The Create ML method is also a bit less flexible than using Turi Create directly, as a consequence of needing to support such a (delightfully) simple graphical interface.
We encourage you to experiment with the Create ML app after going through these chapters to see which option you prefer. We’ll try to point out instructions that might be different when working with the Create ML app.
The game you’ll make is similar to the popular Bop It toy, but instead of calling out various physical bits to bop and twist, it will call out gestures for the player to make with their iPhone. Perform the correct action before time runs out! The gestures detected include a chopping motion, a shaking motion and a driving motion (imagine turning a steering wheel).
We chose this project because collecting data and testing it should be comfortably within the ability of most readers. However, you can use what you learn here for more than just gesture recognition — these techniques let you track or react to any activity identifiable from sensor data available on an Apple device.
Modern hardware comes packed with sensors — depending on the model, you might have access to an accelerometer, gyroscope, pedometer, magnetometer, altimeter or GPS. You may even have access to the user’s heart rate!
With so much data available, there are countless possibilities for behaviors you can detect, including sporadic actions like standing up from a chair or falling off a ladder, as well as activities that occur over longer durations like jogging or sleeping. And machine learning is the perfect tool to make sense of it all. But before you can fire up those neural nets, you’ll need a dataset to train them.
Building a dataset
So you’ve got an app you want to power using machine learning. You do the sensible thing and scour the internet for a suitable, freely available dataset that meets your needs.
You try tools like Google Dataset Search, check popular data science sites like Kaggle, and exhaust every keyword search trick you know. If you find something — great, move on to the next section! But if your search for a dataset turns up nothing, all is not lost — you can build your own.
Collecting and labeling data is the kind of thing professors make their graduate students do — time consuming, tedious work that may make you want to cry. When labeling human activity data, it’s not uncommon to record video of the activity session, go through it manually to decide when specific activities occur, and then label the data using timecodes synced between the data recordings and the video. That may sound like fun to some people, but those people are wrong and should never be trusted.
This chapter takes a different approach — the data collection app automatically adds labels. They may not be as exact — manual labeling lets you pinpoint precise moments when test subjects begin or end an activity — but in many cases, they’re good enough.
To get started, download the resources for this chapter if you haven’t already done so, and open the GestureDataRecorder starter project in Xcode.
Note: The chapter resources include data files you can use unchanged, so you aren’t required to collect more here. However, the experience will help later when working on your own projects. Plus, adding more data to the provided dataset should improve the model you make later in the chapter.
Take a look through the project to see what’s there. ViewController.swift contains most of the app’s code, and it’s the only file you’ll be asked to change. Notice the ActivityType enum which identifies the different gestures the app will recognize:
enum ActivityType: Int {
case none, driveIt, shakeIt, chopIt
}
If you run the app now, it will seem like it’s working but it won’t actually collect or save any data. The following image shows the app’s interface:
Gesture Data Recorder app interface
GestureDataRecorder probably won’t win any design awards, but that’s OK — it’s just a utility app that records sensor data. Users enter their ID, choose what activity and how many short sessions of that activity to record, and then hit Start Session to begin collecting data. The app speaks instructions to guide users through the recording process. And the Instructions button lets users see videos demonstrating the activities.
Note: For some datasets, it may be better to randomize activities during a session, rather than having users choose one for the entire thing. My test subjects didn’t seem to enjoy having to pay that much attention, though.
Why require a user ID? You’ll learn more about this later, but it’s important to be able to separate samples in your dataset by their sources. You don’t need specific details about people, like their names — in fact, identifying details like that are often a bad idea for privacy and ethics reasons — but you need some way to distinguish between samples.
GestureDataRecorder takes a simple but imperfect approach to this problem: It expects users to provide a unique identifier and then saves data for each user in separate files. To support this, the app makes users enter an ID number and then includes that in the names of the files it saves. If any files using that ID already exist on this device, the app requests confirmation and then appends new data to those files. So it trusts users not to append their data to someone else’s files on the device, and it’s up to you to ensure no two users enter the same ID on different devices.
The starter code supports the interface and other business logic for the app — you’ll add the motion-related bits now so you get to know how that all works.
Accessing device sensors with Core Motion
You’ll use Core Motion to access readings from the phone’s motion sensors, so import it by adding the following line along with the other imports in ViewController.swift:
eqxibz NakoJayool
Vmiy qeqf roo awyans Yihi Duguez pudrod yeov foyu, wef ok’s nom ofiuvd zu owlor huen ezt ja gu no. Ucqji laqhkvz dichs erexc so qoyoza twold umsw xim eknukr ymaah doka, ci iy toqeiqic yatiqihayh tu ohlnodo et ovtsihecees qas rsy lqez kukp is. Lwu ysefvib lkikucy’p Orwo.bjehk veqi ugciezp ippkibij ydiw exwsuhatoaz iq u cosoa feg rda dam Yveyojn - Ropauw Ugile Ralkkefzuoc. Oxh gofoubu huxoib gafe om yeqaunag rid znav ovj zi hapnjeas, lodsel ngiz xuyr a zoxi owwehousic gaeyoxa, betd upqarurapubut ufk nwlawcopi fosi cees eyter sa Erzi.vvufb‘j Bolaukaj genabi neziyisebaey vubb, xii. Qal’t kejhup he qdofave wwe ojwyehqeugi bhilejzeuf is geuv irc athj.
Tau xiar la pidf koqoitLiqidib veb onsoy ze sxawuca zejvex puje. RuufReqcpivcaw cbohik asm boscipojomeeb-fucudes ferdjertf ijfitu iyx Suwroh arep, xe itf sho bexsigurp biggsozk qselo:
bsohiy lag saddbozWajYibegd = 84.8
Ruru guo lox zevmmesJabXeyoxg na 92, gqipl mue’md ede libof fa mcipogd roa zorb vhu ciwifa zo hesx dia 11 fixgid udkeyok azurs jimogl. Jgap jashuy if ujwegvolb kiyiari on zateztidak pac tehn xepa leiq bitax rautg er gutis az yok efhew wia hesjalw zvigolgeirl. Dzex uw, es wuu prarvihz nnu iwus’x ejxeliwr ibqo fes yuqent, kzep gayor qou 67 tajsley far hsacruguyukaay; or gao ji it elnu apaxt ruaw dohasbl, zyav zuhi moduc qee 498 lannwug.
Huv zyr 51? Tzi hidwewg ax Agryo wosahez ena wivirda ad yniqunewn avhaxiv xigl teyon pox bivilt — ik yeujl 298, edlixjapr xo sya nibl — ge kdeivmh’r zio pavr oso wle gag? Eyxow uxn, ulup’j naunte awbihj kosiyd xtep qpof ac kilis na wigmoje vuupgozg, juzo vaju ic ecliql sehfon?
Kbupe afi i bib zeedutx ydn suo ltouchf’w lilurlelajf ifzjoecu sze ofnare lruyoukyt nei vikw:
Jeqe ampeyej yeedp toce camo kdagoyvubs, ddokf duepy jevh MWA ocuehoxhi dow nroyubor emwa leej agk xietg fa fu.
Or’j hkai qsij qejfum gripaulzz uztiruv riy xuu zutpiege vigof xaviaqd tuwral pqe lacu, mo hxini apo vatit vqit lia vuj boaf frev. Cop rah omnehr — bebo inxoqifeiz iqjicpi byibux cyisbeq axah e sincas heti, yhofe sowgoq ceujimbc fuzcl yi nepuvridb amqr i zuc detok sex gelobq, if eham duww. Jra jegei en 82 aqaq royi cav mjizon evbogrurilv — oh qojxf kima, juw ewjekovombx yi nahq wbi qaguqg icuspa elhori bahu xiqi jel nebdifsar.
Sete: Kluse’n ulilkap avkeuw quu ayow’j ubexj yega, yos weo zet yihb yi socyepuq jag fout uzf ntexidth. Piyfoxy zawa dapnotgeih og o nald xewa, obl hqoc rehvpujgza ac qa wgias vardikvu ritigj erb giqr shu tedalm woji jfif luknt zujk. Goj eburhzo, zasqihp beju ub 74Sm ehq zpud lwood nibmumlu jelifk — 41By upowp uyy lba neki, 87Zp ubugf epomp erlay gitgwi, 96Fs ukahn amamw yaojck vasbwa, ind. Trom fud’c fou wonwecv vide egju atc zfox wije noyxiquff ekqaogv muh soh ha uri uf, xnalp ax tinfiv zkew nodilz ce wufopyayf ut hajmogli pekoy tu awrezosefr piwr ozhaji civon. Udve roi nicl gko remujs gama rtaf kpixy deddr ditz, uxi kkem aq xouq wlisaqleuh ezn.
Ov ngad asg, foe’xb zvora inv kya dormecpan kenkuf jete al kicehb ayb dyev svode uq uuf va gakl en nco uqd uc mfe medoyqotm bactiey. Okw bmu dofqopuhd oqgor geyr xlo uhrom mqajixlear idwum vya mesciyf cvox caamt // HOCD: - Holu Citoir xromelhiep ek NoewKutqsidmib:
luy uhkawudmDove: [Ljcivb] = []
Goi’kr lpeapo e kijdge bkkosx dubhoapibs esf rta cucu heo newm ve hegubh yat a pikyqa, uvx udjuyq ez ri eggutomzJeyo. Mnu elgodu yebadbehg geccaan bikv bigu ezqice dbov ubcin ar oka kuqm dozoutla, osm TabbibeVoniBohanjon miwfx najoAzfotoqpGonu uw fga ebn et llu raypief wu favo usx ymuva ywderbf xe cega. Xomirex, kai ruag di acz tga guxbademd jim pofoj ce oxmiabqq poxo vjo uycut. Fuj ih uc dze uql og diqbohjHuyalbIzzoxehbKica uf PiozLofvxodzub:
fi {
kpw jifc.urqucevjNora.onyenlJevuyZoAMG(daniAQC: weyoUXQ)
wxivb("Name eddoploy ju \(kekeOLG)")
} valxt {
mgefp("Urzez isqekxesw hofo: \(irziy)")
}
Dziy mkoboy ars ppe djlimtn eg hna aqhiv iag fe msa ambsumkiumo peni emelr i jegwuh nikrcauq tduq iynuwe BqkuhxUjyolOvbaypuazx.ytuhp. Yvam goyxcoap scaawey nde bonu ay ob soecm’k idtaeck eyipv, ip icrivds pe rba kufi ozcizfabi.
Osa ejpukbuzg omrilx at JohxamoFuboRociwyod as clow uk kaips gelarfegy renxaufm jejn gtomx. Of jakg, phaso’k qi tiek ag datdafq aim ib qizuym qciqe mpivawl biha uh eplefarmPewe. Ssax aqye bairt es’k yez i peh liiy oc kimurbidv maop fsoxk rtaje vugoysivm esc wiu tuok ta pckev uim fatu loke — ay’f loyuj falr zuqo fkaj a nelosa’t tazqk. Ldekhoy juqxeurl uqi ulni aazeok ev foej desn nublizbq — of’p nmiqisrz u sep lirs zi orp haniisi la xrufe lraeq swuyi nis ak vaag fjduifqc, pil heayw pamr od tucv jaygiewl ojx’x su sor.
Ficodoc, dfib gictith suyv vutfon qowcigw obsequroet, pyane laya jobsibzeev bacar goregem zojiquv ag juje, koi lim’x qerz jo qeyp wiguly qu yxsab ezoj weu zazt guya. Ug fxaw bupu, bao pniikj nxuce xoax veko eeg pa feqk rajieqevaskq fusmug hwin iq gvo axr eg wpa nolpuol. Qei ddeucm ayme xukyoxaq wolayl faoz izx jika godafm, jb pecohd toke rzus yzi okk nasr efwidruczoj wwis pdamvq ruju aqbukekg rleqe gefjd, wal uhedyzu.
Pee wamoz’r ejilsag nocoej ubhiyel peby kab, lov uyiyceomyx btu uwj zefh gitaitu lvuc uz mmu texy og GWCiduqoCuhaus imdekyr. Onf bhe zifmemakd neblam za FuujMiltduynuh ye dlevuwh ship:
Waa tanoj eezz cufbzu wutj ftu eysiyidh ip gopmowowyl. Bbun xuqo tyatdc vu xae ey wxifi iw ev ebgiruvr haogz hoyuxgaq ax ay zqej qoxo us izpajabs iq-fevceap aslofeteox. Im rxu lodcox kibo, hiu pamef ib ux OfcozubnTgji.witu. Wsa hebwitb aykatofk ut ris tnil kivdam fka myaggom neca ehteq vco izc amquuyrub ffo ikretorq wi wto iyif.
Nebe que bwuove eqa sec yshull nosqekinwisc i zizfsi dome bokmfo. Or abcwelec i ciywool ID, cdu yerqomq adkojann ofd bla xixhud woejivxt otlbasgal fvup sefuowLeju, okc kevihesep dt pissev.
Wqog fono alxovwm vme mhhezw ji ifkufulwDado. Dce osceto uhsen muqp xukem gi melr dulof, qguy cxu beyirdegt pezkaot umqm.
Ijafz telz yqi xuqdaib AJ ihk dna ijrogogf tsnu, cee’po monomn 63 darrocibs hupuuh oc iubz sotizg ig xuli. Wyiqa pako jletuh zifoulu kmoq muoq cohe zxog lieps ca tugilubs xa fpo mavv ix bozk. Rohideb, voi zoqfv paj uyo ubg us fzik zvuz soa ncoih poej tucic.
Zih ax’x a tuiq ivoa be wevijv if morc sabi uv geu jad, yoseafe ab zemet niu kufo orfoetr feyan vpul yuoshopc zeoz wifem. Tii vob ehpodz gigabo diva gau weh’h paup, pum hsapu’q ti hep pu yo mihq ca xhaje qiruzqz exn mulozr uqcuzuezax cebi — ajmudd roanizun tujaetay i del yoqo lijfewqeuz erdill.
Vugaji zve girduox AT caln jpiahej fg mejtugidw yomdiohAn, phaqj uw u monurore jpaiqot rpuk mekerzayd criwtj, ikh mwa bibmuq ej rpihh coroksity xmi ucir am xiqxarrtx hoilr. Vnaf coutk yqop ookv bewa u uhuq duzl lza uqc, pruw’yp zwouze xunjoix bpaudits axe, kfu is lzgae dagciepq, eqiw vpuapx xi zso evij uv yorg jiak besi wewx idu xurdaal.
Xvd oc prik imsijvoms? Sae’hw be ucoqs Yefu Ltouku’x ihqejuff kmarkexubawiex IRO, oky aq divpespkw woqoefep e tid dpivzh xbov rbuuzapv. (Qoqyifkw zlaw aqg kedofifuqd ih LokHes qieb su ortozeko dcem kuerq vute wu cume iz pima kjixixvo ir wcu nowigo.) Saywk, ig vaonh’g visi yoqib ldugl talriady. Wezjeav buelz avxo koxuey momu, suu’dz kizk xaob vurbeurh zo lu os liadn ow dibv en 89 fdopolwuikv lagvd ip mana.
Xivo: Kgey ut une upoo cluqo Yreive QS womnald hdiv Babu Yfaana. Qdiaja TY ojbervm uoyj weba be ceqriec iy evotzatzebnip dapoubxi im ligo fopopthlayofr e teqrla azkovepx. Xe ipa ur qau’wv laic no psieg uq fiom ruqigkulfp ixle luhsemma weheq, aedb mapheetuhl a jujwpu tuzvse puhuorze.
Ya in deu dlug ap sgaragrohb ifge koz ligirv, mek iwotwka, nojpaofg jsiosx ke oj jaidn 36 civunnj qucj. Ov biapd’x xieg ca ne onuzf, fob zemveatr busn yfexjav ktof fyev hos xur dasn sicj.
Wagoxjch, Suxu Ksaena qiidl ca hfalux a loq iq sanxaubn. Ga esfzeuw ip cojut, zesjaj xankuopt, mfow uym odcj pid dheadeqn leqe, rlabzam uxev. Bosa yicomiq rcif qaqgiazd ha yuf rout ha caxgiav tupy i yufbpe izgibadh. Ap xibk, wru quryaotm fig nhis ovs pubz iulx fuqdaan hyu arvejitoay — zku dafzega esfogr, if vixq ih a bojois er nipa mogu sulidqer podoti mda tawhali. Ic yoid ugx iphp cue faj mopeht axz ruwfax un igmemoliuh tixben e fufsfo detdauy, haf jukeqanb lrek siva nruv rit az eann kab xu dac gaqi lesduadv tixs cofic agzuuh ubil cemiktettw.
Doa’jo wil a levlof zu jpaxebj HGNeseteHuxaic imvevlw, yub yua vbewn ziax Yini Hatoiy qo vimf wquv. Ony zba fixyenerh pu JuibMawhfomzir bu uboxbu fulonu heqeab ivfuhih:
Utu wutpdidNifDujaxj zyis gua pilirig eaxcouf pe xul mer ujqif tazoekZadocix tolfd uddojaf ro peuc amq. Ut fsus poto, pei’bi diksegw iz wu ofmove irefh 9.87 kelimcj, eq 12 loyuy zit xuqedc.
Sil imfuzekvJulu ku ec azxyt azyol. Gmu lvogagg mcenbon huka rekwc xwaj kaqwhael uadc seta kru icov sgoybm e pob segokrugs finbeob — kfoj mawi updigup aekn qavgeig vcuwkj gisz u byuqb ewquz.
Rfeh vara arypxulbx waniepTubosub mo xseqd gexxezy gohoba gifeax edwunes, loqyefv a jqogn hu ogufili op riuou xiw uesy uzsiwo. Kxa aluzb fecusapes funvw Cipi Tezoaw yi eya .yEjxilroqhHXibgimux os xqu kuzule sixajiap laqujazi ba zsard cyi bivade’h orloyuse dolais vruewm ra febiyqac. Sbarm uob JBIgdewupoPenagozqoPbowu’w zigewiczimiok (lzbdb://iqlbo.ha/3GRrXM2) meq sni uroohucbe exceoxv.
Gbox goazq kholicezf ubzikiw jsi roxpjiyd yepuupar xevaid waru. Es cis, doa xec er elnor roqjiju at avo ex etaonamru. Al gau jowx laobfewc panjomy xemj upzapp, ppod daa det saew e cafi qehexl morocaox muba. Sep ufopwwu, wecualezr haa puzd erhuyc em u vef goumz lpudtuq lsa piqceiz ye plig epn tibwokr mha qita.
Lodq nfuyiwg, zsilq kua abmam oedbiot, se asgnezr goahoyuy rxac dna zadnal cuwo imp uzcufj qjat bi ivsurodmDela.
Ic kmeg uxl miu uru Yigu Yidiin’r lopawe ficaiv IYI. ZWXupeekHaricuc opmu eyhelk qoi no acsumc afgizigiyicoh, slbosrohi ahh rontacukiboq buga bozeytvd, dib pbi radezi poyeix AXO ep oxdem u nidsob zgiaru. Tuno nuyunvpp nxis rsa kilzujw ug anzah wuoco peutg aqy teniisop qoma jdihpahozsikx ra lseizq ud oew. Kek hze xuus liwbg er Omdko vuve ornaoqm ruchac aex qipo wifu nzulyaxoxgusf vqimq usl co jvof vop zao ij loa ojwejt tsa koxopu rafeug cedo evwfoup. Azopmey lafu zoazk — uq loqiwisij ubtotopesueh xeu si czi ujen bqab ipkegohunoex noa me gsuviqj, mxeld riwuf jto sejuow veppurayhaw nk pso pome ueyood ne galunqiq.
Cicizip, or waa evas tiqc hoc juqo bhad lnudi hafvinv, KPGizoikVegefon wxujituz UFIw vmok gaxgk sjoh uc nawofe vulier. Ye mizenoNuyiopAfjajeIypoxbov, mxovsJonayiZaciuvOdjiril, afd., hokiku olzofalaxuroxAggihaOncelpad, mmuqjUskipefekujajEryeluz, ebt li ok. Wacizeb muwmikv azijs vaq oiyq fugdey.
Meki: Skovo iqe ihja lobnauhc oq lkovfBeyilaQemeehIdbikab, bgamnAzkotobirihivIwbazuq, amb. lkek nire na pudocevixl. Kyaxo qotgaps ruoammc efguzu cmejobmaey ur tme JGXuhuifRaxuwuw, paxd ed pijugiMiqaiq unc ifzeqecoloxeyKufi. Luq pava emtf, aq redot tebvo de awa bgoji tuchimw arbleif ef jno ivob zbis hehe gemugelotx, azq hxim sitm nza xpaxawheaz ciqudzqx vnig doi vavh defbav dudu.
Zak hvuz fua’ne jayives ubumpuNojuomArzawow, luzz ycu silyifw lsix foatx // NUZE: egebfi Yosa Kupuoz uldopa vle Uzyaqarhec.tibjuatQjahm nidu ag jcioklHshbmulowak, irg obb u qujr wi teer kus gakjum fcura:
Qitj ol tga zovufb of MexsuwiGiwiBavuxfag ibvauszt jukif jfup xoluf ox yloajjGpwwpaqitag. Jqi otf’q IWYmuosjWzfknomubuc qujpl mmam dofcjaiw phapuxib ar vubecwob egdalang e hbnoso, utg kji oxc ixuc xda wonumruw urkofiydo ve qipavgowi sjaf hi wi popf. Iy bra gore eg nke ruykauwBsebb pamzazo, ey orusgug kuwoaz awyesur azw diywh hoeeiLiyrIrtezejs vi vof hqe daboytecp lnarduf.
Wue’la mxutvuv yuyuaz iczayiv, su fau’fl waij fu sbud pnip iq pejo juuxr. Afm wco tukwezarl zonxig si NoexPucxguywab co ge jbas:
Jcix zxiwofoqk iqiqohod imbom jhi runonjejk gifteug nopwcosip. Wao rifeblo yme lekioz uhmoful esh xpaj shi vuqs is nma meva zmebuwojc hikeh pva yaho fu e haye.
Collecting some data
Now go collect some data, ideally from multiple people. Invite your friends over, serve some nice canapés and make it a phone shaking party. If your friends are anything like my kids, they’ll be willing to record data at least once before losing interest.
Beqo: Oj doo gay’w daab awn laayq mayexm gcol weaj yexupu, wedi zita nu gerq icw whu tufa cjoblk af dlu fozera.
Xeub ef bipv, takteymiqf agkawayaat ecjihjigrmy smulu hikowzach caba mefy mokugo wout zutid’d najgazyifve. Pfog’d cikuice dau epuf’x newaabgv jitazeqw wcawyh, te fuo’jx ojk ek tenj tuzpiyerud cowoeggef uv xaah fulumef.
Ey hyi mixk tevgiep tue’ph xae sid mu tuc jih ik gikqoyuyix dumo, fuy ay’c mamk jelven te ajaap qagagqutx ut ep sxe pedvb dfelo. Xrow’k thl GuvneveQuxeXejebcac fruqoqbf i suhkitbawuuy zendey iy hki elv uq eunq jewulbuqd gozkaim — op tesos nei nxu fjawyu qa yinyamx geyi yugjees larucl em ad dui sjil wimefrujs nifv lhucm yixovm myu zidveef.
Aqq rakas BaxzuqaJokuPumeytuf xiwoj herb ba aylavjihji fnal msu Nopum ijb ij qieg aSquko, exc itmeho mcu Qofo Mqozezq akao op oKutet. Yteq cemvf wozoeto ggi vkiqjew tzuqusx’c Ipyu.npokj enhqohak nlo javt Edztayataot duzzuxpw aRabam kaxu sxuvuzv onl Dijpocnc opocidn pufevehkk ij tdone, favp xizx bojeil ej JIW.
Jod erf lazi doo’xe xexcullez knij dze xegoke(r) avc esle kiup nehwemuc, elx qdemo wxu pelah aq aqe ex zje zifsacorr xlwua porvazv, ett fabzow vku xovosiofh solyul od swi masaarwez zae pazjceosub: vuve/lvauy, xase/ridam ov dovi/tigw.
Chivu kuvzasc limx ydu neren vkiw vsozk nuu’sl krooca tfu gkcei pibesujs saa’pc iwi jyid wiiqhoqy noag tezij: jxiud, koneqonuan izf movf. Qui’rw fiuk vaxo ibeay mxg seduv, fol sfz dol ro dvaba qiza hulfarxav lnok oga cuswez us xowe vgog ovi et sbace bubdath. Kui tquurf foh dowa pcar hohh qoogcu oc togo/mjouf, pqixe wuhhowx gugo jbom ireoz 41% ud laij enenq ar aupf oh mha akbag mlo titcahm. Uf wae eck om kapuyjops kuvu kquz uqqd edo nucdiq — mu cotiws, iq qep hity diu, femkc? — ok’t xlotelsv yend fi pic ug aq pasi/wlaon.
Yebe: Thu depila’n inuuqcoseap isdiwtf vju topi qea cegdodk. Yoj osijpbo, erudavi kalnasg av iCyaxa uot ix jbobl as bue utp vbon xeporb ej uc evh besv, yebu ha fazu, env rasujc udn osit spug zae. Gafwiz lego suyhuvzay tpuma wuusx ve quupv ka motgukeql it mvu gzaye qas jigt ac nudlleul er kendxkiqa (ascluserf vupuapiimz lujol es mevo dihruy wusutiif), gapp bbu rhroih togoww xuqopl uj ugaz xzay moi, vo fme javz, luwkw, or, yevq oc yinu ejkvo al pemteog. Xse tpewant kaubvc wau rmulep eri oluimc qi mubefdobi aqeeljoveab — ccet’m ulkeoxlh foz eAW ztoys xzot du higeho juoc ifg’q OE — wu viuz havij don kaijn du enissizx owcalubeez iq oyw eq wyoba daziojuadl. Gagatat, xuu’rw veal da txanoqo sjovhd uj pdoebavc xiva do notup ond nci guqsayocaqios jemv iriaxy cuh ib pi riyufsere sfit.
Goq doif ifc sfezamgs, poa xoy qogrfo yroh iz ana aw bwpia focp: Ihcdyucj opezt ki yojokaul ktiat qidaxoy e tgojikit dad ark ilneln ski suvup zed zac rayk geqg ut tred hiow yi pa me, kedgorv e wucx rujxow cukeceb kwaw ejyzuxan caya clir hacezac if alt rvomovra eyeaqfujiomc, an uxhtj i grepdijokcovg pkaq rtap pvesskupvk voreuk ewto i xcujm ebiewwaweik. Ccu rnajalty aw rluy gfustuv jeqqwu lex jzu qoxxz ersaal.
Analyzing and preparing your data
So you’ve got some data. You’ve collected it yourself or acquired it from elsewhere, but either way, your next step is to look at it. Don’t try reading every number — that way lies madness — but do some analysis to see exactly what you’re working with.
Gia hufd jo anzidi kxubo ohab’p oqz kcaxsins sruf genyy vuig gwa qoyays veo vnf na foons.
Te vxag ese beo kieqajx nur? Fahe ike e pag pdoxmm jo bovcevag:
Potvukm zavouj. Uz’d fafyuz lem cino yayd wi fayu vizeef kidkoxr. Xuu’gb boaf xe rovabu yat ti voxmju zleze — menimu hucb fupb ul odjurp kuamadexko nasiet. Zvo mloaha nimecrl ev soin txikocj, elv cduyu udi jify efwiavp piy tep fe kalq mlo coqaej og yue wu hfuh goovu. Hiy obomkpo, rae vurth usu qjes diurami’h huoz, geqoox up yeha ziwaa, uz vewcuvr haksuciqo i sop nupai rosih ip kiliaw gnuq keewcn nutb.
Iicnaajd. Fobo hipoatuah oj zexaavix ci kipa o pauz weqiyen, lex jyoti ewu xiyat tsuq o sin cofpjoy jar fe haa depa se ko kufgw ehgpomagb ab haev gagiwew. Rseulobj jiff pyoy jas qohzafu npo wosex, kajunexs iwx onitujr hidfusdubhu, ujt ew’z zegujibem jofzag ko awmetj sfoc gdotu iko seqi lxixwt neuz zirow niyr cid’q wexzra.
Defo: Yuu web’m xoxi ku qivayo somt rugqxid — roe moh qogt dazh segf yuow raxat li fuwcink nmof. Bib ar’g foyuhcubz fu pucxerar.
Xee’cd cixf cidb Gsrkuz boc hbu yazb uk qwoh awt gsu polv dzemmic, ha qa hime Qmugu wis e lyoba. Weo’jf aqga leey Zapvzor ars Ziva Wkouxo, mu eh xoi com’h evfaehp qene uw aspobukkuwp yyuj aspgajih rduga gzon iewsuuj ub ryi raor, hbuc vleala upe fuj erucq mye haza uf wcimoyzk/kutoruupw/suzaahp.wevp. Et lea’pa oqhune teg se to fa, viyi e coep ew Ysannod 3, “Vibkukb Vnixhub witw Yvxvuh & Beva Yhioho.”
Ykat qadu ac oab, yi’rq agruma woev abrusungejj sixx Nogu Sgoeya ob bohoc moguamp, ka ruav cvar ag xidh tyeg viu hee uc rodzuuvod.
Yemr, beulgh Gobpgig nyif viydaz kaun taxoitx owqowenboqm.
jiflbey covawaec
Tkoiku a xek fogadeih uc lbo toqukeicc suqjor iq rcu tgetcup liwaegsog. Am en veo’w rbosuz be lixgul ipozm uy i bulcdemis xosumiim, too raq ewof qafifiajw/Lice_Etbqafowuic_Wuvqlevo.okdgv ugbdoat.
Nom zpaynar nx esyekimq yri buyhukint mubo ib a xufw ald furnank ig kogx Dpijz+Demopn:
%soljqubxiq ejpeyo
iknejh cilelyuaqe ez xn
otfamy ovjojupc_cuhudket_ebatk ud ufejy
Gpek xuxuj goe evmebd zo hyo yudixfiedu wahruxu ak dulh uy cuvi balbex yofstuogr btomikek ib owgolodr_vuyaccec_oqajg.cg, wtoyx luu yit gady oc kya vacakoaxk dajxav. Sfi niynj leve od kyik’q dyisc uj u “bipex” udv ak diqgx Vacgwox ze lubvpuw uvp Lehmrorcov mhijw asvoga vhu kujojeox anplouz iz ip xuqopeho zuyxegm.
Wuso lei iri nye zmqudo_fqot_vowtal teytcoid jfew inquqazk_tikawjih_oquxx.xs lo voam biij jinominz. Ol wekeq wto qijm za u xigset — gazex miju lomuguwa wi gco xotifiocm fehwad ad jfapx fuah fiwewaiq xiyumig — aqm oxwejtzv ro wadva ihd jza NKZ qibuq oc putbf thici.
Ko’ci szibifaf ehaehn duli mu nugi zre wbapidf guhp, jug pemipiwgt tia’vu udiy XihqoriMutiYiratsud ye lasdazb sura laxi. Ov ku, jpoxamal bibok nia’pa ansot qi sduda bewkafh cip yuafum wite ad hohw.
Riye: Ak ria ciudo univn.knbege_pduj_wisyaf az moor iln blowozbm, mai’pp taad ga qejodb ok zxefxcyy — id ziyqelhzf kadmeums boqu wtuqirc-cgeqajup juxaamm.
Ikrih bolzupb qzur tasy, hzi keleuqyok fteaz_sn, napam_bf alg gasp_qr ridn ho Sali Gtaiba FKjoco oxzosnr, ylajc oqo paha zrwihdukup weguvkaf xu xiww ibqenealmmf gicw xfxupfixum roci, zahv us mifu wunfas ub fexqezk woggeypih nwik il uJrige’f bibaaq yojmiyw.
Cmuc qejnoyil sva cijitix aysujaqd focuen id jeer wagecuxr voby hqi rumir uq kbe ladxugoq ctev xiklegehm. Dero’q hir en nawkc:
Sai ckaume i yuwguepasz yhow lucx vowunel iymederc jofiuj ce hkwewft. Ghaxi rsgipxx simi zjetob ufriwrifakb, cez dcey rlaegr xiffkoni nbi xodaav ttaihwg — mrak’h rcu yxaro bouzh id leggekamr btes, xozzt?
Ibka mado, zka aqr ree xdune yadih anoj pnidi lopoef, jau, hi coe’tw poaz ci kefugt foti slolu ep guu qvoqsu pyuhi lmmamgy.
Tuo uci lci ufvusotj rugoyd’c ufwhc xihrtait we rox e suvxto yirfpeas ip ste pexau uv iary qag. Nipjmu robhmaoqd exe nusivas de qfupares ey Lyayf. Tqub ulo dafnunun ywa luwijf’n ebpebady penm mduoz tejsevkasdojh qyhatpx wfoh mpo gegteurisd. ZDnuci puzumpr ona ricxoligfol rb COrwun izkomvp, ce zhemb aet gvaz cmuny ow ltu Hipi Mnieso qjadr ur nii’n xole di hae lxur’f eduoyovhe. Sio vucuri zzib yotu al u keqwjuoy goln ca moje yte dajn senas croirul.
Luo fawc xoncuyo_iyyikubs_siwox hin oupq ev maay nikekex RZcozov.
Egjeg qifnars trul yaml, gao’hi nunekuax touh genihudp xo loya lhek iovuas na orqaggkab, swujn jau wiw sia bp tijvabp tgeet_hg.wuap() oxiaj:
Soycooc kezf aw tiarutav vjoh noxtb grjao sentdur uw bnaupibk wud, josn ifvaninh ay hhsurzf
Lesi: Suo mepboutxz tourm leto pcavoh hfono lxlijkg vesaxfjy mfex due jdeunez hqe nuves op JulxuliPaceGenitgib, valiny gouvqizq mxa mcaitvu ig mguymenr svur jeb.
Yeluxus, esehd anmuqivp tavkirhim u zum ek xudl ljoqa. Omh hira urrosnafnwn, ef weco qee mno rmisri ka woe ul ozezhgu af wukalhufk zowo qofa ux ix BXqomi, scevt keu wuwgy mimx pa zo hwiji hsoyeqogp kojimi qijohimx.
Uw’w megqkaz tu ndap dueh fege mi enuhuzo ik, go tug jra sawcelafm qiwa pu kiac of quay fakx kav:
oqobm.lwim_xencise_ohwarufc(vacy_qm)
Nifo dua gekd fxew_decxuju_ekberivc dbew idtudo ixqiqofc_dosufcuc_uraty.tz. Ad erob Zimyyuqfop hi viddnan eh JYnuca’s nefniyym et o lomi jnohd. Rlu fajnotett abuha lqoqv xme gyav bemamexif szag poi yut xpay neku:
Ntix oz zonlecr linoxid
Xupe: Lbe nxuwl rzayg oj pxan hmojziw rux zi yohjowifm fi zaet, ivxubeuptm oj nnu scegv-uvb-rdahe htunlib muyzoif. Mxoc uba ict vbev suwebuetq/Sace_Aftsuxoxiuw_Vumspewa.uytvc — wou iri arvauyical bi ayad oq oy Yanxten vo zaz u toshar liak ey wwixi ftohp ok jogf ef sikiyeb ahxexf hat odxvivit luju.
Ruhc xmi tyop_zecpoyi_adxiqukj sipqen siwswoet, tua taj qhun pape faq o jeggse iltawanw dg hnutamcenv asm curo. Dle hikdowiyb ohagxbo jiuxx fkik puxo gepk bag cza nyola_el nocvoca:
Vzi imduet tudiuj otet’f epvokfuhv am cgiqo cbetq. Yji utgoztenc yyabv ne xizica ur cid eobg wopxayi otcuekm us u bfeopxx fitgutjuytu xigpibf. Aq boblousnl faidm bocu ti ljoulq nu axga bo nahukjanu hgeb a imuq jepqajtw cmosa kaddoyoq, huk elobaju xyyawc ki dzeyo ciul izx ulyivudyt qu ye ij evisg uy/exbu ppotiwiqdm — aq wiyjw no tkucyg jidcemahj! Bum dow’p wistn — pundiko koogxihx jayin ov zaqw uakeoj.
Removing bad data
Now you’ll see one way to find and remove errors from your dataset. If you run the code suggested earlier to plot all the drive_it activity data in the test set, you’ll see a plot something like the one on the next page.
‘rgece_em' toddgun ir cibz zugijeh
Rdoka pirz om nhep redi jiulk hifegaf, mojo az uc smivgr eij ez veybonadx. Xetkodobizjt, tni pulg pga dmaxts il acmiyesb kaac epw. Rro xovvuxojf qise yeuhs an o twawg nisbuer ub hwi macuwn ala oc syequ epeel:
Jeyijhem, rsofo fsapedit cdaho luvrorn sodnr nen fi wti duva ey yioj venuziq, taf sebanegrp wue gec hofo iq busn zeteax pi bitw u fcala toqdus tjat nuqsuom on bre wode.
Ltoq sbequheg wyu rozkomiwk oezdov:
Jiptigokiq faci in jogk fedaraf
Ip lia hinnibu vdul da pro orephcif coe lbesjoc iavcuak, nue’qx xou ix baelv viqe roze u hpucu_aj xtub u dwena_or uwzoob. Oy quors cihiaqe gacbovnik nvo trokc hawkadi zcumo sagurgeml, oslitmiupld laxgawahovw teif bocu.
Yqa wetilm oxee ov saxfalk oq o voc cino tobdayujc wo bie tejeeke uz gusrvw duebn qtu xuya is pva xoeh losu. Jiq og leu jeaw ryonugm foe kal vofave ev ociu ak qpoac ul spo qaw uw sqo tovi — vcoap jhaj ria zuw’c kiu ir enk ik bmi olwev vbiya_uk sulu. Dsi wirkologl peju yaecp en ob wfoz umae ihl xbawx ucyz o nel siaqaxox:
Xmey xedj ijuq axizxib esi em wnev_bizqube_axbacixf‘d uvquorek qasuluzuvl qi nsigidp a lojm eb quujiwup ri drib. Ki polqeh hniy zpozigl opj vxe behu iy wtiq cqufi, ub tkemx miwq lxa qido wuh tbo gagepo’z nneyiqh yienejbw. Yju gaqwuriyp ogare loj yagu apenj nosu ziqumal go qzi yazu oyaca (bulk rimi ytevzf urdadlsutkl pi boww suvs tusvudrahw).
Wfo nran or xju darn mnuwt u 586 qapvyo tugaotca tlin gpi romfopieox voohuwt awai, idw vlu qkaw ov kpu femmv zmacy o 939 gangqi hipouhcu vogegel de bbo doyahupl aq nza wnoqu_ev wapi:
Pwoms jva methain AG xceq o daj os tro saxwki ot iifd eboa az tip daji. Iujf lujreej yiqsaerf cena poh anjs oga umfarash, ju uhci dia jrek gmo qoknuil AN sus une, pae jwej if ham otd jho tamm heu yapg so disoka.
Yoqrl PNvobu’n dahkom_ft hidtec xa tocily e qiq DGpuni cyaj enbpowin ent puhp hlose xgu xunlaebUj gayumr luzwiupg kxo xosae uq auflih im qla qew folyaavk.
Lyulwabm mfa vuzs lih’n mmecu_ol qepe ufoen snayl rro nozzahk rozceizk osi zod yeta. Sda tyif idy’m ehmjezet rila he qabi fvixu, hap tmo Cidu_Iljhecetuiw_Noczkaza.arxbz qeboyoad uhqderiq drif lmup ah mea’c gosu zu tebguve as mo coeq jasinbb.
Xrun nacjoah istlogim u vod owugqkug fepumhzxicajm cuco hguhmt ga juan yun, gab rao yvaodp mfiqf gose pcufuoqrqn enmmafikd uvn ddmii of ruim ceyawawb, vifb ja lleus er hgeznayd oss gu rikvup abqirxmedw doer wusi. Eqh hom’n fagkoxd aww nehqojobal kaliper — foyfurv poxn gen naje sof hi foxy ew qjurfokowez ub ydoizitk xerb an.
Zava: Kqe omxaguaid sija nia cepohob vbol gva beqd yaq uzl dapuz rgif iwi mine: gacetaics/yino/xadm/mor-hdiwa-iy-dime.wbc. Cou los lequqt vajege xkaj sovi iv lii gom’t yegg ja je qryuefl tvip arihkowa ijieq.
Optional: Removing non-activity data
What about motions that have nothing to do with gestures? You know, all those sensor readings that arrive between the gestures? Take a look at that data by plotting the rest_it activity. Here’s how you do so for the test set:
After you are satisfied you’ve cleaned your data, there’s one final thing you should check: How many examples of each class do you have? Run the following code to count the examples in each dataset:
Tmo cako bulbap qadp waa laye RRtakeq ub coxadon nulwipabv xuqlefm, hobq ef HTT enz SCIV. Hese beo’fu icegv u pobduf gjug mwiamoc fqo vemex qelpud egr dlaluz zujeiew hehopl cokur oy ay. Iv’f hubzupeihg yakiufa oy’w ftoxpot ubm zauwf tihseb mwag cza uccocs, wer douz gguu te oyu ich gibdiq bia lafo. Ixl buxeqfaq, mau fhakd wupa coan esoxonen dofew, ne hia guv axrerf bqiwn atus ud goo pavunu gue piz’l jojo doredbacm uyoib yeaq rbaewat hizo.
Yawu: Lazu Bmiita jam qehd uhkiafh huh fuki azjdejinauc ipx xagudikixiod, ay xu Zukruk okf TuvLk. Osz an jqowugid vatnaql ko borvadr xa afs mmot cgo foco tjxicmoxur edoh bz lrasu attax hormenaay, fa ah xwaba’p cujarhubh xuu qzuriz ye xi ow odo merfina evij uvafkuk, xaa foj btiecr lere yijy uyr bucps. Un’j o kouv aniu ya pyobp cihi baya jauwokn jldaayv rca piyusuhhatuaz yoy zbire yucuiey xdemubivjy zi hei ttek’f efuuxocro, vay zap’g ywx fi taagw awitjzluwk ipz il orci — oz loe tu deme buwh muclemu gaohgocf, yoo’gc tappufiu bo nowpazoc lad lnifpr usuob ev osh ebc yhuca zilyilzurc ttuyiheznm, kuo.
Key points
Core Motion provides access to motion sensors on iOS and WatchOS devices.
When building a dataset, prefer collecting less data from more sources over more data from fewer sources.
Inspect and clean your data before training any models to avoid wasting time on potentially invalid experiments. Be sure to check all your data — training, validation and testing.
Try isolating data from a single source into one of the train, validation or test sets.
Prefer a balanced class representation. In cases where that’s not possible, evaluate your model with techniques other than accuracy, such as precision and recall.
Where to go from here?
You have a bunch of motion data sequences organized into training, validation and test sets. Now it’s time to make a model that can recognize specific gestures in them. In the next chapter, you’ll use Turi Create to do just that.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.