markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
RETOObtener:- destino- hora de llegada- duración del vuelo- duración de la escala. *Tip: el último segmento no tendrá esta información*- número del vuelo- modelo del avión | # Destino
segmento.find_element_by_xpath('.//div[@class="arrival"]/span[@class="ground-point-name"]').text
# Hora de llegada
segmento.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
# Duración del vuelo
segmento.find_element_by_xpath('.//span[@class="duration flight-schedule-duration"]/... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
CLASEUna vez que hayamos obtenido toda la información, debemos cerrar el modal/pop-up. | driver.find_element_by_xpath('//div[@class="modal-dialog"]//button[@class="close"]').click() | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Por último debemos obtener la información de las tarifas. Para eso, debemos clickear sobre el vuelo (sobre cualquier parte) | vuelo.click() | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
La información de los precios para cada tarifa está contenida en una tabla. Los precios en sí están en el footer y podemos sacar los nombres de la clase de cada elemento | tarifas = vuelo.find_elements_by_xpath('.//div[@class="fares-table-container"]//tfoot//td[contains(@class, "fare-")]')
precios = []
for tarifa in tarifas:
nombre = tarifa.find_element_by_xpath('.//label').get_attribute('for')
moneda = tarifa.find_element_by_xpath('.//span[@class="price"]/span[@class="currency-s... | {'LIGHT': {'moneda': 'US$', 'valor': '1282,40'}}
{'PLUS': {'moneda': 'US$', 'valor': '1335,90'}}
{'TOP': {'moneda': 'US$', 'valor': '1773,50'}}
| MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Será de gran utilidad armar funciones que resuelvan la extracción de información de cada sección de la página. Por eso te propongo que armes 3 funciones de las cuales te dejo las estructuras: RETOArmar funciones para obtener los datos de las escalas y las tarifas. Te dejo los prototipos: | def obtener_precios(vuelo):
tarifas = vuelo.find_elements_by_xpath(
'.//div[@class="fares-table-container"]//tfoot//td[contains(@class, "fare-")]')
precios = []
for tarifa in tarifas:
nombre = tarifa.find_element_by_xpath('.//label').get_attribute('for')
moneda = tarifa.find_element_... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C4. Scrapeando escalas y tarifas - Script.ipynb | Alejandro-sin/Learning_Notebooks |
In this chapter, we study how to work with PDF and Microsoft Word files using Python. PDF and Word documents are binary files, which makes them much more complex than plaintext files. In addition to text, they store lots of font, color, and layout information. If you want your programs to read or write to PDFs or Word ... | !pip install PyPDF2 | Collecting PyPDF2
Downloading PyPDF2-1.26.0.tar.gz (77 kB)
Building wheels for collected packages: PyPDF2
Building wheel for PyPDF2 (setup.py): started
Building wheel for PyPDF2 (setup.py): finished with status 'done'
Created wheel for PyPDF2: filename=PyPDF2-1.26.0-py3-none-any.whl size=61087 sha256=21f0c54caa... | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
PDF stands for 'Portable Document Format' and uses the .pdf file extension. Although PDFs support many features, this chapter will focus on the two things you’ll be doing most often with them: reading text content from PDFs and crafting new PDFs from existing documents.PDFs are actually very hard to work with in Python... | import PyPDF2
import os
path='C:\\Users\\pgao\\Documents\\PGZ Documents\\Programming Workshop\PYTHON\\Python Books\\Automate the Boring Stuff with Python\\Datasets and Files'
os.chdir(path)
pdfFileObj = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print(type(pdfReader))
print('Number of... | <class 'PyPDF2.pdf.PdfFileReader'>
Number of the pages for the current PDF file: 19
| MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
As you see from the example above, text extractions aren't always perfect: The text Charles E. "Chas" Roemer, President from the PDF is absent from the string returned by extractText(), and the spacing is sometimes off. Still, this approximation of the PDF text content may be good enough for your program in many cases.... | pdfReader = PyPDF2.PdfFileReader(open('encrypted.pdf', 'rb'))
print(pdfReader.isEncrypted)
try:
pdfReader.getPage(0)
except:
print("PdfReadError: file has not been decrypted")
pdfReader.decrypt('rosebud') # the password is rosebud
pageObj = pdfReader.getPage(0)
print(pageObj) | {'/CropBox': [0, 0, 612, 792], '/Parent': IndirectObject(4, 0), '/Type': '/Page', '/Contents': [IndirectObject(946, 0), IndirectObject(947, 0), IndirectObject(948, 0), IndirectObject(949, 0), IndirectObject(950, 0), IndirectObject(951, 0), IndirectObject(952, 0), IndirectObject(953, 0)], '/Resources': {'/ExtGState': {'... | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
Notice that in the original package, there is a bug. If you use the original package, you may encounter an error. The error is the following: after decrypting the 'PdfFileReader' object, calling pdfReader.getPage(0) raises an error with the message: 'IndexError: list index out of range'. The reason is because th... | from IPython.display import Image
Image("ch13_snapshot_1.jpg", width=900, height=800) | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
The counterpart in the package to 'PdfFileReader' objects is 'PdfFileWriter' objects, which can create new PDF files. But 'PyPDF2' cannot write arbitrary text to a PDF like Python can do with plaintext files. Instead, the PDF-writing capabilities are limited to copying pages from other PDFs, rotating pages, overlaying ... | pdf1File = open('meetingminutes.pdf', 'rb')
pdf2File = open('meetingminutes2.pdf', 'rb')
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
pdfWriter = PyPDF2.PdfFileWriter() # creating a blank PDF document here
for pageNum in range(pdf1Reader.numPages): # copy all the pages from t... | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
One cautionary note: 'PyPDF2' cannot insert pages in the middle of a 'PdfFileWriter' object. The addPage() method will only add pages to the end. Also keep in mind that the 'File' object passed to PyPDF2.PdfFileReader() needs to be opened in read-binary mode by passing 'rb' as the second argument to open(). Likewise, t... | minutesFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(minutesFile)
page = pdfReader.getPage(0)
page.rotateClockwise(90)
pdfWriter = PyPDF2.PdfFileWriter() # creating a blank PDF output file
pdfWriter.addPage(page) # adding the rotated page
resultPdfFile = open('rotatedPage.pdf', 'wb')
pdfWrit... | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
Now let's study overlaying pages. 'PyPDF2' can overlay the contents of one page over another, which is useful for adding a logo, timestamp, or watermark to a page. With Python, it’s easy to add watermarks to multiple files and only to pages your program specifies.Here in the example below, we make a 'PdfFileReader' obj... | minutesFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(minutesFile)
minutesFirstPage = pdfReader.getPage(0)
pdfWatermarkReader = PyPDF2.PdfFileReader(open('watermark.pdf', 'rb'))
minutesFirstPage.mergePage(pdfWatermarkReader.getPage(0))
pdfWriter = PyPDF2.PdfFileWriter()
pdfWriter.addPage(minut... | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
Lastly, a 'PdfFileWriter' object can also add encryption to a PDF document. Below is an example. The key is to use the encrypy() method. In general, PDFs can have a user password (allowing you to view the PDF) and an owner password (allowing you to set permissions for printing, commenting, extracting text, and other fe... | pdfFile = open('meetingminutes.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfWriter.encrypt('swordfish') # encrypting with a password
resultPdf = open('encryptedminutes.pdf', 'wb') ... | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
We now study how to manipulate Microsoft Word documents. This is achieved through the "Python-Docx" package, which needs to be installed first. The full documentation for this package is available at https://python-docx.readthedocs.org/. | !pip install python-docx | Requirement already satisfied: python-docx in c:\programdata\anaconda3\lib\site-packages
Requirement already satisfied: lxml>=2.3.2 in c:\programdata\anaconda3\lib\site-packages (from python-docx)
| MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
Although there is a version of Word for OS X, this chapter will focus on Word for Windows. Compared to plaintext, ".docx" files have a lot of structure. This structure is represented by three different data types in 'Python-Docx'. At the highest level, a 'Document' object represents the entire document. The 'Document' ... | from IPython.display import Image
Image("ch13_snapshot_2.jpg") | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
You can think of each run as a block of strings that has its own special properties. This is because the text in a (Microsoft) Word document is more than just a string. It has font, size, color, and other styling information associated with it. A 'style' in Word is a collection of these attributes. A 'Run' object is a ... | import docx
doc = docx.Document('demo.docx')
print('Number of paragraph objects: ', len(doc.paragraphs))
ob1=doc.paragraphs[0].text
print(type(ob1)) # string
print(ob1)
ob2=doc.paragraphs[1].text
print(type(ob2)) # string
print(ob2)
ob3=doc.paragraphs[1].runs
print(type(ob3)) # list
print(ob3)
print(doc.paragraphs[1].r... | A plain paragraph with
some
bold
and some
italic
| MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
If you care only about the text, not the styling information, in the Word document, you can use the user-defined getText() function. It accepts a filename of a '.docx' file and returns a single string value of its text: | def getText(filename):
doc = docx.Document(filename)
fullText = []
for paragraph in doc.paragraphs:
fullText.append(paragraph.text)
return '\n'.join(fullText) | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
The getText() function opens the Word document, loops over all the 'Paragraph' objects in the paragraphs list, and then appends their text to the list in the 'fullText' list (originally set to be empty). After the loop, the strings in 'fullText' are joined together with newline characters. | print(getText('demo.docx')) | Document Title
A plain paragraph with some bold and some italic
Heading, level 1
Intense quote
first item in unordered list
first item in ordered list
| MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
Microsoft Word and other word processors use styles to keep the visual presentation of similar types of text consistent and easy to change. For example, perhaps you want to set body paragraphs in 11-point, Times New Roman, left-justified, ragged-right text. You can create a style with these settings and assign it to al... | from IPython.display import Image
Image("ch13_snapshot_3.jpg") | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
For example, to change the styles of demo.docx, The following commands will help us get the styles for the document and change styles based on different 'Paragraph' objects and 'Run' objects. Here in the example below, we use the text and style attributes to easily see what’s in the paragraphs in our document. We can s... | doc = docx.Document('demo.docx')
print('doc: ', doc.paragraphs[0].text) # 'Document Title'
print('The style of the paragraph: ', doc.paragraphs[0].style) # 'Title'
tupleobject=(doc.paragraphs[1].runs[0].text, doc.paragraphs[1].runs[1].text, doc.paragraphs[1].runs[2].text, doc.paragraphs[1].runs[3].text)
print(tupleobj... | Title
Body Text
| MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
Now let's study how to write Word document using Python. To do, the most important methods include docx.Document(), which is to return a new, blank Word 'Document' object. In addition, the add_paragraph() document method adds a new paragraph of text to the document and returns a reference to the 'Paragraph' object that... | doc = docx.Document()
doc.add_paragraph('Hello world!', 'Title') # adding a title
paraObj1 = doc.add_paragraph('This is a second paragraph.')
paraObj2 = doc.add_paragraph('This is a yet another paragraph.')
paraObj1.add_run(' This text is being added to the second paragraph.')
doc.add_heading('Header 0', 0)
doc.add_hea... | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
To add a line break (rather than starting a whole new paragraph), you can call the add_break() method on the 'Run' object you want to have the break appear after. To create page break, you can use the 'docx.enum.text.WD_BREAK.PAGE' argument in the add_break() method. For details can be found here: https://stackover... | doc = docx.Document()
doc.add_paragraph('This is on the first page!')
doc.paragraphs[0].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE) # adding a page break
doc.add_paragraph('This is on the second page!')
doc.add_picture("ch13_snapshot_3.jpg", width=docx.shared.Inches(1), height=docx.shared.Cm(4)) # width 1 inch and ... | _____no_output_____ | MIT | Automate the Boring Stuff with Python Ch13.ipynb | pgaods/Automate-the-Boring-Stuff-with-Python |
Overview:In order to deal with accessing and storing the mounds of data associated with the matrix project, I have written a script called matrix_manager. The main workhorse of this script is custom class called 'Database' that uses the 'shelve' package (https://docs.python.org/3.4/library/shelve.html). There is also ... | import matrix_manager as mm
import shelve
%matplotlib notebook | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Code to create matrix database One can create an instance of the Databse object by giving it the path to where the database file are or will be stored. Since the database is being made for the first, all it's attributes are set to either None, '' or [ ]. | imp.reload(mm)
db_path = '/net/levsha/share/sameer/U54/matrix_shared/sameer/metadata/U54_matrix_info'
db = mm.Database(db_path)
print(db.metadata, db.keys, db.analysis_path, db.cooler_paths, db.dot_paths) | None []
| MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Now I will create the database for the matrix project. For this I will need to feed the Database object 4 things:1) A list of paths the point to where the coolers are located.2) The path to the base directory where all the analysis will be stored3) A list of paths for the dot calls4) A DataFrame that contains the metad... | cooler_paths = ['/net/levsha/share/lab/U54/2019_mapping_hg38/U54_deep/cooler_library_group/',
'/net/levsha/share/lab/U54/2019_mapping_hg38/U54_matrix/cooler_library/']
analysis_path = '/net/levsha/share/sameer/U54/hic_matrix/'
dot_paths = ['/net/levsha/share/lab/U54/2019_mapping_hg38/U54_matrix/snaked... | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Once we create the dataset, we see that most of the attributes of the object as now filled. Note: If you try to use the create_dataset method once you have already created the shelve object, it will raise an error. | db.create_dataset(metadata, cooler_paths, analysis_path, dot_paths)
display(db.metadata)
print(db.keys, db.analysis_path, db.cooler_paths, db.dot_paths) | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Accessing and modifying an already existing databaseNow that we've created the database, you can access it by initializing the object with the right database_path. | imp.reload(mm)
db = mm.Database(db_path)
display(db.metadata)
# I can also alternative access the metadata using the get_tables() method.
display(db.get_tables()) | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Adding to databaseFor each feature of Hi-C (pileups for example), I like to create various metrics that quantify that feature (dot enrichment score for example) and store these away permanently. I can do this by using the add_table method. The add table method takes in a DataFrame. However this data __must__ have a co... | df = db.get_tables()
df = df[['lib_name']].copy()
df.loc[:, 'dummy'] = 1
df
db.add_table('dummy', df) | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Now even if I reinitialize the object, it will retreive the 'dummy' table in addition to the metadata | db = mm.Database(db_path)
print(db.keys)
db.get_tables('dummy') # I can give this function a any list of keys that I know the database contains.
# It will append these tables to the metadata table and return it | ['dummy']
| MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Modifying the databaseModifying an existing table is done using the modify_table() method. | df['dummy'] = np.nan
db.modify_table('dummy', df)
db.get_tables('dummy') | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Removing from the databaseRemoving an existing table is done using the remove_table() method. | db.remove_table('dummy')
db.keys | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Accessing coolers from the databaseI've created this database to allow easy access to the various data files associated with the matrix project. I've created methods for retrieving coolers, scalings, eigenvectors, pileups and insulation tracks. Here I will show you how to access cooler files. Storing the cooler object... | table = db.get_tables()
table = db.get_coolers(table, res=100000)
table | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
You may be wondering why I chose to feed in the metadata table to to get_coolers() method, we the database object already has access to the metadata. The reason for this is that I can now chain several get_coolers() methods together as shown below. I use this methodology regularly for analysis that requires multiple... | table = db.get_tables()
table = db.get_coolers(table, res=100000)
display(table.head())
table = db.get_coolers(table, res=1000)
display(table.head()) | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
I've tried to make the code as flexible as possible but there are some bottlenecks. For example, P(s) curves are expected to be stored in hdf5 formats because it allows me to store P(s) as well as average trans interactions in the same location. Similiarly, similarly eigenvectors and eigenvalues are stored together in ... | mm.filter_data(table, filter_dict={'celltype':['ESC','HFF'],'xlink':'DSG'}) | _____no_output_____ | MIT | sameer/database_construction_(README).ipynb | dekkerlab/matrix_shared |
Self join Edinburgh Buses[Details of the database](https://sqlzoo.net/wiki/Edinburgh_Buses.) Looking at the data```stops(id, name)route(num, company, pos, stop)``` | library(tidyverse)
library(DBI)
library(getPass)
drv <- switch(Sys.info()['sysname'],
Windows="PostgreSQL Unicode(x64)",
Darwin="/usr/local/lib/psqlodbcw.so",
Linux="PostgreSQL")
con <- dbConnect(
odbc::odbc(),
driver = drv,
Server = "localhost",
Database = "sqlzoo",
UID... | -- [1mAttaching packages[22m --------------------------------------- tidyverse 1.3.0 --
[32mv[39m [34mggplot2[39m 3.3.0 [32mv[39m [34mpurrr [39m 0.3.4
[32mv[39m [34mtibble [39m 3.0.1 [32mv[39m [34mdplyr [39m 0.8.5
[32mv[39m [34mtidyr [39m 1.0.2 [32mv[39m [34mstringr[39m 1.4.0
... | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
1.How many **stops** are in the database. | stops <- dbReadTable(con, 'stops')
route <- dbReadTable(con, 'route')
stops %>% tally | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
2.Find the **id** value for the stop 'Craiglockhart' | stops %>%
filter(name=='Craiglockhart') %>%
select(id) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
3.Give the **id** and the **name** for the **stops** on the '4' 'LRT' service. | stops %>%
inner_join(route, by=c(id="stop")) %>%
filter(num=='4' & company=='LRT') %>%
select(id, name) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
4. Routes and stopsThe query shown gives the number of routes that visit either London Road (149) or Craiglockhart (53). Run the query and notice the two services that link these stops have a count of 2. Add a HAVING clause to restrict the output to these two routes. | route %>%
filter(stop==149 | stop==53) %>%
group_by(company, num) %>%
summarise(n_route=n()) %>%
filter(n_route==2) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
5.Execute the self join shown and observe that b.stop gives all the places you can get to from Craiglockhart, without changing routes. Change the query so that it shows the services from Craiglockhart to London Road. | route %>%
inner_join(route, by=c(company="company", num="num")) %>%
filter(stop.x==53 & stop.y==149) %>%
select(company, num, stop.x, stop.y) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
6.The query shown is similar to the previous one, however by joining two copies of the **stops** table we can refer to **stops** by **name** rather than by number. Change the query so that the services between 'Craiglockhart' and 'London Road' are shown. If you are tired of these places try 'Fairmilehead' against 'Tol... | route %>%
inner_join(stops, by=c(stop="id")) %>%
inner_join(route %>%
inner_join(stops, by=c(stop="id")),
by=c(company="company", num="num")
) %>%
filter(name.x=='Craiglockhart' &
name.y=='London Road') %>%
select(company, num, name.x, name.y) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
7. [Using a self join](https://sqlzoo.net/wiki/Using_a_self_join)Give a list of all the services which connect stops 115 and 137 ('Haymarket' and 'Leith') | route %>%
inner_join(route, by=c(company="company", num="num")) %>%
filter(stop.x==115 & stop.y==137) %>%
distinct(company, num) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
8.Give a list of the services which connect the stops 'Craiglockhart' and 'Tollcross' | route %>%
inner_join(stops, by=c(stop="id")) %>%
inner_join(route %>%
inner_join(stops, by=c(stop="id")),
by=c(company="company", num="num")
) %>%
filter(name.x=='Craiglockhart' &
name.y=='Tollcross') %>%
distinct(company, num) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
9.Give a distinct list of the **stops** which may be reached from 'Craiglockhart' by taking one bus, including 'Craiglockhart' itself, offered by the LRT company. Include the company and bus no. of the relevant services. | route %>%
inner_join(stops, by=c(stop="id")) %>%
inner_join(route %>%
inner_join(stops, by=c(stop="id")),
by=c(company="company", num="num")
) %>%
filter(name.x=='Craiglockhart' &
company=='LRT') %>%
distinct(name.y, company, num) | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
10.Find the routes involving two buses that can go from **Craiglockhart** to **Lochend**.Show the bus no. and company for the first bus, the name of the stop for the transfer,and the bus no. and company for the second bus.> _Hint_ > Self-join twice to find buses that visit Craiglockhart and Lochend, then join those... | bus1 <- route %>%
inner_join(stops, by=c(stop="id")) %>%
inner_join(route %>%
inner_join(stops, by=c(stop="id")),
by=c(company="company", num="num")
) %>%
filter(name.x=='Craiglockhart')
bus2 <- route %>%
inner_join(stops, by=c(stop="id")) %>%
inner_join... | _____no_output_____ | MIT | R/09 Self join.ipynb | madlogos/sqlzoo |
Tarea 4Con base a los métodos vistos en clase resuelva las siguientes dos preguntas (A) Integrales* $\int_{0}^{1}x^{-1/2}\,\text{d}x$* $\int_{0}^{\infty}e^{-x}\ln{x}\,\text{d}x$* $\int_{0}^{\infty}\frac{\sin{x}}{x}\,\text{d}x$ | def f(x):
return x**(-0.5)
n=1000000
def Integrando1(f):
x,y = np.linspace(0,1, num = n +1, retstep = True)
return (5/4)*y*f(x[0] + f(x[-1])) + y*np.sum(f(x[1:-1]))
Integrando1(f)
def f(x):
return math.exp(-x)
def trapecio2(f, n, a, b):
h = (b - a) / float(n)
integrando = 0.5 * h * (f(a) +... | Integrando 3 1.5622244668962069
| MIT | soluciones/ce.rueda12/tarea4/solucion.ipynb | SamuelCanas/FISI2028-202120 |
(B) FourierCalcule la transformada rápida de Fourier para la función de la **Tarea 3 (D)** en el intervalo $[0,4]$ ($k$ máximo $2\pi n/L$ para $n=25$). Ajuste la transformada de Fourier para los datos de la **Tarea 3** usando el método de regresión exacto de la **Tarea 3 (C)** y compare con el anterior resultado. Para... | df = pd.read_pickle(r"C:\Users\Camilo Rueda\Downloads\ex1.gz")
sns.scatterplot(x='x',y='y',data=df)
plt.show()
df
x = df["x"]
y = df["y"]
lx = []
ly = []
for i in range(len(x)):
if x[i]<=1.5 :
lx.append(x[i])
ly.append(y[i])
x = np.array(lx)
y = np.array(ly)
def f(p,x):
ret... | _____no_output_____ | MIT | soluciones/ce.rueda12/tarea4/solucion.ipynb | SamuelCanas/FISI2028-202120 |
Cyber Literacy in the World of CyberinfrastructureHere you will learn about Cyber Literacy for GIScience. | # This code cell starts the necessary setup for Hour of CI lesson notebooks.
# First, it enables users to hide and unhide code by producing a 'Toggle raw code' button below.
# Second, it imports the hourofci package, which is necessary for lessons and interactive Jupyter Widgets.
# Third, it helps hide/control other as... | _____no_output_____ | BSD-3-Clause | gateway-lesson/gateway/gateway-6.ipynb | mohsen-gis/test2 |
ReminderContinue with the lessonBy continuing with this lesson you are granting your permission to take part in this research study for the Hour of Cyberinfrastructure: Developing Cyber Literacy for GIScience project. In this study, you will be learning about cyberinfrastructure and related concepts using a web-based ... | # Multiple choice question using a ToggleButton widget
# This code cell has tags "Init", "Hide", and "5A"
import sys
sys.path.append('../../supplementary') # relative path (may change depending on the location of the lesson notebook)
import hourofci
widget1=widgets.ToggleButtons(
options=['Yes, absolutely!','No'],
... | _____no_output_____ | BSD-3-Clause | gateway-lesson/gateway/gateway-6.ipynb | mohsen-gis/test2 |
NopeNo! You do *not* need to be an expert in parallel programming to be cyber literate. Just like basic literacy, you can have a basic understanding of parallel programming and rely on other experts or tools to make use of the technology to advance your own research. Let's check inFind all of the core areas of cyber ... | # Multiple choice question using a ToggleButton widget
# This code cell has tags "Init", "Hide", and "5A"
widget2=widgets.SelectMultiple(
options=['Interdisciplinary communication',
'The Internet',
'Parallel Computing',
'Geospatial Data',
'A Shark with a Laser',
'Computational Thinking',
'C... | _____no_output_____ | BSD-3-Clause | gateway-lesson/gateway/gateway-6.ipynb | mohsen-gis/test2 |
Core knowledge areas and your next stepWhat core knowledge area are you most excited about? | widget3=widgets.RadioButtons(
options=['Interdisciplinary communication',
'Parallel Computing',
'Geospatial Data',
'Computational Thinking',
'Cyberinfrastructure',
'Spatial Modeling and Analytics',
'Spatial Thinking',
'Big Data'],
description='',
disabled=False
)
# Show the opt... | _____no_output_____ | BSD-3-Clause | gateway-lesson/gateway/gateway-6.ipynb | mohsen-gis/test2 |
Demo: Probabilistic neural network training for denoising of synthetic 2D dataThis notebook demonstrates training a probabilistic CARE model for a 2D denoising task, using provided synthetic training data. Note that training a neural network for actual use should be done on more (representative) data and with more tr... | from __future__ import print_function, unicode_literals, absolute_import, division
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
from tifffile import imread
from csbdeep.utils import download_and_extract_zip_file, axes_dict, plot_some, plot_history... | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
The TensorFlow backend uses all available GPU memory by default, hence it can be useful to limit it: | # limit_gpu_memory(fraction=1/2) | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
Training dataDownload and read provided training data, use 10% as validation data. | download_and_extract_zip_file (
url = 'http://csbdeep.bioimagecomputing.com/example_data/synthetic_disks.zip',
targetdir = 'data',
)
(X,Y), (X_val,Y_val), axes = load_training_data('data/synthetic_disks/data.npz', validation_split=0.1, verbose=True)
c = axes_dict(axes)['C']
n_channel_in, n_channel_out = ... | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
CARE modelBefore we construct the actual CARE model, we have to define its configuration via a `Config` object, which includes * parameters of the underlying neural network,* the learning rate,* the number of parameter updates per epoch,* the loss function, and* whether the model is probabilistic or not.The defaults s... | config = Config(axes, n_channel_in, n_channel_out, probabilistic=True, train_steps_per_epoch=30)
print(config)
vars(config) | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
We now create a CARE model with the chosen configuration: | model = CARE(config, 'my_model', basedir='models') | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
TrainingTraining the model will likely take some time. We recommend to monitor the progress with [TensorBoard](https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard) (example below), which allows you to inspect the losses during training.Furthermore, you can look at the predictions for some of the val... | history = model.train(X,Y, validation_data=(X_val,Y_val)) | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
Plot final training history (available in TensorBoard during training): | print(sorted(list(history.history.keys())))
plt.figure(figsize=(16,5))
plot_history(history,['loss','val_loss'],['mse','val_mse','mae','val_mae']); | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
EvaluationExample results for validation images. | plt.figure(figsize=(12,10))
_P = model.keras_model.predict(X_val[:5])
_P_mean = _P[...,:(_P.shape[-1]//2)]
_P_scale = _P[...,(_P.shape[-1]//2):]
plot_some(X_val[:5],Y_val[:5],_P_mean,_P_scale,pmax=99.5)
plt.suptitle('5 example validation patches\n'
'first row: input (source), '
... | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
Export model to be used with CSBDeep **Fiji** plugins and **KNIME** workflowsSee https://github.com/CSBDeep/CSBDeep_website/wiki/Your-Model-in-Fiji for details. | model.export_TF() | _____no_output_____ | BSD-3-Clause | examples/denoising2D_probabilistic/1_training.ipynb | uschmidt83/CSBDeep |
Imports | import numpy as np
from numpy import pi, cos, sin, array
from scipy import signal
from scipy.linalg import toeplitz, inv
import matplotlib.pyplot as plt
plt.style.use('dark_background')
np.set_printoptions(precision=3, suppress=True)
from warnings import filterwarnings
filterwarnings('ignore', category=UserWarning) | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
Useful functions | def calculate_error_rms(x, x_est):
error = x[:len(x_est)] - x_est
error_rms = np.linalg.norm(error)/len(error)
return error_rms.round(5) | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
Zero Forcing Equalizer | x = np.random.choice([-1, 1], 40)
channel = array([.1, -.1, 0.05, 1, .05])
y = np.convolve(x, channel)
_, ax = plt.subplots(1, 2, figsize=(10, 4))
ax[0].stem(x)
ax[1].stem(y);
# 6 tap equalizer
taps = 6
Y = toeplitz(y[taps-1:taps-1+taps], np.flip(y[:taps]))
zerof = inv(Y)@x[:taps]
zerof
x_zerof = np.convolve(y, zerof,... | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
Least Squares Error Equalizer | taps = 6
L = 30 # number of input samples used
Y = toeplitz(y[taps-1: taps-1+L ] ,np.flip(y[:taps]))
lse = inv(Y.T @ Y)@Y.T @ x[:L] #.T is fine because Y is a real matrix, else use Y.conj().T
lse
x_lse = np.convolve(y, lse, 'valid')
plt.stem(x_lse);
calculate_error_rms(x, x_lse) | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
Channel Estimation | L = 30
taps = 5
X = toeplitz( x[:L], np.zeros(6) )
h_est = inv(X.T@X)@X.T@y[:L]
h_est | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
MMSE Equalizer | x_var = 1
noise_var = 1e-4 # SNR = 40 dB
channel = array([.1, -.1, .05, .9+0.1j, .05], complex) # L = 5
N = 5 # Taps in equalizer
L = len(channel)
D = N + L - 4
# Calculate H
col = np.zeros(N, complex)
col[0] = channel[0]
row = np.zeros(N+L-1, complex)
row[:L] = channel
H = toeplitz(col, row)
H.shape
# Calculate R_... | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
A quick note about how `np.convolve()` and `signal.lfilter()` are related.1. ```y_full = np.convolve(x, channel, 'full') size: 2004```2. ```y_same = np.convolve(x, channel, 'same') size: 2000, ```This is same as `y_full[2:-2]` (drops 2 samples in the beginning and end)3. ```y_filt = signal.lfilter(channel, 1, x) si... | estimation = signal.lfilter(C, 1, observations)
error = estimation[D:] - x[:-D]
evm_db = 10*np.log10(np.var(error)/x_var)
snr_db = 10*np.log10(np.var(y)/noise_var)
evm_rms = 100*np.sqrt( np.var(error)/x_var )
print(f'EVM: {evm_db:.2f} dB , {evm_rms:.4f} (% rms) \nSNR: {snr_db:.1f} dB')
fig, ((ax1, ax2), (ax3, ax4)) =... | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
Least Mean Squares (LMS) | x_len = 1500
x = np.random.choice([-1, 1], x_len) + 1j*np.random.choice([-1, 1],x_len)
channel = array([-.19j, .14, 1+.1j, -.16, .11j+.03])
y = signal.lfilter(channel, 1, x)
_, (ax1, ax2) = plt.subplots(2, 1)
ax1.stem(x[:80].imag)
ax2.stem(y[:80].imag);
taps = 13
equalizer = np.zeros(taps, complex)
equalizer[taps//2] =... | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
Decision feedback equalizers | # QPSK signal
x_len = 200
qpsk = np.random.choice([-1, 1], x_len) + 1j*np.random.choice([-1, 1], x_len)
channel = array([0.05, 0.1j, 1.0, 0.20, -0.15j, 0.1])
y = signal.lfilter(channel, 1, qpsk)
# Feed forward filter
# feed_forward_filter = array([0, 0, 0, 1, 0]) # Pass through
feed_forward_filter = array([ 0.004, 0.01... | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
MMSE Optimal Coefficient Calculation | x_var = 1
noise_var = 0 # Noise-free
channel = array([0.05, 0.1j, 1]) # After removing post-cursors (using feedback loop)
L = len(channel) # number of taps in channel
N = 5 # taps in feed forward FIR
D = N + L - 2
# Calculate H
col = np.zeros(N, complex)
col[0] = channel[0]
row = np.zeros(N+L-1, complex)
row[:L] = c... | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
Combine LMS and Decision Feedback | x_len = 1000
qpsk = np.random.choice([1, -1], x_len) + 1j*np.random.choice([1, -1], x_len)
channel = array([0.05, 0.1j, 1.0, 0.2, -0.15j, 0.1])
y = signal.lfilter(channel, 1, qpsk)
# Initialize feed forward equalizer
equalizer = array([ 0.004, 0.0109j, -0.06, -0.1j, 1.0]) # MMSE (see prev section)
N = len(equalizer)
ch... | _____no_output_____ | MIT | chap4.ipynb | mohantyk/dsp_in_comm |
0. get data demographics with pandas | datadir = '../data'
zipped_data = os.path.join(datadir, 'thickness.zip')
with zipfile.ZipFile(zipped_data, 'r') as zip_ref:
zip_ref.extractall(datadir)
dfname = os.path.join(datadir, 'thickness.csv')
df = pd.read_csv(dfname)
idx = np.array(df["ID2"])
age = np.array(df["AGE"])
iq = np.array(df["IQ"])
| _____no_output_____ | MIT | code/analysis_01.ipynb | jsheunis/COSN-talk |
1. load thickness data | j = 0
for Sidx in idx:
# load mgh files for left hem
for file_L in glob.glob('../data/thickness/%s*_lh2fsaverage5_20.mgh'
% (Sidx)):
S_Lmgh = mgh.load(file_L).get_fdata()
S_Larr = np.array(S_Lmgh)[:,:,0]
# load mgh files for right hem ... | _____no_output_____ | MIT | code/analysis_01.ipynb | jsheunis/COSN-talk |
2. plot mean thickness along the cortex | Fs_Mesh_L = read_geometry(os.path.join(datadir, 'fsaverage5/lh.pial'))
Fs_Mesh_R = read_geometry(os.path.join(datadir, 'fsaverage5/rh.pial'))
Fs_Bg_Map_L = load_surf_data(os.path.join(datadir, 'fsaverage5/lh.sulc'))
Fs_Bg_Map_R = load_surf_data(os.path.join(datadir, 'fsaverage5/rh.sulc'))
Mask_Left = nb.freesurfer.... | _____no_output_____ | MIT | code/analysis_01.ipynb | jsheunis/COSN-talk |
3. build the stats model | term_intercept = FixedEffect(1, names="intercept")
term_age = FixedEffect(age, "age")
term_iq = FixedEffect(iq, "iq")
model = term_intercept + term_age
slm = SLM(model, -age, surf=surf_mesh)
slm.fit(thickness)
tvals = slm.t.flatten()
pvals = slm.fdr()
print("t-values: ", tvals) # These are the t-values of the model... | _____no_output_____ | MIT | code/analysis_01.ipynb | jsheunis/COSN-talk |
This is a Level 1 HeadingThis is some paragraph text that describes the code below: | print("this is the code the was describes above") | this is the code the was describes above
| MIT | HelloJupyter.ipynb | fsslh007/artificial-intelligence-fundamentals-with-python-2021-class |
SNOW partitioning parallelThe filter is used to perform SNOW algorithm in parallel and serial mode to save computational time and memory requirement respectively. [SNOW](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.96.023307) algorithm converts a binary image in to partitioned regions while avoiding oversegm... | import numpy as np
import porespy as ps
from porespy.tools import randomize_colors
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 4)
gs.update(wspace=0.5)
np.random.seed(10)
ps.visualization.set_mpl_style() | _____no_output_____ | MIT | examples/filters/tutorials/snow_partitioning_parallel.ipynb | jamesobutler/porespy |
Create a random image of overlapping spheres | im = ps.generators.overlapping_spheres([1000, 1000], r=10, porosity=0.5)
fig, ax = plt.subplots()
ax.imshow(im, origin='lower'); | _____no_output_____ | MIT | examples/filters/tutorials/snow_partitioning_parallel.ipynb | jamesobutler/porespy |
Apply SNOW_partitioning_parallel on the binary image | snow_out = ps.filters.snow_partitioning_parallel(
im=im, divs=2, r_max=5, sigma=0.4) | _____no_output_____ | MIT | examples/filters/tutorials/snow_partitioning_parallel.ipynb | jamesobutler/porespy |
Plot output results | fig, ax = plt.subplots(1, 3, figsize=[9, 3])
ax[0].imshow(snow_out.im);
ax[1].imshow(snow_out.dt);
ax[2].imshow(randomize_colors(snow_out.regions));
ax[0].set_title('Binary Image');
ax[1].set_title('Euclidean Distance Transform')
ax[2].set_title('Segmented Image');
print(f"Number of regions: {snow_out.regions.max()}") | Number of regions: 1006
| MIT | examples/filters/tutorials/snow_partitioning_parallel.ipynb | jamesobutler/porespy |
Blog 4: Spectral ClusteringIn this blog post, we'll explore several algorithms to cluster data points. Some notation:- Boldface capital letters like $\mathbf{A}$ are matrices.- Boldface lowercase letters like $\mathbf{v}$ are vectors. The clustering problemWe're aiming to solve the problem of assigning labels to obser... | import numpy as np
from sklearn import datasets
from matplotlib import pyplot as plt
n = 200
np.random.seed(1111)
X, y = datasets.make_blobs(n_samples=n, shuffle=True, random_state=None, centers = 2, cluster_std = 2.0)
plt.scatter(X[:,0], X[:,1]) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
For this simple distribution, we can use k-means clustering. Intuitively, this minimizes the distances between each cluster's members and its "center of gravity", and works well for roughly circular blobs. | from sklearn.cluster import KMeans
km = KMeans(n_clusters = 2)
km.fit(X)
plt.scatter(X[:,0], X[:,1], c = km.predict(X)) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Generalizing the distributionNow let's look at this distribution of data points. | np.random.seed(1234)
n = 200
X, y = datasets.make_moons(n_samples=n, shuffle=True, noise=0.05, random_state=None)
plt.scatter(X[:,0], X[:,1]) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
The two clusters are still obvious by sight, but k-means clustering fails. | km = KMeans(n_clusters = 2)
km.fit(X)
plt.scatter(X[:,0], X[:,1], c = km.predict(X)) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Constructing a similarity matrix AAn important ingredient in all of the clustering algorithms in this post is the similarity matrix *similarity matrix* $\mathbf{A}$. A is a symmetric square matrix with n rows and columns. `A[i,j]` should be equal to `1` if and only if `X[i]` is close to `X[j]`. To quantify closeness, ... | from sklearn.metrics import pairwise_distances
epsilon = 0.4
dist = pairwise_distances(X)
A = np.array(dist < epsilon).astype('int')
np.fill_diagonal(A,0)
A | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Norm cut objective functionNow that we have encoded the pairwise distances of the data points in $\mathbf{A}$, we can define the clustering problem as a minimization problem. Intuitively, the parameter space of this minimization problem should be the possible cluster assignments (a vector of n 0s and 1s), and the obje... | def cut(A,y):
# diff[i,j] is 1 iff y[i] is in a different group than y[j]
diff = np.array([y != i for i in y], dtype='int')
# return sum of entries in A where diff is 1, divide by 2 due to double counting
return np.sum(np.multiply(diff,A))/2
| _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
We first test it with the true labels, `y`. | cut(A,y) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
...and then with randomly generated labels | randn = np.random.randint(0,2,n)
cut(A,randn) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
As expected, the true labels yield a lower cut term than the fake labels. The Volume Term Now we compute the *volume* of each cluster. The volume of the cluster is just the sum of degrees of the cluster's elements. Remember we want to minimize $\frac{1}{\mathbf{vol}(C_0)}$ so we want to maximize the volume. | def vols(A,y):
# sum the rows of A where the row belongs to the cluster
v0 = np.sum(A[y==0,])
v1 = np.sum(A[y==1,])
return v0, v1 | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Now we have all the ingredients for the norm cut objective. | def normcut(A,y):
v0, v1 = vols(A,y)
return cut(A,y) * (1/v0 + 1/v1)
print(vols(A,y))
print(normcut(A,y)) | (2299, 2217)
0.011518412331615225
| MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Again, the true labels `y` yield a much lower minimizing value than the random labels. | normcut(A,randn) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Part CUnfortunately, with what we have, the parameter space (the possible set of labels) is too large for a computationally efficient algorithm. This is why we need some linear algebra magic to give us another formula for the norm cut objective:$$\mathbf{N}_{\mathbf{A}}(C_0, C_1) = \frac{\mathbf{z}^T (\mathbf{D} - \ma... | def transform(A,y):
# compute volumes
v0, v1 = vols(A,y)
# initialize z to be array of same shape as y, then fill depending on y
z = np.where(y==0, 1/v0, -1/v1)
return z
z = transform(A,y)
# degree matrix: row sums placed on diagonal
# the "at" sign is the matrix product
D = np.diag(A@np.ones(n)) ... | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
We check that the value of the norm cut function is numerically close by either method. | np.isclose(normcut(A,y), normcut_formula) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
We can also check the identity $\mathbf{z}^T\mathbf{D}\mathbb{1} = 0$, where $\mathbb{1}$ is the vector of `n` ones. This identity effectively says that $\mathbf{z}$ should contain roughly as many positive as negative entries, i.e. as many labels in each cluster. | D = np.diag(A@np.ones(n))
np.isclose((z@D@np.ones(n)),0) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
We denote the objective function$$ R_\mathbf{A}(\mathbf{z})\equiv \frac{\mathbf{z}^T (\mathbf{D} - \mathbf{A})\mathbf{z}}{\mathbf{z}^T\mathbf{D}\mathbf{z}} $$We can minimize this function subject to the condition $\mathbf{z}^T\mathbf{D}\mathbb{1} = 0$, which says that the clusters ar equally sized. We can guarantee the... | def orth(u, v):
return (u @ v) / (v @ v) * v
e = np.ones(n)
d = D @ e
def orth_obj(z):
z_o = z - orth(z, d)
return (z_o @ (D - A) @ z_o)/(z_o @ D @ z_o)
from scipy.optimize import minimize
z_min = minimize(fun=orth_obj, x0=np.ones(n)).x | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
By construction, the sign of `z_min[i]` corresponds to the cluster label of data point `i`. We plot the points below, coloring it by the sign of `z_min`. | plt.scatter(X[:,0], X[:,1], c = (z_min >= 0)) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Part FExplicitly minimizing the orthogonal objective is extremely slow, but thankfully find a solution using eigenvalues and eigenvectors.The Rayleigh-Ritz Theorem implies that the minimizing $\mathbf{z}$ is a solution to the eigenvalue problem $$ \mathbf{D}^{-1}(\mathbf{D} - \mathbf{A}) \mathbf{z} = \lambda \mathbf{z... | L = np.linalg.inv(D)@(D-A)
Lam, U = np.linalg.eig(L)
z_eig = U[:,1] | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Now we color the point according to the sign of `z_eig`. Looks pretty good. | plt.scatter(X[:,0], X[:,1], c = z_eig<0) | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Finally, we can define `spectral_clustering(X, epsilon)` which takes in the input data `X` and the distance threshold `epsilon`, performs spectral clustering, and returns an array of labels indicating whether data point `i` is in group `0` or group `1`. | def spectral_clustering(X, epsilon):
'''
Given input X (n by 2 array) and distance threshold epsilon,
performs spectral clustering, and
returns n by 1 labels of cluster classification.
'''
A = np.array(pairwise_distances(X) < epsilon).astype('int')
np.fill_diagonal(A,0)
D = np.diag(A@n... | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Now we can run som experiments, making the problem harder by increasing the noise parameter, and increase the computation by increasing `n`. | np.random.seed(123)
fig, axs = plt.subplots(3, figsize = (8,20))
noises = [0.05, 0.1, 0.2]
for i in range(3):
X, y = datasets.make_moons(n_samples=1000, shuffle=True, noise=noises[i], random_state=None)
axs[i].scatter(X[:,0], X[:,1], c = spectral_clustering(X,0.4))
axs[i].set_title(label = "noise = " + str(... | _____no_output_____ | MIT | notebooks/blog4.ipynb | zhijianli9999/zhijianli9999.github.io |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.