版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
七
toria1s in
s 尸LY EASY G
www.
tutoriaIs
https://
/tutorialspointindlia
/tutorialspoi,nt
AIwithPython
PAGE\*roman
iii
AbouttheTutorial
Artificialintelligenceistheintelligencedemonstratedbymachines,incontrasttotheintelligencedisplayedbyhumans.
ThistutorialcoversthebasicconceptsofvariousfieldsofartificialintelligencelikeArtificialNeuralNetworks,NaturalLanguageProcessing,MachineLearning,DeepLearning,Geneticalgorithmsetc.,anditsimplementationinPython.
Audience
Thistutorialwillbeusefulforgraduates,postgraduates,andresearchstudentswhoeitherhaveaninterestinthissubjectorhavethissubjectasapartoftheircurriculum.Thereadercanbeabeginneroranadvancedlearner.
Prerequisites
WeassumethatthereaderhasbasicknowledgeaboutArtificialIntelligenceandPythonprogramming.He/sheshouldbeawareaboutbasicterminologiesusedinAIalongwithsomeusefulpythonpackageslikenltk,OpenCV,pandas,OpenAIGym,etc.
Copyright&Disclaimer
©Copyright2016byTutorialsPoint(I)Pvt.Ltd.
Allthecontentandgraphicspublishedinthise-bookarethepropertyofTutorialsPoint(I)Pvt.Ltd.Theuserofthise-bookisprohibitedtoreuse,retain,copy,distributeorrepublishanycontentsorapartofcontentsofthise-bookinanymannerwithoutwrittenconsentofthepublisher.
Westrivetoupdatethecontentsofourwebsiteandtutorialsastimelyandaspreciselyaspossible,however,thecontentsmaycontaininaccuraciesorerrors.TutorialsPoint(I)Pvt.Ltd.providesnoguaranteeregardingtheaccuracy,timelinessorcompletenessofourwebsiteoritscontentsincludingthistutorial.Ifyoudiscoveranyerrorsonourwebsiteorinthistutorial,pleasenotifyusat
contact@
TableofContents
TOC\o"1-2"\h\z\u
AbouttheTutorial i
Audience i
Prerequisites i
Copyright&Disclaimer i
TableofContents ii
AIwithPython–PrimerConcepts 1
BasicConceptofArtificialIntelligence(AI) 1
TheNecessityofLearningAI 1
WhatisIntelligence? 2
WhatisIntelligenceComposedOf? 3
Learning−l 4
What’sInvolvedinAI 6
ApplicationofAI 6
CognitiveModeling:SimulatingHumanThinkingProcedure 7
Agent&Environment 8
AIwithPython–GettingStarted 9
WhyPythonforAI 9
FeaturesofPython 9
InstallingPython 10
SettingupPATH 11
RunningPython 12
ScriptfromtheCommand-line 13
IntegratedDevelopmentEnvironment 13
AIwithPython–MachineLearning 15
TypesofMachineLearning(ML) 15
MostCommonMachineLearningAlgorithms 16
AIwithPython–DataPreparation 20
PreprocessingtheData 20
TechniquesforDataPreprocessing 21
LabelingtheData 23
AIwithPython–SupervisedLearning:Classification 26
StepsforBuildingaClassifierinPython 26
BuildingClassifierinPython 29
LogisticRegression 34
DecisionTreeClassifier 37
RandomForestClassifier 39
Performanceofaclassifier 40
ClassImbalanceProblem 42
EnsembleTechniques 43
AIwithPython–SupervisedLearning:Regression 44
BuildingRegressorsinPython 44
AIwithPython–LogicProgramming 49
HowtoSolveProblemswithLogicProgramming 49
InstallingUsefulPackages 50
ExamplesofLogicProgramming 50
CheckingforPrimeNumbers 51
SolvingPuzzles 52
AIwithPython–UnsupervisedLearning:Clustering 55
WhatisClustering? 55
AlgorithmsforClusteringtheData 55
MeasuringtheClusteringPerformance 61
CalculatingSilhouetteScore 61
FindingNearestNeighbors 63
K-NearestNeighborsClassifier 65
AIwithPython–NaturalLanguageProcessing 69
ComponentsofNLP 69
DifficultiesinNLU 69
NLPTerminology 70
StepsinNLP 70
AIwithPython–NLTKpackage 72
ImportingNLTK 72
DownloadingNLTK’sData 72
InstallingOtherNecessaryPackages 73
ConceptofTokenization,Stemming,andLemmatization 73
Chunking:DividingDataintoChunks 75
Typesofchunking 76
BagofWord(BoW)Model 77
ConceptoftheStatistics 78
BuildingaBagofWordsModelinNLTK 79
SolvingProblems 79
TopicModeling:IdentifyingPatternsinTextData 84
AlgorithmsforTopicModeling 84
AIwithPython–AnalyzingTimeSeriesData 86
Introduction 86
InstallingUsefulPackages 86
Pandas:Handling,SlicingandExtractingStatisticfromTimeSeriesData 87
ExtractingStatisticfromTimeSeriesData 91
AnalyzingSequentialDatabyHiddenMarkovModel(HMM) 95
Example:AnalysisofStockMarketdata 96
AIwithPython–SpeechRecognition 99
BuildingaSpeechRecognizer 99
VisualizingAudioSignals-ReadingfromaFileandWorkingonit 100
CharacterizingtheAudioSignal:TransformingtoFrequencyDomain 102
GeneratingMonotoneAudioSignal 104
FeatureExtractionfromSpeech 106
RecognitionofSpokenWords 108
AIwithPython–HeuristicSearch 111
ConceptofHeuristicSearchinAI 111
DifferencebetweenUninformedandInformedSearch 111
RealWorldProblemSolvedbyConstraintSatisfaction 112
AIwithPython–Gaming 115
SearchAlgorithms 115
CombinationalSearch 115
MinimaxAlgorithm 115
Alpha-BetaPruning 116
NegamaxAlgorithm 116
BuildingBotstoPlayGames 116
ABottoPlayLastCoinStanding 116
ABottoPlayTicTacToe 119
AIwithPython–NeuralNetworks 122
WhatisArtificialNeuralNetworks(ANN) 122
InstallingUsefulPackages 122
BuildingNeuralNetworks 122
PerceptronbasedClassifier 123
Single-LayerNeuralNetworks 124
Multi-LayerNeuralNetworks 127
AIwithPython–ReinforcementLearning 131
BasicsofReinforcementLearning 131
BuildingBlocks:EnvironmentandAgent 131
ConstructinganEnvironmentwithPython 133
ConstructingalearningagentwithPython 134
AIwithPython–GeneticAlgorithms 135
WhatareGeneticAlgorithms? 135
HowtoUseGAforOptimizationProblems? 135
InstallingNecessaryPackages 136
ImplementingSolutionsusingGeneticAlgorithms 136
AIwithPython–ComputerVision 142
ComputerVision 142
ComputerVisionVsImageProcessing 142
InstallingUsefulPackages 143
Reading,WritingandDisplayinganImage 144
ColorSpaceConversion 145
EdgeDetection 147
FaceDetection 148
EyeDetection 149
AIwithPython–DeepLearning 151
MachineLearningv/sDeepLearning 151
ConvolutionalNeuralNetwork(CNN) 151
InstallingUsefulPythonPackages 152
BuildingLinearRegressorusingANN 153
ImageClassifier:AnApplicationofDeepLearning 154
PAGE
1
AIwithPython
AIwithPython–PrimerConcepts
Sincetheinventionofcomputersormachines,theircapabilitytoperformvarioustaskshasexperiencedanexponentialgrowth.Humanshavedevelopedthepowerofcomputersystemsintermsoftheirdiverseworkingdomains,theirincreasingspeed,andreducingsizewithrespecttotime.
AbranchofComputerSciencenamedArtificialIntelligencepursuescreatingthecomputersormachinesasintelligentashumanbeings.
BasicConceptofArtificialIntelligence(AI)
AccordingtothefatherofArtificialIntelligence,JohnMcCarthy,itis“Thescienceandengineeringofmakingintelligentmachines,especiallyintelligentcomputerprograms”.
ArtificialIntelligenceisawayofmakingacomputer,acomputer-controlledrobot,orasoftwarethinkintelligently,inthesimilarmannertheintelligenthumansthink.AIisaccomplishedbystudyinghowhumanbrainthinksandhowhumanslearn,decide,andworkwhiletryingtosolveaproblem,andthenusingtheoutcomesofthisstudyasabasisofdevelopingintelligentsoftwareandsystems.
Whileexploitingthepowerofthecomputersystems,thecuriosityofhuman,leadhimtowonder,“Canamachinethinkandbehavelikehumansdo?”
Thus,thedevelopmentofAIstartedwiththeintentionofcreatingsimilarintelligenceinmachinesthatwefindandregardhighinhumans.
TheNecessityofLearningAI
AsweknowthatAIpursuescreatingthemachinesasintelligentashumanbeings.TherearenumerousreasonsforustostudyAI.Thereasonsareasfollows:
AIcanlearnthroughdata
Inourdailylife,wedealwithhugeamountofdataandhumanbraincannotkeeptrackofsomuchdata.Thatiswhyweneedtoautomatethethings.Fordoingautomation,weneedtostudyAIbecauseitcanlearnfromdataandcandotherepetitivetaskswithaccuracyandwithouttiredness.
AIcanteachitself
Itisverynecessarythatasystemshouldteachitselfbecausethedataitselfkeepschangingandtheknowledgewhichisderivedfromsuchdatamustbeupdatedconstantly.WecanuseAItofulfillthispurposebecauseanAIenabledsystemcanteachitself.
AIcanrespondinrealtime
Artificialintelligencewiththehelpofneuralnetworkscananalyzethedatamoredeeply.Duetothiscapability,AIcanthinkandrespondtothesituationswhicharebasedontheconditionsinrealtime.
AIwithPython
PAGE
2
AIachievesaccuracy
Withthehelpofdeepneuralnetworks,AIcanachievetremendousaccuracy.AIhelpsinthefieldofmedicinetodiagnosediseasessuchascancerfromtheMRIsofpatients.
AIcanorganizedatatogetmostoutofit
Thedataisanintellectualpropertyforthesystemswhichareusingself-learningalgorithms.WeneedAItoindexandorganizethedatainawaythatitalwaysgivesthebestresults.
UnderstandingIntelligence
WithAI,smartsystemscanbebuilt.Weneedtounderstandtheconceptofintelligencesothatourbraincanconstructanotherintelligencesystemlikeitself.
WhatisIntelligence?
Theabilityofasystemtocalculate,reason,perceiverelationshipsandanalogies,learnfromexperience,storeandretrieveinformationfrommemory,solveproblems,comprehendcomplexideas,usenaturallanguagefluently,classify,generalize,andadaptnewsituations.
TypesofIntelligence
AsdescribedbyHowardGardner,anAmericandevelopmentalpsychologist,Intelligencecomesinmultifold:
Intelligence
Description
Example
Linguisticintelligence
Theabilitytospeak,recognize,andusemechanismsofphonology(speechsounds),syntax(grammar),andsemantics(meaning).
Narrators,Orators
Musicalintelligence
Theabilitytocreate,communicatewith,andunderstandmeaningsmadeofsound,understandingofpitch,rhythm.
Musicians,Singers,Composers
Logical-mathematicalintelligence
Theabilitytouseandunderstandrelationshipsintheabsenceofactionorobjects.Itisalsotheabilitytounderstandcomplexandabstractideas.
Mathematicians,Scientists
Spatialintelligence
Theabilitytoperceivevisualorspatialinformation,changeit,andre-createvisualimageswithoutreferencetotheobjects,construct3D
Map readers,Astronauts,Physicists
images,andtomoveandrotatethem.
Bodily-Kinestheticintelligence
Theabilitytousecompleteorpartofthebodytosolveproblemsorfashionproducts,controloverfineandcoarsemotorskills,andmanipulatetheobjects.
Players,Dancers
Intra-personalintelligence
Theabilitytodistinguishamongone’sownfeelings,intentions,andmotivations.
GautamBuddhha
Interpersonalintelligence
Theabilitytorecognizeandmakedistinctionsamongotherpeople’sfeelings,beliefs,andintentions.
MassCommunicators,Interviewers
Youcansayamachineorasystemisartificiallyintelligentwhenitisequippedwithatleastoneorallintelligencesinit.
WhatisIntelligenceComposedOf?
Theintelligenceisintangible.Itiscomposedof−
Reasoning
Learning
ProblemSolving
Perception
LinguisticIntelligence
Letusgothroughallthecomponentsbriefly−
Reasoning
Itisthesetofprocessesthatenableustoprovidebasisforjudgement,makingdecisions,andprediction.Therearebroadlytwotypes−
InductiveReasoning
DeductiveReasoning
Itconductsspecificobservationstomakesbroadgeneralstatements.
Itstartswithageneralstatement and
examines thepossibilitiestoreachaspecific, logicalconclusion.
Evenifallofthepremisesaretrueinastatement,inductivereasoningallowsfortheconclusiontobefalse.
Ifsomethingistrueofaclassofthingsingeneral,itisalsotrueforallmembersofthatclass.
Example−"Nitaisateacher.Nitaisstudious.Therefore,Allteachersarestudious."
Example−"Allwomenofageabove60yearsaregrandmothers.Shaliniis65years.Therefore,Shaliniisagrandmother."
Learning−l
Theabilityoflearningispossessedbyhumans,particularspeciesofanimals,andAI-enabledsystems.Learningiscategorizedasfollows−
AuditoryLearning
Itislearningbylisteningandhearing.Forexample,studentslisteningtorecordedaudiolectures.
EpisodicLearning
Tolearnbyrememberingsequencesofeventsthatonehaswitnessedorexperienced.Thisislinearandorderly.
MotorLearning
Itislearningbyprecisemovementofmuscles.Forexample,pickingobjects,writing,etc.
ObservationalLearning
Tolearnbywatchingandimitatingothers.Forexample,childtriestolearnbymimickingherparent.
PerceptualLearning
Itislearningtorecognizestimulithatonehasseenbefore.Forexample,identifyingandclassifyingobjectsandsituations.
RelationalLearning
Itinvolveslearningtodifferentiateamongvariousstimulionthebasisofrelationalproperties,ratherthanabsoluteproperties.ForExample,Adding‘littleless’saltatthetimeofcookingpotatoesthatcameupsaltylasttime,whencookedwithaddingsayatablespoonofsalt.
SpatialLearning−Itislearningthroughvisualstimulisuchasimages,colors,maps,etc.Forexample,Apersoncancreateroadmapinmindbeforeactuallyfollowingtheroad.
Stimulus-ResponseLearning−Itislearningtoperformaparticularbehaviorwhenacertainstimulusispresent.Forexample,adograisesitsearonhearingdoorbell.
ProblemSolving
Itistheprocessinwhichoneperceivesandtriestoarriveatadesiredsolutionfromapresentsituationbytakingsomepath,whichisblockedbyknownorunknownhurdles.
Problemsolvingalsoincludesdecisionmaking,whichistheprocessofselectingthebestsuitablealternativeoutofmultiplealternativestoreachthedesiredgoal.
Perception
Itistheprocessofacquiring,interpreting,selecting,andorganizingsensoryinformation.
Perceptionpresumessensing.Inhumans,perceptionisaidedbysensoryorgans.InthedomainofAI,perceptionmechanismputsthedataacquiredbythesensorstogetherinameaningfulmanner.
LinguisticIntelligence
Itisone’sabilitytouse,comprehend,speak,andwritetheverbalandwrittenlanguage.Itisimportantininterpersonalcommunication.
What’sInvolvedinAI
Artificialintelligenceisavastareaofstudy.Thisfieldofstudyhelpsinfindingsolutionstorealworldproblems.
LetusnowseethedifferentfieldsofstudywithinAI:
MachineLearning
ItisoneofthemostpopularfieldsofAI.Thebasicconceptofthisfiledistomakethemachinelearningfromdataasthehumanbeingscanlearnfromhis/herexperience.Itcontainslearningmodelsonthebasisofwhichthepredictionscanbemadeonunknowndata.
Logic
Itisanotherimportantfieldofstudyinwhichmathematicallogicisusedtoexecutethecomputerprograms.Itcontainsrulesandfactstoperformpatternmatching,semanticanalysis,etc.
Searching
Thisfieldofstudyisbasicallyusedingameslikechess,tic-tac-toe.Searchalgorithmsgivetheoptimalsolutionaftersearchingthewholesearchspace.
Artificialneuralnetworks
Thisisanetworkofefficientcomputingsystemsthecentralthemeofwhichisborrowedfromtheanalogyofbiologicalneuralnetworks.ANNcanbeusedinrobotics,speechrecognition,speechprocessing,etc.
GeneticAlgorithm
Geneticalgorithmshelpinsolvingproblemswiththeassistanceofmorethanoneprogram.Theresultwouldbebasedonselectingthefittest.
KnowledgeRepresentation
Itisthefieldofstudywiththehelpofwhichwecanrepresentthefactsinawaythemachinethatisunderstandabletothemachine.Themoreefficientlyknowledgeisrepresented;themoresystemwouldbeintelligent.
ApplicationofAI
Inthissection,wewillseethedifferentfieldssupportedbyAI:
Gaming
AIplayscrucialroleinstrategicgamessuchaschess,poker,tic-tac-toe,etc.,wheremachinecanthinkoflargenumberofpossiblepositionsbasedonheuristicknowledge.
NaturalLanguageProcessing
Itispossibletointeractwiththecomputerthatunderstandsnaturallanguagespokenbyhumans.
ExpertSystems
Therearesomeapplicationswhichintegratemachine,software,andspecialinformationtoimpartreasoningandadvising.Theyprovideexplanationandadvicetotheusers.
VisionSystems
Thesesystemsunderstand,interpret,andcomprehendvisualinputonthecomputer.Forexample,
Aspyingaeroplanetakesphotographs,whichareusedtofigureoutspatialinformationormapoftheareas.
Doctorsuseclinicalexpertsystemtodiagnosethepatient.
Policeusecomputersoftwarethatcanrecognizethefaceofcriminalwiththestoredportraitmadebyforensicartist.
SpeechRecognition
Someintelligentsystemsarecapableofhearingandcomprehendingthelanguageintermsofsentencesandtheirmeaningswhileahumantalkstoit.Itcanhandledifferentaccents,slangwords,noiseinthebackground,changeinhuman’snoiseduetocold,etc.
HandwritingRecognition
Thehandwritingrecognitionsoftwarereadsthetextwrittenonpaperbyapenoronscreenbyastylus.Itcanrecognizetheshapesofthelettersandconvertitintoeditabletext.
IntelligentRobots
Robotsareabletoperformthetasksgivenbyahuman.Theyhavesensorstodetectphysicaldatafromtherealworldsuchaslight,heat,temperature,movement,sound,bump,andpressure.Theyhaveefficientprocessors,multiplesensorsandhugememory,toexhibitintelligence.Inaddition,theyarecapableoflearningfromtheirmistakesandtheycanadapttothenewenvironment.
CognitiveModeling:SimulatingHumanThinkingProcedure
Cognitivemodelingisbasicallythefieldofstudywithincomputersciencethatdealswiththestudyandsimulatingthethinkingprocessofhumanbeings.ThemaintaskofAIistomakemachinethinklikehuman.Themostimportantfeatureofhumanthinkingprocessisproblemsolving.Thatiswhymoreorlesscognitivemodelingtriestounderstandhowhumanscansolvetheproblems.AfterthatthismodelcanbeusedforvariousAIapplicationssuchasmachinelearning,robotics,naturallanguageprocessing,etc.Followingisthediagramofdifferentthinkinglevelsofhumanbrain:
Cognitive
Behaviora
Physical
Kinematic
Geometri
Agent&Environment
Inthissection,wewillfocusontheagentandenvironmentandhowthesehelpinArtificialIntelligence.
Agent
Anagentisanythingthatcanperceiveitsenvironmentthroughsensorsandactsuponthatenvironmentthrougheffectors.
Ahumanagenthassensoryorganssuchaseyes,ears,nose,tongueandskinparalleltothesensors,andotherorganssuchashands,legs,mouth,foreffectors.
Aroboticagentreplacescamerasandinfraredrangefindersforthesensors,andvariousmotorsandactuatorsforeffectors.
Asoftwareagenthasencodedbitstringsasitsprogramsandactions.
Environment
Someprogramsoperateinanentirelyartificialenvironmentconfinedtokeyboardinput,database,computerfilesystemsandcharacteroutputonascreen.
Incontrast,somesoftwareagents(softwarerobotsorsoftbots)existinrich,unlimitedsoftbotsdomains.Thesimulatorhasaverydetailed,complexenvironment.Thesoftwareagentneedstochoosefromalongarrayofactionsinrealtime.Asoftbotisdesignedtoscantheonlinepreferencesofthecustomerandshowsinterestingitemstothecustomerworksintherealaswellasanartificialenvironment.
PAGE
9
AIwithPython
AIwithPython–GettingStarted
Inthischapter,wewilllearnhowtogetstartedwithPython.WewillalsounderstandhowPythonhelpsforArtificialIntelligence.
WhyPythonforAI
Artificialintelligenceisconsideredtobethetrendingtechnologyofthefuture.Alreadythereareanumberofapplicationsmadeonit.Duetothis,manycompaniesandresearchersaretakinginterestinit.ButthemainquestionthatariseshereisthatinwhichprogramminglanguagecantheseAIapplicationsbedeveloped?TherearevariousprogramminglanguageslikeLisp,Prolog,C++,JavaandPython,whichcanbeusedfordevelopingapplicationsofAI.Amongthem,Pythonprogramminglanguagegainsahugepopularityandthereasonsareasfollows:
Simplesyntax&lesscoding
PythoninvolvesverylesscodingandsimplesyntaxamongotherprogramminglanguageswhichcanbeusedfordevelopingAIapplications.Duetothisfeature,thetestingcanbeeasierandwecanfocusmoreonprogramming.
InbuiltlibrariesforAIprojects
AmajoradvantageforusingPythonforAIisthatitcomeswithinbuiltlibraries.PythonhaslibrariesforalmostallkindsofAIprojects.Forexample,NumPy,SciPy,matplotlib,nltk,SimpleAIaresometheimportantinbuiltlibrariesofPython.
Opensource:Pythonisanopensourceprogramminglanguage.Thismakesitwidelypopularinthecommunity.
Canbeusedforbroadrangeofprogramming:Pythoncanbeusedforabroadrangeofprogrammingtaskslikesmallshellscripttoenterprisewebapplications.ThisisanotherreasonPythonissuitableforAIprojects.
FeaturesofPython
Pythonisahigh-level,interpreted,interactiveandobject-orientedscriptinglanguage.Pythonisdesignedtobehighlyreadable.ItusesEnglishkeywordsfrequentlywhereasotherlanguagesusepunctuation,andithasfewersyntacticalconstructionsthanotherlanguages.Python'sfeaturesincludethefollowing−
Easy-to-learn−Pythonhasfewkeywords,simplestructure,andaclearlydefinedsyntax.Thisallowsthestudenttopickupthelanguagequickly.
Easy-to-read−Pythoncodeismoreclearlydefinedandvisibletotheeyes.
Easy-to-maintain−Python'ssourcecodeisfairlyeasy-to-maintain.
Abroadstandardlibrary−Python'sbulkofthelibraryisveryportableandcross-platformcompatibleonUNIX,Windows,andMacintosh.
AIwithPython
PAGE
10
InteractiveMode−Pythonhassupportforaninteractivemodewhichallowsinteractivetestinganddebuggingofsnippetsofcode.
Portable−Pythoncanrunonawidevarietyofhardwareplatformsandhasthesameinterfaceonallplatforms.
Extendable−Wecanaddlow-levelmodulestothePythoninterpreter.Thesemodulesenableprogrammerstoaddtoorcustomizetheirtoolstobemoreefficient.
Databases−Pythonprovidesinterfacestoallmajorcommercialdatabases.
GUIProgramming−PythonsupportsGUIapplicationsthatcanbecreatedandportedtomanysystemcalls,librariesandwindowssystems,suchasWindowsMFC,Macintosh,andtheXWindowsystemofUnix.
Scalable−Pythonprovidesabetterstructureandsupportforlargeprogramsthanshellscripting.
ImportantfeaturesofPython
LetusnowconsiderthefollowingimportantfeaturesofPython:
ItsupportsfunctionalandstructuredprogrammingmethodsaswellasOOP.
Itcanbeusedasascriptinglanguageorcanbecompiledtobyte-codeforbuildinglargeapplications.
Itprovidesveryhigh-leveldynamicdatatypesandsupportsdynamictypechecking.
Itsupportsautomaticgarbagecollection.
ItcanbeeasilyintegratedwithC,C++,COM,ActiveX,CORBA,andJava.
InstallingPython
Pythondistributionisavailableforalargenumberofplatforms.YouneedtodownloadonlythebinarycodeapplicableforyourplatformandinstallPython.
Ifthebinarycodeforyourplatformisnotavailable,youneedaCcompilertocompilethesourcecodemanually.Compilingthesourcecodeoffersmoreflexibilityintermsofchoiceoffeaturesthatyourequireinyourinstallation.
HereisaquickoverviewofinstallingPythononvariousplatforms−
UnixandLinuxInstallation
FollowthesestepstoinstallPythononUnix/Linuxmachine.
OpenaWebbrowserandgoto
/downloads/
.
FollowthelinktodownloadzippedsourcecodeavailableforUnix/Linux.
Downloadandextractfiles.
EditingtheModules/Setupfileifyouwanttocustomizesomeoptions.
run./configurescript
make
makeinstall
ThisinstallsPythonatthestandardlocation/usr/local/binanditslibrariesat/usr/local/lib/pythonXXwhereXXistheversionofPython.
WindowsInstallation
FollowthesestepstoinstallPythononWindowsmachine.
OpenaWebbrowserandgoto
/downloads/
.
FollowthelinkfortheWindowsinstallerpython-XYZ.msifilewhereXYZistheversionyouneedtoinstall.
Tousethisinstallerpython-XYZ.msi,theWindowssystemmustsupportMicrosoftInstaller2.0.SavetheinstallerfiletoyourlocalmachineandthenrunittofindoutifyourmachinesupportsMSI.
Runthedownloadedfile.ThisbringsupthePythoninstallwizard,whichisreallyeasytouse.Justacceptthedefaultsettingsandwaituntiltheinstallisfinished.
MacintoshInstallation
IfyouareonMacOSX,itisrecommendedthatyouuseHomebrewtoinstallPython3.ItisagreatpackageinstallerforMacOSXanditisreallyeasytouse.Ifyoudon'thaveHomebrew,youcaninstallitusingthefollowingcommand:
$ruby-e"$(curl-fsSL/Homebrew/install/master/install)"
Wecanupdatethepackagemanagerwiththecommandbelow:
$brewupdate
NowrunthefollowingcommandtoinstallPython3onyoursystem:
$brewinstallpython3
SettingupPATH
Programsandotherexecutablefilescanbeinmanydirectories,sooperatingsystemsprovideasearchpaththatliststhedirectoriesthattheOSsearchesforexecutables.
Thepathisstoredinanenvironmentvariable,whichisanamedstringmaintainedbytheoperatingsystem.Thisvariablecontainsinformationavailabletothecommandshellandotherprograms.
ThepathvariableisnamedasPATHinUnixorPathinWindows(Unixiscase-sensitive;Windowsisnot).
InMacOS,theinstallerhandlesthepathdetails.ToinvokethePythoninterpreterfromanyparticulardirectory,youmustaddthePythondirectorytoyourpath.
SettingPathatUnix/Linux
ToaddthePythondirectorytothepathforaparticularsessioninUnix−
Inthecshshell−typesetenvPATH"$PATH:/usr/local/bin/python"andpressEnter.
In the bash shell (Linux)− type exportATH="$PATH:/usr/local/bin/python"andpressEnter.
Intheshor
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 岁儿童常见心理问题
- 工程建设招标与投标
- 《投入产出核算》课件
- 工程结构设计原理混凝土柱承载力
- 应用小组合作构建高效课堂
- 2025-2026学年北师大正负数说课稿
- 2025-2026学年关于风景的说课稿题目
- 2027年劳动合同解除协议范本(离职手续适用附带补偿标准)
- 淘宝商家入驻合同范本
- 住房回收合同范本
- 小学语文新部编版六年级上册全册教案(2026秋新版)
- 满70岁以上换领驾照三力测试题及答案
- 2026年国家公务员考试(国考)行测+申论真题及标准答案(完整版)
- 八年级上册道德与法治第二单元《维护社会秩序》整体教学设计
- 2026年蜜雪冰城加盟考试题及答案
- 产品外观标准检验指导书
- 智联猎头:2026年企业薪酬调研报告
- 场景美术创作技法
- 10KV高压电缆敷设专项施工方案
- 2025年军事理论与国防教育考试题及答案
- 公司门房日常管理制度
评论
0/150
提交评论