使用Python实现人工智能_第1页
使用Python实现人工智能_第2页
使用Python实现人工智能_第3页
使用Python实现人工智能_第4页
使用Python实现人工智能_第5页
已阅读5页,还剩33页未读 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Lecture11:UsingPythonforArtificialIntelligence

CS5001/CS5003:

IntensiveFoundationsofComputerScience

PDFofthispresentation

1

Lecture11:UsingPythonforArtificialIntelligence

Today'stopics:IntroductiontoArtificialIntelligence

IntroductiontoArtificialNeuralNetworksExamplesofsomebasicneuralnetworksUsingPythonforArtificialIntelligenceExample:PyTorch

2

Lecture11:IntroductiontoArtificialIntelligence

VideoIntroduction

1950:

AlanTuring

:

TuringTest

1951:FirstAIprogram1965:

Eliza

(firstchatbot)

1974:Firstautonomousvehicle

1997:

DeepBluebeatsGaryKasimov

atChess2004:FirstAutonomousVehiclechallenge2011:

IBMWatsonbeatsJeopardywinners

2016:

DeepMindbeatsGochampion

2017:

AlphaGoZerobeatsDeepMind

3

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

NNslearnrelationshipbetweencauseandeffectororganizelargevolumesofdataintoorderlyandinformativepatterns.

Slidesmodifiedfrom

PPT

byMohammedShbier

4

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

ANeuralNetworkisabiologicallyinspiredinformationprocessingidea,modeledafterourbrain.

Aneuralnetworkisalargenumberofhighlyinterconnectedprocessingelements(neurons)workingtogether

Likepeople,theylearnfromexperience(byexample)

5

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

NeuralnetworkstaketheirinspirationfromneurobiologyThisdiagramisthehumanneuron:

6

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Abiologicalneuronhasthreetypesofmaincomponents;dendrites,soma(orcellbody)andaxonDendritesreceivessignalsfromotherneurons

Thesoma,sumstheincomingsignals.Whensufficientinputisreceived,thecellfires;thatisittransmitasignaloveritsaxontoothercells.

7

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Anartificialneuralnetwork(ANN)isaninformationprocessingsystemthathascertainperformancecharacteristicsincommonwithbiologicalnets.

SeveralkeyfeaturesoftheprocessingelementsofANNaresuggestedbythepropertiesofbiologicalneurons:

Theprocessingelementreceivesmanysignals.

Signalsmaybemodifiedbyaweightatthereceivingsynapse.

Theprocessingelementsumstheweightedinputs.

Underappropriatecircumstances(sufficientinput),theneurontransmitsasingleoutput.

Theoutputfromaparticularneuronmaygotomanyotherneurons.

8

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Fromexperience:examples/trainingdata

Strengthofconnectionbetweentheneuronsisstoredasaweight-valueforthespecificconnection.

Learningthesolutiontoaproblem=changingtheconnectionweights

9

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

ANNshavebeendevelopedasgeneralizationsofmathematicalmodelsofneuralbiology,basedontheassumptionsthat:

Informationprocessingoccursatmanysimpleelementscalledneurons.

Signalsarepassedbetweenneuronsoverconnectionlinks.

Eachconnectionlinkhasanassociatedweight,which,intypicalneuralnet,multipliesthesignaltransmitted.

Eachneuronappliesanactivationfunctiontoitsnetinputtodetermineitsoutputsignal.

10

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

11

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Modelofaneuron

12

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Aneuralnetconsistsofalargenumberofsimpleprocessingelementscalledneurons,units,cellsornodes.

Eachneuronisconnectedtootherneuronsbymeansofdirectedcommunicationlinks,eachwithassociatedweight.

Theweightrepresentinformationbeingusedbythenettosolveaproblem.

Eachneuronhasaninternalstate,calleditsactivationoractivitylevel,whichisafunctionoftheinputsithasreceived.Typically,aneuronsendsitsactivationasasignaltoseveralotherneurons.

Itisimportanttonotethataneuroncansendonlyonesignalatatime,althoughthatsignalisbroadcasttoseveralotherneurons.

13

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Neuralnetworksareconfiguredforaspecificapplication,suchaspatternrecognitionordataclassification,throughalearningprocess

Inabiologicalsystem,learninginvolvesadjustmentstothesynapticconnectionsbetweenneurons

Thisisthesameforartificialneuralnetworks(ANNs)!

14

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Aneuronreceivesinput,determinesthestrengthortheweightoftheinput,calculatesthetotalweightedinput,andcomparesthetotalweightedwithavalue(threshold)Thevalueisintherangeof0and1

Ifthetotalweightedinputgreaterthanorequalthethresholdvalue,theneuronwillproducetheoutput,andifthetotalweightedinputlessthanthethresholdvalue,nooutputwillbeproduced

15

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

16

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

17

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

18

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

19

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Let'smodelaslightlymorecomplicatedneuralnetwork:

Ifwetouchsomethingcoldweperceiveheat

Ifwekeeptouchingsomethingcoldwewillperceivecold

Ifwetouchsomethinghotwewillperceiveheat

WewillassumethatwecanonlychangethingsondiscretetimestepsIfcoldisappliedforonetimestepthenheatwillbeperceived

Ifacoldstimulusisappliedfortwotimestepsthencoldwillbeperceived

Ifheatisappliedatatimestep,thenweshouldperceiveheat

20

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

21

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Ittakestimeforthestimulus(appliedatX1andX2)tomakeitswaytoY1and

Y2whereweperceiveeitherheatorcold

Att(0),weapplyastimulustoX1andX2Att(1)wecanupdateZ1,Z2andY1

Att(2)wecanperceiveastimulusatY2

Att(2+n)thenetworkisfullyfunctional

22

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Wewantthesystemtoperceivecoldifacoldstimulusisappliedfortwotimesteps

Y2(t)=X2(t–2)ANDX2(t–1)

X2(t–2)

X2(t–1)

Y2(t)

1

1

1

1

0

0

0

1

0

0

0

0

23

SlidesmodifiedfromGrahamKendall'sIntroductiontoArtificialIntelligence

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Wewantthesystemtoperceiveheatifeitherahotstimulusisappliedoracoldstimulusisapplied(foronetimestep)andthenremoved

Y1(t)=[X1(t–1)]OR[X2(t–3)ANDNOTX2(t–2)]

X2(t–3)

X2(t–2)

ANDNOT

X1(t–1)

OR

1

1

0

1

1

1

0

1

1

1

0

1

0

1

1

0

0

0

1

1

1

1

0

0

0

1

0

1

0

1

0

1

0

0

0

0

0

0

0

0

24

Lecture11:IntroductiontoArtificialNeuralNetworks(ANNs)

Thenetworkshows

Y1(t)=X1(t–1)ORZ1(t–1)

Z1(t–1)=Z2(t–2)ANDNOTX2(t–2)Z2(t–2)=X2(t–3)

Substituting,weget

Y1(t)=[X1(t–1)]OR[X2(t–3)ANDNOTX2(t–2)]

whichisthesameasouroriginalrequirements

25

Lecture11:UsingPythonforArtificialIntelligence

Thisisgreat...buthowdoyoubuildanetworkthatlearns?Wehavetouseinputtopredictoutput

Wecandothisusingamathematicalalgorithmcalledbackpropogation,whichmeasuresstatisticsfrominputvaluesandoutputvalues.

Backpropogationusesatrainingset

Wearegoingtousethefollowingtrainingset:

Canyoufigureoutwhatthequestionmarkshouldbe?

26

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

Thisisgreat...buthowdoyoubuildanetworkthatlearns?Wehavetouseinputtopredictoutput

Wecandothisusingamathematicalalgorithmcalledbackpropogation,whichmeasuresstatisticsfrominputvaluesandoutputvalues.

Backpropogationusesatrainingset

Wearegoingtousethefollowingtrainingset:

Canyoufigureoutwhatthequestionmarkshouldbe?

Theoutputisalwaysequaltothevalueoftheleftmostinputcolumn.Thereforetheansweristhe

‘?’shouldbe1.

27

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

Westartbygivingeachinputaweight,whichwillbeapositiveornegativenumber.

Largenumbers(positiveornegative)willhavealargeeffectontheneuron'soutput.

Westartbysettingeachweighttoarandomnumber,andthenwetrain:

Taketheinputsfromatrainingsetexample,adjustthembytheweights,andpassthemthroughaspecialformulatocalculatetheneuron’soutput.

Calculatetheerror,whichisthedifferencebetweentheneuron’soutputandthedesiredoutputinthetrainingsetexample.

Dependingonthedirectionoftheerror,adjusttheweightsslightly.

Repeatthisprocess10,000times.

28

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

Eventuallytheweightsoftheneuronwillreachanoptimumforthetrainingset.Ifweallowtheneurontothinkaboutanewsituation,thatfollowsthesamepattern,itshouldmakeagoodprediction.

29

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

Whatisthisspecialformulathatwe'regoingtousetocalculatetheneuron'soutput?

First,wetaketheweightedsumoftheneuron'sinputs:

∑weighti

×inputi

=weight1×input1+weight2×input2+weight3×input3

Nextwenormalizethis,sotheresultisbetween0and1.Forthis,weuseamathematicallyconvenientfunction,calledtheSigmoidfunction:

1 1+e−x

TheSigmoidfunctionlookslikethiswhenplotted:Noticethecharacteristic"S"

shape,andthatitisboundedby1and0.

30

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

WecansubstitutethefirstfunctionintotheSigmoid:

1 1+e−(∑weighti×inputi)

Duringthetraining,wehavetoadjusttheweights.Tocalculatethis,weusetheErrorWeightedDerivativeformula:

error×input×SigmoidCurvedGradient(output)

What'sgoingonwiththisformula?

Wewanttomakeanadjustmentproportionaltothesizeoftheerror

Wemultiplybytheinput,whichiseither1or0

Wemultiplybythe

gradient(steepness)oftheSigmoidcurve

.

31

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

What'sgoingonwiththisformula?

Wewanttomakeanadjustmentproportionaltothesizeoftheerror

Wemultiplybytheinput,whichiseither1or0

Wemultiplybythe

gradient(steepness)oftheSigmoidcurve

.

WhythegradientoftheSigmoid?

WeusedtheSigmoidcurvetocalculatetheoutputoftheneuron.

Iftheoutputisalargepositiveornegativenumber,itsignifiestheneuronwasquiteconfidentonewayoranother.

Fromthediagram,wecanseethatatlargenumbers,theSigmoidcurvehasashallowgradient.

Iftheneuronisconfidentthattheexistingweightiscorrect,itdoesn’twanttoadjustitverymuch.MultiplyingbytheSigmoidcurvegradientachievesthis.

32

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

ThegradientoftheSigmoidcurve,canbefoundbytakingthederivative(remembercalculus?)

SigmoidCurvedGradient(output)=output×(1−output)

Sobysubstitutingthesecondequationintothefirstequation(fromtwoslidesago),thefinalformulaforadjustingtheweightsis:

error×input×output×(1−output)

Thereareother,moreadvancedformulas,butthisoneisprettysimple.

33

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

Finally,Python!

Wewillusethenumpymodule,whichisamathematicslibraryforPython.Wewanttousefourmethods:

exp—thenaturalexponential

array—createsamatrix

dot—multipliesmatrices

random—givesusrandomnumbers

array()createslist-likearraysthatarefasterthanregularlists.E.g.,forthetrainingsetwesawearlier:

1training_set_inputs=array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]])

2training_set_outputs=array([[0,1,1,0]]).T

The‘.T’function,transposesthematrixfromhorizontaltovertical.Sothe

0 0

⎢1 1

1⎤⎡0⎤

1⎥⎢1⎥

computerisstoringthenumberslikethis: 1

0

0 1⎥⎢1⎥

1 1⎦⎣0⎦

34

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

Lecture11:UsingPythonforArtificialIntelligence

In10linesofPythoncode:

fromnumpyimportexp,array,random,dot

training_set_inputs=array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]])

training_set_outputs=array([[0,1,1,0]]).T

random.seed(1)

synaptic_weights=2*random.random((3,1))-1

foriterationinrange(10000):

output=1/(1+exp(-(dot(training_set_inputs,synaptic_weights))))

synaptic_weights+=dot(training_set_inputs.T,(training_set_outputs-output)

*output*(1-output))

print1/(1+exp(-(dot(array([1,0,0]),synaptic_weights))))

35

Exampleborrowedfrom:

Howtobuildasimpleneuralnetworkin9linesofPythoncode

1fromnumpyimportexp,array,random,dot

2

3

4classNeuralNetwork():

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

definit(self):

#Seedtherandomnumbergenerator,soitgeneratesthesamenumbers#everytimetheprogramruns.

random.seed(1)

#Wemodelasingleneuron,with3inputconnectionsand1outputconnection.

#Weassignrandomweightstoa3x1matrix,withvaluesintherange-1to1#andmean0.

self.synaptic_weights=2*random.random((3,1))-1

#TheSigmoidfunction,whichdescribesanSshapedcurve.

#Wepasstheweightedsumoftheinputsthroughthisfunctionto#normalisethembetween0and1.

defsigmoid(self,x):return1/(1+exp(-x))

#ThederivativeoftheSigmoidfunction.

#ThisisthegradientoftheSigmoidcurve.

#Itindicateshowconfidentweareabouttheexistingweight.defsigmoid_derivative(self,x):

returnx*(1-x)

#Wetraintheneuralnetworkthroughaprocessoftrialanderror.#Adjustingthesynapticweightseachtime.

deftrain(self,training_set_inputs,training_set_outputs,number_of_training_iterations):foriterationinrange(number_of_training_iterations):

#Passthetrainingsetthroughourneuralnetwork(asingleneuron).output=self.think(training_set_inputs)

#Calculatetheerror(Thedifferencebetweenthedesiredoutput#andthepredictedoutput).

error=training_set_outputs-output

#MultiplytheerrorbytheinputandagainbythegradientoftheSigmoidcurve.#Thismeanslessconfidentweightsareadjustedmore.

#Thismeansinputs,whicharezero,donotcausechangestotheweights.adjustment=dot(training_set_inputs.T,error*self.sigmoid_derivative(output))

#Adjusttheweights.self.synaptic_weights+=adjustment

#Theneuralnetworkthinks.defthink(self,inputs):

#Passinputsthroughourneuralnetwork(oursingleneuron).returnself.sigmoid(dot(inputs,self.synaptic_weights))

51

52ifname=="main":53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

#Intialiseasingleneuronneuralnetwork.

neural_network=NeuralNetwork()

print("Randomstartingsynapticweights:")

print(neural_network.synaptic_weights)

#Thetrainingset.Wehave4examples,eachconsistingof3inputvalues#and1outputvalue.

training_set_inputs=array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]])

training_set_outputs=array([[0,1,1,0]]).T

#Traintheneuralnetworkusingatrainingset.

#Doit10,000timesa

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论