SlideShare a Scribd company logo
1 of 39
Download to read offline
Python for Data Science
                            PyCon Finland 17.10.2011
                                Harri Hämäläinen
                             harri.hamalainen aalto fi
                                     #sgwwx




Wednesday, October 19, 11
What is Data Science
                    • Data science ~ computer science +
                            mathematics/statistics + visualization
                    • Most web companies are actually doing
                            some kind of Data Science:
                            -   Facebook, Amazon, Google, LinkedIn, Last.fm...

                            -   Social network analysis, recommendations,
                                community building, decision making, analyzing
                                emerging trends, ...


Wednesday, October 19, 11
Scope of the talk
                    • What is in this presentation
                            -   Pythonized tools for retrieving and dealing with
                                data

                            -   Methods, libraries, ethics

                    • What is not included
                            -   Dealing with very large data

                            -   Math or detailed algorithms behind library calls



Wednesday, October 19, 11
Outline

                    •       Harvesting

                    •       Cleaning

                    •
                    •
                            Analyzing
                            Visualizing
                                               Data
                    •       Publishing



Wednesday, October 19, 11
Data harvesting



Wednesday, October 19, 11
Authorative borders
                             for data sources
                    1. Data from your system
                            -   e.g. user access log files, purchase history, view
                                counts

                            -   e.g. sensor readings, manual gathering

                    2. Data from the services of others
                            -   e.g. view counts, tweets, housing prizes, sport
                                results, financing data



Wednesday, October 19, 11
Data sources

                    • Locally available data
                    • Data dumps from Web
                    • Data through Web APIs
                    • Structured data in Web documents

Wednesday, October 19, 11
API

                    • Available for many web applications
                            accessible with general Python libraries
                            -   urllib, soaplib, suds, ...

                    • Some APIs available even as application
                            specific Python libraries
                            -   python-twitter, python-linkedin, pyfacebook, ...



Wednesday, October 19, 11
Data sources

                    • Locally available data
                    • Data dumps in Web
                    • Data through Web APIs
                    • Structured data in Web documents

Wednesday, October 19, 11
Crawling

                    • Crawlers (spiders, web robots) are used to
                            autonomously navigate the Web documents

                               import urllib
                               # queue holds urls, managed by some other component
                               def crawler(queue):
                                   url = queue.get()
                                   fd = urllib.urlopen(url)
                                   content = fd.read()
                                   links = parse_links(content)
                                   # process content
                                   for link in links:
                                       queue.put(link)




Wednesday, October 19, 11
Web Scraping
                    •       Extract information from structured documents in
                            Web
                    •       Multiple libraries for parsing XML documents
                    •       But in general web documents are rarely valid XML
                    •       Some candidates who will stand by you when data
                            contains “dragons”
                            -   BeautifulSoup

                            -   lxml



Wednesday, October 19, 11
urllib & BeautifulSoup
                            >>> import urllib, BeautifulSoup
                            >>> fd = urllib.urlopen('http://mobile.example.org/
                            foo.html')
                            >>> soup = BeautifulSoup.BeautifulSoup(fd.read())
                            >>> print soup.prettify()
                            ...
                            <table>
                                <tr><td>23</td></tr>
                                <tr><td>24</td></tr>
                                <tr><td>25</td></tr>
                                <tr><td>22</td></tr>
                                <tr><td>23</td></tr>
                            </table>
                            ...




                 >>> values = [elem.text for elem in soup.find('table').findChildren('td')]
                 >>>> values
                 [u'23', u'24', u'25', u'22', u'23']




Wednesday, October 19, 11
Scrapy
                    •       A framework for crawling web sites and extracting
                            structured data
                    •       Features
                            -   extracts elements from XML/HTML (with XPath)

                            -   makes it easy to define crawlers with support more specific
                                needs (e.g. HTTP compression headers, robots.txt, crawling
                                depth)

                            -   real-time debugging

                    •       http://scrapy.org


Wednesday, October 19, 11
Tips and ethics
                    •       Use the mobile version of the sites if available
                    •       No cookies
                    •       Respect robots.txt
                    •       Identify yourself
                    •       Use compression (RFC 2616)
                    •       If possible, download bulk data first, process it later
                    •       Prefer dumps over APIs, APIs over scraping
                    •       Be polite and request permission to gather the data
                    •       Worth checking: https://scraperwiki.com/

Wednesday, October 19, 11
Data cleansing
                             (preprocessing)




Wednesday, October 19, 11
Data cleansing
                    • Harvested data may come with lots of
                            noise
                    • ... or interesting anomalies?
                    • Detection
                            -   Scatter plots

                            -   Statistical functions describing distribution



Wednesday, October 19, 11
Data preprocessing

                    • Goal: provide structured presentation for
                            analysis
                            -   Network (graph)

                            -   Values with dimension




Wednesday, October 19, 11
Network representation

                    • Vast number of datasets are describing a
                            network
                            -   Social relations

                            -   Plain old web pages with links

                            -   Anything where some entities in data are related to
                                each other




Wednesday, October 19, 11
Analyzing the Data



Wednesday, October 19, 11
•       Offers efficient          • Builds on top of NumPy
                            multidimensional array
                            object, ndarray          • Modules for
                                                       • statistics, optimization,
                    •       Basic linear algebra             signal processing, ...
                            operations and data
                            types                    • Add-ons (called SciKits)
                                                       for

                    •       Requires GNU Fortran       •     machine learning

                                                       •     data mining

                                                       •     ...



Wednesday, October 19, 11
>>> pylab.scatter(weights, heights)
           >>> xlabel("weight (kg)")
                                                 Curve fitting with numpy polyfit &
           >>> ylabel("height (cm)")
                                                 polyval functions
           >>> pearsonr(weights, heights)
           (0.5028, 0.0)




Wednesday, October 19, 11
NumPy + SciPy +
                            Matplotlib + IPython
                      • Provides Matlab ”-ish” environment
                      • ipython provides extended interactive
                            interpreter (tab completion, magic
                            functions for object querying, debugging, ...)


                            ipython --pylab
                            In [1]: x = linspace(1, 10, 42)
                            In [2]: y = randn(42)
                            In [3]: plot(x, y, 'r--.', markersize=15)




Wednesday, October 19, 11
Analyzing networks


                    • Basicly two bigger alternatives
                            -   NetworkX

                            -   igraph




Wednesday, October 19, 11
NetworkX
                    • Python package for dealing with complex
                            networks:
                            -   Importers / exporters

                            -   Graph generators

                            -   Serialization

                            -   Algorithms

                            -   Visualization



Wednesday, October 19, 11
NetworkX
                            >>> import networkx
                            >>> g = networkx.Graph()
                            >>> data = {'Turku':     [('Helsinki', 165), ('Tampere', 157)],
                                        'Helsinki': [('Kotka', 133), ('Kajaani', 557)],
                                        'Tampere':   [('Jyväskylä', 149)],
                                        'Jyväskylä': [('Kajaani', 307)] }
                            >>> for k,v in data.items():
                            ...     for dest, dist in v:
                            ...         g.add_edge(k, dest, weight=dist)
                            >>> networkx.astar_path_length(g, 'Turku', 'Kajaani')
                            613
                            >>> networkx.astar_path(g, 'Kajaani', 'Turku')
                            ['Kajaani', 'Jyväskylä', 'Tampere', 'Turku']




Wednesday, October 19, 11
Visualizing Data



Wednesday, October 19, 11
NetworkX
                            >>> import networkx
                            >>> g = networkx.Graph()
                            >>> data = {'Turku':     [('Helsinki', 165), ('Tampere', 157)],
                                        'Helsinki': [('Kotka', 133), ('Kajaani', 557)],
                                        'Tampere':   [('Jyväskylä', 149)],
                                        'Jyväskylä': [('Kajaani', 307)] }
                            >>> for k,v in data.items():
                            ...     for dest, dist in v:
                            ...         g.add_edge(k, dest, weight=dist)
                            >>> networkx.astar_path_length(g, 'Turku', 'Kajaani')
                            613
                            >>> networkx.astar_path(g, 'Kajaani', 'Turku')
                            ['Kajaani', 'Jyväskylä', 'Tampere', 'Turku']
                            >>> networkx.draw(g)




Wednesday, October 19, 11
PyGraphviz

                    • Python interface for the Graphviz layout
                            engine
                            -   Graphviz is a collection of graph layout programs




Wednesday, October 19, 11
>>> pylab.scatter(weights, heights)
           >>> xlabel("weight (kg)")
           >>> ylabel("height (cm)")
           >>> pearsonr(weights, heights)
           (0.5028, 0.0)
           >>> title("Scatter plot for weight/height
           statisticsnn=25000, pearsoncor=0.5028")
           >>> savefig("figure.png")




Wednesday, October 19, 11
3D visualizations


                                           with mplot3d toolkit




Wednesday, October 19, 11
Data publishing



Wednesday, October 19, 11
Open Data
                    •       Certain data should be open and therefore available to everyone
                            to use in a way or another
                    •       Some open their data to others hoping it will be beneficial for
                            them or just because there’s no need to hide it
                    •       Examples of open dataset types
                            -   Government data

                            -   Life sciences data

                            -   Culture data

                            -   Commerce data

                            -   Social media data

                            -   Cross-domain data




Wednesday, October 19, 11
The Zen of Open Data
                                                Open is better than closed.
                                            Transparent is better than opaque.
                                               Simple is better than complex.
                                          Accessible is better than inaccessible.
                                              Sharing is better than hoarding.
                                            Linked is more useful than isolated.
                                         Fine grained is preferable to aggregated.

                            Optimize for machine readability — they can translate for humans.
                                                              ...
                            “Flawed, but out there” is a million times better than “perfect, but
                                                      unattainable”.
                                                              ...


                                                  Chris McDowall & co.


Wednesday, October 19, 11
Sharing the Data
                    • Some convenient formats
                            -   JSON (import simplejson)

                            -   XML (import xml)

                            -   RDF (import rdflib, SPARQLWrapper)

                            -   GraphML (import networkx)

                            -   CSV (import csv)



Wednesday, October 19, 11
Resource Description Framework
                             (RDF)
                    • Collection of W3C standards for modeling
                            complex relations and to exchange
                            information
                    • Allows data from multiple sources to
                            combine nicely
                    • RDF describes data with triples
                            -   each triple has form subject - predicate - object e.g.
                                PyconFi2011 is organized in Turku


Wednesday, October 19, 11
RDF Data

     @prefix poi:           <http://schema.onki.fi/poi#> .
     @prefix skos:          <http://www.w3.org/2004/02/skos/core#> .

     ...

     <http://purl.org/finnonto/id/rky/p437>
         a       poi:AreaOfInterest ;
         poi:description """Turun rautatieasema on maailmansotien välisen ajan merkittävimpiä asemarakennushankkeita Suomessa..."""@fi ;
         poi:hasPolygon "60.454833421,22.253543828 60.453846032,22.254787430 60.453815665,22.254725349..." ;
         poi:history """Turkuun suunniteltiin rautatietä 1860-luvulta lähtien, mutta ensimmäinen rautatieyhteys Turkuun..."""@fi ;
         poi:municipality kunnat:k853 ;
         poi:poiType poio:tuotantorakennus , poio:asuinrakennus , poio:puisto ;
         poi:webPage "http://www.rky.fi/read/asp/r_kohde_det.aspx?KOHDE_ID=1865" ;
         skos:prefLabel "Turun rautatieympäristöt"@fi .

     ...




Wednesday, October 19, 11
from SPARQLWrapper import SPARQLWrapper, JSON
    QUERY = """
       Prefix lgd:<http://linkedgeodata.org/>
       Prefix lgdo:<http://linkedgeodata.org/ontology/>
       Prefix rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>

          Select distinct ?label ?g From <http://linkedgeodata.org> {
             ?s rdf:type <http://linkedgeodata.org/ontology/Library> .
             ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label.
             ?s geo:geometry ?g .
             Filter(bif:st_intersects (?g, bif:st_point (24.9375, 60.170833), 1)) .
          }"""

    sparql = SPARQLWrapper("http://linkedgeodata.org/sparql")
    sparql.setQuery(QUERY)
    sparql.setReturnFormat(JSON)
    results = sparql.query().convert()['results']['bindings']
    for result in results:
        print result['label']['value'].encode('utf-8'), result['g']['value']

                                        German library POINT(24.9495 60.1657)
        Query for libraries in          Metsätalo POINT(24.9497 60.1729)
                                        Opiskelijakirjasto POINT(24.9489 60.1715)
       Helsinki located within          Topelia POINT(24.9493 60.1713)
       1 kilometer radius from          Eduskunnan kirjasto POINT(24.9316 60.1725)
            the city centre             Rikhardinkadun kirjasto POINT(24.9467 60.1662)
                                        Helsinki 10 POINT(24.9386 60.1713)


Wednesday, October 19, 11
RDF Data sources
                    •       CKAN

                    •       DBpedia

                    •       LinkedGeoData

                    •       DBTune

                    •       http://semantic.hri.fi/




Wednesday, October 19, 11
harri.hamalainen aalto fi
Wednesday, October 19, 11

More Related Content

What's hot

Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesAndrew Ferlitsch
 
Machine Learning Using Python
Machine Learning Using PythonMachine Learning Using Python
Machine Learning Using PythonSavitaHanchinal
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Linear regression
Linear regressionLinear regression
Linear regressionMartinHogg9
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Edureka!
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessingankur bhalla
 
Python for Data Science | Python Data Science Tutorial | Data Science Certifi...
Python for Data Science | Python Data Science Tutorial | Data Science Certifi...Python for Data Science | Python Data Science Tutorial | Data Science Certifi...
Python for Data Science | Python Data Science Tutorial | Data Science Certifi...Edureka!
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science Venkata Reddy Konasani
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data AnalysisAndrew Henshaw
 
2.3 bayesian classification
2.3 bayesian classification2.3 bayesian classification
2.3 bayesian classificationKrish_ver2
 
Machine Learning Course | Edureka
Machine Learning Course | EdurekaMachine Learning Course | Edureka
Machine Learning Course | EdurekaEdureka!
 
Introduction of Data Science
Introduction of Data ScienceIntroduction of Data Science
Introduction of Data ScienceJason Geng
 
Introduction to Data Science.pptx
Introduction to Data Science.pptxIntroduction to Data Science.pptx
Introduction to Data Science.pptxVrishit Saraswat
 
Lecture1 introduction to big data
Lecture1 introduction to big dataLecture1 introduction to big data
Lecture1 introduction to big datahktripathy
 

What's hot (20)

Data Preprocessing
Data PreprocessingData Preprocessing
Data Preprocessing
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
Python pandas Library
Python pandas LibraryPython pandas Library
Python pandas Library
 
Machine Learning Using Python
Machine Learning Using PythonMachine Learning Using Python
Machine Learning Using Python
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Linear regression
Linear regressionLinear regression
Linear regression
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 
Python for Data Science | Python Data Science Tutorial | Data Science Certifi...
Python for Data Science | Python Data Science Tutorial | Data Science Certifi...Python for Data Science | Python Data Science Tutorial | Data Science Certifi...
Python for Data Science | Python Data Science Tutorial | Data Science Certifi...
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science Machine Learning Deep Learning AI and Data Science
Machine Learning Deep Learning AI and Data Science
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data Analysis
 
2.3 bayesian classification
2.3 bayesian classification2.3 bayesian classification
2.3 bayesian classification
 
Machine Learning Course | Edureka
Machine Learning Course | EdurekaMachine Learning Course | Edureka
Machine Learning Course | Edureka
 
Introduction of Data Science
Introduction of Data ScienceIntroduction of Data Science
Introduction of Data Science
 
Introduction to Data Science.pptx
Introduction to Data Science.pptxIntroduction to Data Science.pptx
Introduction to Data Science.pptx
 
Lecture1 introduction to big data
Lecture1 introduction to big dataLecture1 introduction to big data
Lecture1 introduction to big data
 
Introduction to data science
Introduction to data scienceIntroduction to data science
Introduction to data science
 

Similar to Python for Data Science

Spotify: Playing for millions, tuning for more
Spotify: Playing for millions, tuning for moreSpotify: Playing for millions, tuning for more
Spotify: Playing for millions, tuning for moreNick Barkas
 
Web search engines and search technology
Web search engines and search technologyWeb search engines and search technology
Web search engines and search technologyStefanos Anastasiadis
 
Building A Scalable Open Source Storage Solution
Building A Scalable Open Source Storage SolutionBuilding A Scalable Open Source Storage Solution
Building A Scalable Open Source Storage SolutionPhil Cryer
 
Search all the things
Search all the thingsSearch all the things
Search all the thingscyberswat
 
Sharing information with MediaWiki
Sharing information with MediaWikiSharing information with MediaWiki
Sharing information with MediaWikiGeert Van Pamel
 
Scraping talk public
Scraping talk publicScraping talk public
Scraping talk publicNesta
 
Gaelyk - SpringOne2GX - 2010 - Guillaume Laforge
Gaelyk - SpringOne2GX - 2010 - Guillaume LaforgeGaelyk - SpringOne2GX - 2010 - Guillaume Laforge
Gaelyk - SpringOne2GX - 2010 - Guillaume LaforgeGuillaume Laforge
 
An Open Platform DM Solution for New Account Intake
An Open Platform DM Solution for New Account IntakeAn Open Platform DM Solution for New Account Intake
An Open Platform DM Solution for New Account IntakeAlfresco Software
 
The original vision of Nutch, 14 years later: Building an open source search ...
The original vision of Nutch, 14 years later: Building an open source search ...The original vision of Nutch, 14 years later: Building an open source search ...
The original vision of Nutch, 14 years later: Building an open source search ...Sylvain Zimmer
 
Introduction to Apache Lucene/Solr
Introduction to Apache Lucene/SolrIntroduction to Apache Lucene/Solr
Introduction to Apache Lucene/SolrRahul Jain
 
Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...
Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...
Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...benaam
 
Semantic Search overview at SSSW 2012
Semantic Search overview at SSSW 2012Semantic Search overview at SSSW 2012
Semantic Search overview at SSSW 2012Peter Mika
 
LTR Handout
LTR HandoutLTR Handout
LTR Handoutkoegeljm
 
Nuxeo World Session: Migrating to Nuxeo
Nuxeo World Session: Migrating to NuxeoNuxeo World Session: Migrating to Nuxeo
Nuxeo World Session: Migrating to NuxeoNuxeo
 
Instrumentation with Splunk
Instrumentation with SplunkInstrumentation with Splunk
Instrumentation with SplunkDatavail
 
Big Data Analysis : Deciphering the haystack
Big Data Analysis : Deciphering the haystack Big Data Analysis : Deciphering the haystack
Big Data Analysis : Deciphering the haystack Srinath Perera
 
Workshop: Big Data Visualization for Security
Workshop: Big Data Visualization for SecurityWorkshop: Big Data Visualization for Security
Workshop: Big Data Visualization for SecurityRaffael Marty
 
Optiq: A dynamic data management framework
Optiq: A dynamic data management frameworkOptiq: A dynamic data management framework
Optiq: A dynamic data management frameworkJulian Hyde
 

Similar to Python for Data Science (20)

Spotify: Playing for millions, tuning for more
Spotify: Playing for millions, tuning for moreSpotify: Playing for millions, tuning for more
Spotify: Playing for millions, tuning for more
 
Web search engines and search technology
Web search engines and search technologyWeb search engines and search technology
Web search engines and search technology
 
Building A Scalable Open Source Storage Solution
Building A Scalable Open Source Storage SolutionBuilding A Scalable Open Source Storage Solution
Building A Scalable Open Source Storage Solution
 
Search all the things
Search all the thingsSearch all the things
Search all the things
 
Sharing information with MediaWiki
Sharing information with MediaWikiSharing information with MediaWiki
Sharing information with MediaWiki
 
Scraping talk public
Scraping talk publicScraping talk public
Scraping talk public
 
Gaelyk - SpringOne2GX - 2010 - Guillaume Laforge
Gaelyk - SpringOne2GX - 2010 - Guillaume LaforgeGaelyk - SpringOne2GX - 2010 - Guillaume Laforge
Gaelyk - SpringOne2GX - 2010 - Guillaume Laforge
 
An Open Platform DM Solution for New Account Intake
An Open Platform DM Solution for New Account IntakeAn Open Platform DM Solution for New Account Intake
An Open Platform DM Solution for New Account Intake
 
The original vision of Nutch, 14 years later: Building an open source search ...
The original vision of Nutch, 14 years later: Building an open source search ...The original vision of Nutch, 14 years later: Building an open source search ...
The original vision of Nutch, 14 years later: Building an open source search ...
 
Google Dorks
Google DorksGoogle Dorks
Google Dorks
 
Introduction to Apache Lucene/Solr
Introduction to Apache Lucene/SolrIntroduction to Apache Lucene/Solr
Introduction to Apache Lucene/Solr
 
Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...
Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...
Early Lessons from Building Sensor.Network: An Open Data Exchange for the Web...
 
Semantic Search overview at SSSW 2012
Semantic Search overview at SSSW 2012Semantic Search overview at SSSW 2012
Semantic Search overview at SSSW 2012
 
Webofdata
WebofdataWebofdata
Webofdata
 
LTR Handout
LTR HandoutLTR Handout
LTR Handout
 
Nuxeo World Session: Migrating to Nuxeo
Nuxeo World Session: Migrating to NuxeoNuxeo World Session: Migrating to Nuxeo
Nuxeo World Session: Migrating to Nuxeo
 
Instrumentation with Splunk
Instrumentation with SplunkInstrumentation with Splunk
Instrumentation with Splunk
 
Big Data Analysis : Deciphering the haystack
Big Data Analysis : Deciphering the haystack Big Data Analysis : Deciphering the haystack
Big Data Analysis : Deciphering the haystack
 
Workshop: Big Data Visualization for Security
Workshop: Big Data Visualization for SecurityWorkshop: Big Data Visualization for Security
Workshop: Big Data Visualization for Security
 
Optiq: A dynamic data management framework
Optiq: A dynamic data management frameworkOptiq: A dynamic data management framework
Optiq: A dynamic data management framework
 

Recently uploaded

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Recently uploaded (20)

Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Python for Data Science

  • 1. Python for Data Science PyCon Finland 17.10.2011 Harri Hämäläinen harri.hamalainen aalto fi #sgwwx Wednesday, October 19, 11
  • 2. What is Data Science • Data science ~ computer science + mathematics/statistics + visualization • Most web companies are actually doing some kind of Data Science: - Facebook, Amazon, Google, LinkedIn, Last.fm... - Social network analysis, recommendations, community building, decision making, analyzing emerging trends, ... Wednesday, October 19, 11
  • 3. Scope of the talk • What is in this presentation - Pythonized tools for retrieving and dealing with data - Methods, libraries, ethics • What is not included - Dealing with very large data - Math or detailed algorithms behind library calls Wednesday, October 19, 11
  • 4. Outline • Harvesting • Cleaning • • Analyzing Visualizing Data • Publishing Wednesday, October 19, 11
  • 6. Authorative borders for data sources 1. Data from your system - e.g. user access log files, purchase history, view counts - e.g. sensor readings, manual gathering 2. Data from the services of others - e.g. view counts, tweets, housing prizes, sport results, financing data Wednesday, October 19, 11
  • 7. Data sources • Locally available data • Data dumps from Web • Data through Web APIs • Structured data in Web documents Wednesday, October 19, 11
  • 8. API • Available for many web applications accessible with general Python libraries - urllib, soaplib, suds, ... • Some APIs available even as application specific Python libraries - python-twitter, python-linkedin, pyfacebook, ... Wednesday, October 19, 11
  • 9. Data sources • Locally available data • Data dumps in Web • Data through Web APIs • Structured data in Web documents Wednesday, October 19, 11
  • 10. Crawling • Crawlers (spiders, web robots) are used to autonomously navigate the Web documents import urllib # queue holds urls, managed by some other component def crawler(queue): url = queue.get() fd = urllib.urlopen(url) content = fd.read() links = parse_links(content) # process content for link in links: queue.put(link) Wednesday, October 19, 11
  • 11. Web Scraping • Extract information from structured documents in Web • Multiple libraries for parsing XML documents • But in general web documents are rarely valid XML • Some candidates who will stand by you when data contains “dragons” - BeautifulSoup - lxml Wednesday, October 19, 11
  • 12. urllib & BeautifulSoup >>> import urllib, BeautifulSoup >>> fd = urllib.urlopen('http://mobile.example.org/ foo.html') >>> soup = BeautifulSoup.BeautifulSoup(fd.read()) >>> print soup.prettify() ... <table> <tr><td>23</td></tr> <tr><td>24</td></tr> <tr><td>25</td></tr> <tr><td>22</td></tr> <tr><td>23</td></tr> </table> ... >>> values = [elem.text for elem in soup.find('table').findChildren('td')] >>>> values [u'23', u'24', u'25', u'22', u'23'] Wednesday, October 19, 11
  • 13. Scrapy • A framework for crawling web sites and extracting structured data • Features - extracts elements from XML/HTML (with XPath) - makes it easy to define crawlers with support more specific needs (e.g. HTTP compression headers, robots.txt, crawling depth) - real-time debugging • http://scrapy.org Wednesday, October 19, 11
  • 14. Tips and ethics • Use the mobile version of the sites if available • No cookies • Respect robots.txt • Identify yourself • Use compression (RFC 2616) • If possible, download bulk data first, process it later • Prefer dumps over APIs, APIs over scraping • Be polite and request permission to gather the data • Worth checking: https://scraperwiki.com/ Wednesday, October 19, 11
  • 15. Data cleansing (preprocessing) Wednesday, October 19, 11
  • 16. Data cleansing • Harvested data may come with lots of noise • ... or interesting anomalies? • Detection - Scatter plots - Statistical functions describing distribution Wednesday, October 19, 11
  • 17. Data preprocessing • Goal: provide structured presentation for analysis - Network (graph) - Values with dimension Wednesday, October 19, 11
  • 18. Network representation • Vast number of datasets are describing a network - Social relations - Plain old web pages with links - Anything where some entities in data are related to each other Wednesday, October 19, 11
  • 20. Offers efficient • Builds on top of NumPy multidimensional array object, ndarray • Modules for • statistics, optimization, • Basic linear algebra signal processing, ... operations and data types • Add-ons (called SciKits) for • Requires GNU Fortran • machine learning • data mining • ... Wednesday, October 19, 11
  • 21. >>> pylab.scatter(weights, heights) >>> xlabel("weight (kg)") Curve fitting with numpy polyfit & >>> ylabel("height (cm)") polyval functions >>> pearsonr(weights, heights) (0.5028, 0.0) Wednesday, October 19, 11
  • 22. NumPy + SciPy + Matplotlib + IPython • Provides Matlab ”-ish” environment • ipython provides extended interactive interpreter (tab completion, magic functions for object querying, debugging, ...) ipython --pylab In [1]: x = linspace(1, 10, 42) In [2]: y = randn(42) In [3]: plot(x, y, 'r--.', markersize=15) Wednesday, October 19, 11
  • 23. Analyzing networks • Basicly two bigger alternatives - NetworkX - igraph Wednesday, October 19, 11
  • 24. NetworkX • Python package for dealing with complex networks: - Importers / exporters - Graph generators - Serialization - Algorithms - Visualization Wednesday, October 19, 11
  • 25. NetworkX >>> import networkx >>> g = networkx.Graph() >>> data = {'Turku': [('Helsinki', 165), ('Tampere', 157)], 'Helsinki': [('Kotka', 133), ('Kajaani', 557)], 'Tampere': [('Jyväskylä', 149)], 'Jyväskylä': [('Kajaani', 307)] } >>> for k,v in data.items(): ... for dest, dist in v: ... g.add_edge(k, dest, weight=dist) >>> networkx.astar_path_length(g, 'Turku', 'Kajaani') 613 >>> networkx.astar_path(g, 'Kajaani', 'Turku') ['Kajaani', 'Jyväskylä', 'Tampere', 'Turku'] Wednesday, October 19, 11
  • 27. NetworkX >>> import networkx >>> g = networkx.Graph() >>> data = {'Turku': [('Helsinki', 165), ('Tampere', 157)], 'Helsinki': [('Kotka', 133), ('Kajaani', 557)], 'Tampere': [('Jyväskylä', 149)], 'Jyväskylä': [('Kajaani', 307)] } >>> for k,v in data.items(): ... for dest, dist in v: ... g.add_edge(k, dest, weight=dist) >>> networkx.astar_path_length(g, 'Turku', 'Kajaani') 613 >>> networkx.astar_path(g, 'Kajaani', 'Turku') ['Kajaani', 'Jyväskylä', 'Tampere', 'Turku'] >>> networkx.draw(g) Wednesday, October 19, 11
  • 28. PyGraphviz • Python interface for the Graphviz layout engine - Graphviz is a collection of graph layout programs Wednesday, October 19, 11
  • 29. >>> pylab.scatter(weights, heights) >>> xlabel("weight (kg)") >>> ylabel("height (cm)") >>> pearsonr(weights, heights) (0.5028, 0.0) >>> title("Scatter plot for weight/height statisticsnn=25000, pearsoncor=0.5028") >>> savefig("figure.png") Wednesday, October 19, 11
  • 30. 3D visualizations with mplot3d toolkit Wednesday, October 19, 11
  • 32. Open Data • Certain data should be open and therefore available to everyone to use in a way or another • Some open their data to others hoping it will be beneficial for them or just because there’s no need to hide it • Examples of open dataset types - Government data - Life sciences data - Culture data - Commerce data - Social media data - Cross-domain data Wednesday, October 19, 11
  • 33. The Zen of Open Data Open is better than closed. Transparent is better than opaque. Simple is better than complex. Accessible is better than inaccessible. Sharing is better than hoarding. Linked is more useful than isolated. Fine grained is preferable to aggregated. Optimize for machine readability — they can translate for humans. ... “Flawed, but out there” is a million times better than “perfect, but unattainable”. ... Chris McDowall & co. Wednesday, October 19, 11
  • 34. Sharing the Data • Some convenient formats - JSON (import simplejson) - XML (import xml) - RDF (import rdflib, SPARQLWrapper) - GraphML (import networkx) - CSV (import csv) Wednesday, October 19, 11
  • 35. Resource Description Framework (RDF) • Collection of W3C standards for modeling complex relations and to exchange information • Allows data from multiple sources to combine nicely • RDF describes data with triples - each triple has form subject - predicate - object e.g. PyconFi2011 is organized in Turku Wednesday, October 19, 11
  • 36. RDF Data @prefix poi: <http://schema.onki.fi/poi#> . @prefix skos: <http://www.w3.org/2004/02/skos/core#> . ... <http://purl.org/finnonto/id/rky/p437> a poi:AreaOfInterest ; poi:description """Turun rautatieasema on maailmansotien välisen ajan merkittävimpiä asemarakennushankkeita Suomessa..."""@fi ; poi:hasPolygon "60.454833421,22.253543828 60.453846032,22.254787430 60.453815665,22.254725349..." ; poi:history """Turkuun suunniteltiin rautatietä 1860-luvulta lähtien, mutta ensimmäinen rautatieyhteys Turkuun..."""@fi ; poi:municipality kunnat:k853 ; poi:poiType poio:tuotantorakennus , poio:asuinrakennus , poio:puisto ; poi:webPage "http://www.rky.fi/read/asp/r_kohde_det.aspx?KOHDE_ID=1865" ; skos:prefLabel "Turun rautatieympäristöt"@fi . ... Wednesday, October 19, 11
  • 37. from SPARQLWrapper import SPARQLWrapper, JSON QUERY = """ Prefix lgd:<http://linkedgeodata.org/> Prefix lgdo:<http://linkedgeodata.org/ontology/> Prefix rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> Select distinct ?label ?g From <http://linkedgeodata.org> { ?s rdf:type <http://linkedgeodata.org/ontology/Library> . ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. ?s geo:geometry ?g . Filter(bif:st_intersects (?g, bif:st_point (24.9375, 60.170833), 1)) . }""" sparql = SPARQLWrapper("http://linkedgeodata.org/sparql") sparql.setQuery(QUERY) sparql.setReturnFormat(JSON) results = sparql.query().convert()['results']['bindings'] for result in results: print result['label']['value'].encode('utf-8'), result['g']['value'] German library POINT(24.9495 60.1657) Query for libraries in Metsätalo POINT(24.9497 60.1729) Opiskelijakirjasto POINT(24.9489 60.1715) Helsinki located within Topelia POINT(24.9493 60.1713) 1 kilometer radius from Eduskunnan kirjasto POINT(24.9316 60.1725) the city centre Rikhardinkadun kirjasto POINT(24.9467 60.1662) Helsinki 10 POINT(24.9386 60.1713) Wednesday, October 19, 11
  • 38. RDF Data sources • CKAN • DBpedia • LinkedGeoData • DBTune • http://semantic.hri.fi/ Wednesday, October 19, 11