Commit 6b64aae8 by Sanjay Krishnan

cleaning up the repository for the new class

parent 0cfaadd4
# String Matching Extra Credit
*Due 6/7/19 11:59 PM*
Entity Resolution is the task of disambiguating manifestations of real world entities in various records or mentions by linking and grouping. For example, there could be different ways of addressing the same person in text, different addresses for businesses, or photos of a particular object. In this extra credit assignment, you will link two product catalogs.
## Getting Started
First, pull the most recent changes from the cmsc13600-public repository:
```
$ git pull
```
Then, copy the `ec` folder to your submission repository. Change directories to enter your submission repository. Your code will go into `analzy.py`. You can the files to the repository using `git add`:
```
$ git add analyze.py
$ git commit -m'initialized homework'
```
You will also need to fetch the datasets used in this homework assignment:
```
https://www.dropbox.com/s/vq5dyl5hwfhbw98/Amazon.csv?dl=0
https://www.dropbox.com/s/fbys7cqnbl3ch1s/Amzon_GoogleProducts_perfectMapping.csv?dl=0
https://www.dropbox.com/s/o6rqmscmv38rn1v/GoogleProducts.csv?dl=0
```
Download each of the files and put it into your `ec` folder.
Before we can get started, let us understand the main APIs in this project. We have provided a file named `core.py` for you. This file loads and processes the data that you've just downloaded. For example, you can load the Amazon catalog with the `amazon_catalog()` function. This returns an iterator over data tuples in the Amazon catalog. The fields are id, title, description, mfg (manufacturer), and price if any:
```
>>>for a in amazon_catalog():
... print(a)
... break
{'id': 'b000jz4hqo', 'title': 'clickart 950 000 - premier image pack (dvd-rom)', 'description': '', 'mfg': 'broderbund', 'price': '0'}
```
You can similarly, do the same for the Google catalog:
```
>>>for a in google_catalog():
... print(a)
... break
{'id': 'http://www.google.com/base/feeds/snippets/11125907881740407428', 'title': 'learning quickbooks 2007', 'description': 'learning quickbooks 2007', 'mfg': 'intuit', 'price': '38.99'}
```
A matching is a pairing between id's in the Google catalog and the Amazon catalog that refer to the same product. The ground truth is listed in the file `Amzon_GoogleProducts_perfectMapping.csv`. Your job is to construct a list of pairs (or iterator of pairs) of `(amazon.id, google.id)`. These matchings can be evaluated for accuracy using the `eval_matching` function:
```
>>> my_matching = [('b000jz4hqo', http://www.google.com/base/feeds/snippets/11125907881740407428'),...]
>>> {'false positive': 0.9768566493955095, 'false negative': 0.43351268255188313, 'accuracy': 0.04446992095577143}
```
False positive refers to the false positive rate, false negative refers to the false negative rate, and accuracy refers to the overall accuracy.
## Assignment
Your job is write the `match` function in `analzye.py`. You can run your code by running:
```
python3 analyze.py
```
Running the code will print out a result report as follows:
```
----Accuracy----
{'false positive': 0.690576652601969, 'false negative': 0.4926979246733282, 'accuracy': 0.38439138031450204}
---- Timing ----
114.487954 seconds
```
*For full extra credit, you must write a program that achieves at least 35% accuracy in less than 3 mins on a standard laptop.*
## Submission
After you finish the assignment you can submit your code with:
```
$ git push
```
from core import *
import datetime
def match():
'''
Match must return a list of tuples of amazon ids and google ids.
For example:
[('b000jz4hqo', http://www.google.com/base/feeds/snippets/11125907881740407428'),....]
'''
#YOUR CODE GOES HERE
return []
#prints out the accuracy
now = datetime.datetime.now()
out = eval_matching(match())
timing = (datetime.datetime.now()-now).total_seconds()
print("----Accuracy----")
print(out)
print("---- Timing ----")
print(timing,"seconds")
\ No newline at end of file
'''
The core module sets up the data structures and
and references for this programming assignment.
2010
'''
import platform
import csv
if platform.system() == 'Windows':
print("This assignment will not work on a windows computer")
exit()
#defines an iterator over the google catalog
class Catalog():
def __init__(self, filename):
self.filename = filename
def __iter__(self):
f = open(self.filename, 'r', encoding = "ISO-8859-1")
self.reader = csv.reader(f, delimiter=',', quotechar='"')
next(self.reader)
return self
def __next__(self):
row = next(self.reader)
return {'id': row[0],
'title': row[1],
'description': row[2],
'mfg': row[3],
'price': row[4]
}
def google_catalog():
return Catalog('GoogleProducts.csv')
def amazon_catalog():
return Catalog('Amazon.csv')
def eval_matching(matching):
f = open('Amzon_GoogleProducts_perfectMapping.csv', 'r', encoding = "ISO-8859-1")
reader = csv.reader(f, delimiter=',', quotechar='"')
matches = set()
proposed_matches = set()
tp = set()
fp = set()
fn = set()
tn = set()
for row in reader:
matches.add((row[0],row[1]))
for m in matching:
proposed_matches.add(m)
if m in matches:
tp.add(m)
else:
fp.add(m)
for m in matches:
if m not in proposed_matches:
fn.add(m)
prec = len(tp)/(len(tp) + len(fp))
rec = len(tp)/(len(tp) + len(fn))
return {'false positive': 1-prec,
'false negative': 1-rec,
'accuracy': 2*(prec*rec)/(prec+rec) }
# Three-Way Iterator Matching
# Submitting Homework Assignments
This document describes the basic procedure for completing and submitting homework assignments.
*Due 4/19/19 11:59 PM*
## Initial Setup
All of the coding exercises in this class with use Python3 (NOT Python 2!!!). Python 3 is installed on all of the CSIL machines and you can install it on your own computer by downloading it here:
[https://www.python.org/download/releases/3.0/]
In this assignment, you will write a 3-way match operator similar to the 2-way match operator you saw in lecture. Consider the following example where you are given three iterable objects i1,i2,i3:
```
>> i1 = [ 1,7,2,4,6, ... ] # iterable
>> i2 = [ 3,6,7,2,1, ... ] # iterable
>> i3 = [ 10,6,1,2,3, ... ] # iterable
```
On your personal computer, you probably navigate your hard drive by double clicking on icons. While convenient for simple tasks, this approach is limited. For example, imagine that you want to delete all of the music files over 5 MB that you haven't listened to in over a year. This task is very hard to do with the standard double-click interface but is relatively simple using the terminal. All of the instructions in this class will assume access to a terminal interface whether windows, linux, or macos. It is your responsibility to get familiar with using your available terminal.
There is a great tutorial linked here on accessing the Python interpreter from your command line:
[http://www.cs.bu.edu/courses/cs108/guides/runpython.html]
## Git
The purpose of Git is to manage a project, or a set of files, as they change over time. Git stores this information in a data structure called a repository. A git repository contains, among other things, the following: A set of commit objects. A set of references to commit objects, called heads.
Git is installed on all of the CSIL computers, and to install git on your machine follow the instructions here:
[https://git-scm.com/book/en/v2/Getting-Started-Installing-Git]
Every student in the class has a git repository (a place where you can store completed assignments). This git repository can be accessed from:
[https://mit.cs.uchicago.edu/cmsc13600-spr-19/<your cnetid>.git]
You should be able to construct a `ThreeWayMatchOperator` object:
The first thing to do is to open your terminal application, and ``clone`` this repository (NOTE skr is ME, replace it with your CNET id!!!):
```
>> threeWayIter = ThreeWayMatchOperator( (i1,i2,i3) )
$ git clone https://mit.cs.uchicago.edu/cmsc13600-spr-19/skr.git cmsc13600-submit
```
and this operator should iterate over all values that appear in ALL
three iterators. The order is not important
Your username and id is your CNET id and CNET password. This will create a new folder that is empty titled cmsc13600-submit. There is similarly a course repository where all of the homework materials will stored. Youshould clone this repository as well:
```
>> for i in threeWayIter:
... print(i)
[2,2,2]
[1,1,1]
[6,6,6]
$ git clone https://mit.cs.uchicago.edu/skr/cmsc13600-public.git cmsc13600-materials
```
## Getting Started
Acquaint yourselves with the basic homework submission procedures and please ask us if you have any question on Piazza or during office hours BEFORE the deadline. Remember there are no "slip days" in this class, it is your responsibility to know how to complete and submit the homework assignments. We will run a tutorial on how to use git on Thursday 4/11 2-3 (in 223 JCL). A summary is below:
https://mit.cs.uchicago.edu/skr/cmsc13600-public/tree/master/using-git
First, pull the most recent changes from the cmsc13600-public repository:
This will create a new folder titled cmsc13600-materials. This folder will contain your homework assignments. Before you start an assingment you should sync your cloned repository with the online one:
```
$ cd cmsc13600-materials
$ git pull
```
Then, copy the `hw0` folder to your submission repository. Change directories to enter your submission repository. Your code will go into `match.py` this is the only file that you will modify. Finally, add `match.py` using `git add`:
Then, we will tell you which of the pulled materials to copy over to your repository (cmsc13600-submit). Typically, they will be self-contained in a single folder with an obvious title (like hw0).
Try this out on your own! Copy the folder ``using-git`` to your newly cloned submission repository. Enter that repository from the command line and enter the copied ``using-git`` folder. There should be a single file in the folder called ``README.md``. Once you copy over files to your submission repository, you can work on them all you want. Once you are done, you need to add ALL OF THE FILES YOU WISH TO SUBMIT:
```
$ git add match.py
$ git commit -m'initialized homework'
$ git add README.md
```
## Doing the homework
You will have to implement `__next__` and `__iter__` to write a 3-way matching operator. One edge case to watch out for is if any of the iterators is empty. In this case, raise an exception. We have provided a series of basic tests in `test.py`, these tests are incomplete and are not meant to comprehensively grade your assignment.
After you finish the assignment you can submit your code with:
After adding your files, to submit your code you must run:
```
$ git commit -m"My submission"
$ git push
```
We will NOT grade any code that is not added, committed, and pushed to your submission repository. You can confirm your submission by visiting the web interface[https://mit.cs.uchicago.edu/cmsc13600-spr-19/skr]
class ThreeWayMatchOperator:
"""
In this assignment, you will write a 3-way match operator
similar to the 2-way match operator you saw in lecture.
Consider the following example where you are given three
iterators i1,i2,i3:
>> i1 = [ 1,7,2,4,6, ... ] # iterator
>> i2 = [ 3,6,7,2,1, ... ] # iterator
>> i3 = [ 10,6,1,2,3, ... ] # iterator
You can construct a ThreeWayMatchOperator object:
>> threeWayIter = ThreeWayMatchOperator( (i1,i2,i3) )
and this operator should return all values that appear in ALL
three iterators. The order is not important
>> for i in threeWayIter:
... print(i)
1. [2,2,2]
2. [1,1,1]
3. [6,6,6]
Edge cases:
* Return an error if any of the iterators has 0 values
"""
def __init__(self, input):
self.in1, self.in2, self.in3 = input
def __iter__(self):
raise NotImplemented("You must implement an initializer")
def __next__(self):
raise NotImplemented("You must implement a next function")
\ No newline at end of file
from match import ThreeWayMatchOperator
def tryOrAssert(fn, output, error=False):
try:
return (fn() == output)
except:
return error
def test1():
r1 = range(0,10)
r2 = range(0,10,3)
r3 = range(0,10,2)
t = ThreeWayMatchOperator((r1,r2,r3))
values = set([v[0] for v in t])
return values
def test2():
r1 = range(0,12)
r2 = range(0,10,3)
r3 = range(0,10,2)
t = ThreeWayMatchOperator((r1,r2,r3))
values = set([v[0] for v in t])
return values
def test3():
r1 = range(0)
r2 = range(0)
r3 = range(0)
t = ThreeWayMatchOperator((r1,r2,r3))
values = set([v[0] for v in t])
return values
def test4():
r1 = range(0,1)
r2 = range(0,1)
r3 = range(0,1)
t = ThreeWayMatchOperator((r1,r2,r3))
values = set([v[0] for v in t])
return values
def test5():
r1 = ['a', 'b', 'c','d']
r2 = ['3', '2', '1','d']
r3 = ['p', 'q', 'a','d']
t = ThreeWayMatchOperator((r1,r2,r3))
values = set([v[0] for v in t])
return values
print("Basic 1", tryOrAssert(test1, {0, 6}))
print("Basic 2", tryOrAssert(test2, {0, 6}))
print("Basic 3", tryOrAssert(test5, {'d'}))
print("Empty",tryOrAssert(test3, None, True))
print("Singleton", tryOrAssert(test4, {0}))
# Out-of-Core Group By Aggregate
*Due 4/29/19 11:59 PM*
In this assignment, you will implement an out-of-core
version of the group by aggregate (aggregation by key)
seen in lecture. You will have a set memory limit and
you will have to count the number of times a string shows
up in an iterator. Your program should work for any limit
> 20.
## Getting Started
First, pull the most recent changes from the cmsc13600-public repository:
```
$ git pull
```
Then, copy the `hw1` folder to your submission repository. Change directories to enter your submission repository. Your code will go into `countD.py` this is the only file that you will modify. Finally, add `countD.py` using `git add`:
```
$ git add countD.py
$ git commit -m'initialized homework'
```
Now, you will need to fetch the data used in this assignment. Download title.csv put it in the hw1 folder:
https://www.dropbox.com/s/zl7yt8cl0lvajxg/title.csv?dl=0
DO NOT ADD title.csv to the git repo! After downloading the
dataset, there is a python module provided for you called `core.py`, which reads the dataset. This module loads the data in as
an iterator in two functions `imdb_years()` and `imdb_title_words()`:
```
>> for i in imdb_years():
... print(i)
1992
1986
<so on>
```
Play around with both `imdb_years()` and `imdb_title_words()` to get a feel for how the data works.
## MemoryLimitedHashMap
In this project, the main data structure is the `MemoryLimitedHashMap`. This is a hash map that has an explicit limit on the number of keys it can store. To create one of these data structure, you can import it from core module:
```
from core import *
#create a memory limited hash map
m = MemoryLimitedHashMap()
```
To find out what the limit of this hash map is, you can:
```
print("The max size of m is: ", m.limit)
```
The data structure can be constructed with an explicit limit (the default is 1000), e.g., `MemoryLimitedHashMap(limit=10)`.
Adding data to this hash map is like you've probably seen before in a data structure class. There is a `put` function that takes in a key and assigns that key a value:
```
# put some keys
m.put('a', 1)
m.put('b', 45)
print("The size of m is: ", m.size())
```
You can fetch the data using the `get` function and `keys` function:
```
# get keys
for k in m.keys():
print("The value at key=", k, 'is', m.get(k))
# You can test to see if a key exists
print('Does m contain a?', m.contains('a'))
print('Does m contain c?', m.contains('c'))
```
When a key does not exist in the data structure the `get` function will raise an error:
```
#This gives an error:
m.get('c')
```
Similarly, if you assign too many unique keys (more than the limit) you will get an error:
```
for i in range(0,1001):
m.put(str(i), i)
```
The `MemoryLimitedHashMap` allows you to manage this limited storage with a `flush` function that allows you to persist a key and its assignment to disk. When you flush a key it removes it from the data structure and decrements the limit. Flush takes a key as a parameter.
```
m.flushKey('a')
print("The size of m is: ", m.size())
```
Note that the disk is not intelligent! If you flush a key multiple times it simply appends the flushed value to a file on disk:
```
m.flushKey('a')
<some work...>
m.flushKey('a')
```
Once a key has been flushed it can be read back using the `load` function (which takes a key as a parameter). This loads back *all* of the flushed values:
```
#You can also load values from disk
for k,v in m.load('a'):
print(k,v)
```
If you try to load a key that has not been flushed, you will get an error:
```
#Error!!
for k,v in m.load('d'):
print(k,v)
```
If you want multiple flushes of the same key to be differentiated, you can set a *subkey*:
```
#first flush
m.flushKey('a', '0')
<some work...>
#second flush
m.flushKey('a', '1')
```
The `load` function allows you to selectively pull
certain subkeys:
```
# pull only the first flush
m.load('a', '0')
```
We can similarly iterate over all of the flushed data (which optionally takes a subkey as well!):
```
for k,v in m.loadAll():
print(k,v)
```
There is also a way to iterate over all of the flushed keys (will strip out subkeys):
```
m.fKeys()
```
## Count Per Group
In this assignment, you will implement an out-of-core count operator which for all distinct strings in an iterator returns
the number of times it appears (in no particular order).
For example,
```
In: "the", "cow", "jumped", "over", "the", "moon"
Out: ("the",2), ("cow",1), ("jumped",1), ("over",1), ("moon",1)
```
Or,
```
In: "a", "b", "b", "a", "c"
Out: ("c",1),("b",2), ("a", 2)
```
The catch is that you CANNOT use a list, dictionary, or set from
Python. We provide a general purpose data structure called a MemoryLimitedHashMap (see ooc.py). You must maintain the iterator
state using this data structure.
The class that you will implement is called Count (in countD.py).
The constructor is written for you, and ittakes in an input iterator and a MemoryLimitedHashMap. You will use these objects
in your implementation. You will have to implement `__next__` and `__iter__`. Any solution using a list, dictionary, or set inside `Count` will recieve 0 points.
The hint is to do this in multiple passes and use a subkey to track keys flushed between different passes.
## Testing and Submission
We have provided a series of basic tests in `test.py`, these tests are incomplete and are not meant to comprehensively grade your assignment. There is a file `years.json` with an expected output. After you finish the assignment you can submit your code with:
```
$ git push
```
'''
The core module sets up the data structures and
and references for this programming assignment.
'''
import platform
import os
import json
if platform.system() == 'Windows':
print("This assignment will not work on a windows computer")
exit()
def imdb_title_words():
f = open('title.csv','r')
line = f.readline()
while line != "":
words = line.strip().split(',')[1].split()
for w in words:
yield w
line = f.readline()
f.close()
def imdb_years():
f = open('title.csv','r')
line = f.readline()
while line != "":
csvsplit = line.strip().split(',')
year = csvsplit[len(csvsplit) - 8]
if year.strip() != "":
yield year
line = f.readline()
f.close()
"""
Get the dataset first, download title.csv put it in the pa1 folder
https://www.dropbox.com/s/zl7yt8cl0lvajxg/title.csv?dl=0
Count the number of times each symbol shows up in an iterator
with limited memory. Your program should work for any limit
> 20.
"""
class Count:
"""
In this assignment, you will implement an out-of-core count
operator which for all distinct strings in an iterator returns
the number of times it appears (in no particular order).
For example,
In: "the", "cow", "jumped", "over", "the", "moon"
Out: ("the",2), ("cow",1), ("jumped",1), ("over",1), ("moon",1)
Or,
In: "a", "b", "b", "a", "c"
Out: ("c",1),("b",2), ("a", 2)
The catch is that you CANNOT use a list, dictionary, or set from
python. We provide a general purpose data structure called a
MemoryLimitedHashMap (see ooc.py). You must maintain the iterator
state using this data structure.
"""
def __init__(self, input, memory_limit_hashmap):
'''
The constructor takes in an input iterator and
a MemoryLimitedHashMap. You will use these objects
in your implementation.
'''
self.in1 = input
self.hashmap = memory_limit_hashmap
def __iter__(self):
raise NotImplemented("You must implement an initializer")
def __next__(self):
raise NotImplemented("You must implement a next function")
import os
import json
class MemoryLimitedHashMap(object):
'''
A MemoryLimitedHashMap simulates a hardware memory limit for a
key-value data structure. It will raise an exception if the
limit is exceeded.
Keys must be strings
'''
def __init__(self, diskfile='disk.file', limit=1000):
'''
The constructor takes a reference to a persistent file
and a memory limit.
'''
if os.path.exists(diskfile):
print("[Warning] Overwriting the Disk File", diskfile)
import shutil
shutil.rmtree(diskfile)
os.mkdir(diskfile)
self.diskfile = diskfile
self._data = {}
self.limit = limit
def size(self):
return len(self._data)
def put(self, k, v):
'''
Basically works like dict put
'''
if not self.contains(k) and len(self._data) == self.limit:
raise ValueError("[Error] Attempting to Insert Into a Full Map: " + str((k,v)))
else:
self._data[k] = v
def get(self, k):
'''
Basically works like dict get
'''
return self._data[k]
def contains(self, k):
'''
Basically works like hash map contains
'''
return (k in self._data)
def keys(self):
'''
Returns a set of keys. Tuple
is (key, location)
'''
return set([k for k in self._data])
def fKeys(self):
'''
Returns a set over keys that have been flushed.
Tuple is (key, location)
'''
return set([self.path2Key(k) for k in os.listdir(self.diskfile)])
def keyPath(self, k, subkey):
return self.diskfile+"/"+str(k)+ "_" + subkey
def path2Key(self, k):
key = k.split("_")[0]
return key
def flushKey(self, k, subkey):
'''
Removes the key from the dictionary and
persists it to disk.
'''
if not self.contains(k):
raise ValueError("[Error] Map Does Not Contain " + k)
f = open(self.keyPath(k, subkey), 'a')
f.write(json.dumps(self.get(k)) + "\n")
f.close()
del self._data[k] #free up the space
def load(self, k, subkey=""):
'''
Streams all of the data from a persisted key
'''
fname = self.keyPath(k, subkey)
if not os.path.exists(fname):
raise ValueError("[Error] Disk Does Not Contain " + k)
f = open(fname, 'r')
line = f.readline()
while line != "":
yield (k, json.loads(line.strip()))
line = f.readline()
def loadAll(self, subkey=""):
'''
Streams all of the data from all keys
'''
for k in self.keys():
yield (k, self.get(k))
for k in self.fKeys():
for _,v in self.load(k, subkey):
yield (k,v)
\ No newline at end of file
from countD import *
from core import *
from ooc import *
import json
test_file = open('years.json','r')
expected = json.loads(test_file.read())
for l in range(80, 140, 20):
m = MemoryLimitedHashMap(limit = l)
actual = {k:v for k,v in Count(imdb_years(), m)}
print("Memory Limit", l, expected == actual)
{"1944": 1831, "1917": 4514, "1907": 1487, "1975": 14054, "1880": 1, "2003": 67777, "2012": 164307, "1958": 9768, "1894": 93, "1904": 1136, "1979": 14926, "1915": 7670, "2010": 141703, "2017": 3, "1982": 14770, "1954": 7199, "2014": 3077, "1948": 2840, "1893": 2, "1923": 2614, "2005": 95005, "2009": 128696, "1992": 24917, "1949": 3847, "1945": 1730, "1896": 791, "1902": 1799, "1976": 13994, "1965": 13063, "1961": 11073, "1951": 5663, "1962": 10308, "1929": 2800, "2000": 53013, "1910": 4597, "1912": 7770, "1898": 1740, "1901": 1747, "1922": 3066, "1957": 9491, "1927": 2915, "2001": 58590, "1940": 2202, "2002": 62568, "1995": 36437, "1913": 8902, "1999": 50564, "1994": 30027, "1932": 2567, "1980": 14779, "1925": 2786, "1983": 15489, "1889": 2, "1973": 14284, "1936": 2798, "1892": 9, "1939": 2483, "1971": 14442, "1981": 14456, "2013": 63827, "1942": 2181, "1968": 14235, "1930": 2543, "1990": 23040, "2015": 401, "1914": 8125, "1909": 3417, "1906": 1104, "1920": 4012, "1972": 13623, "1891": 7, "1938": 2730, "1985": 18391, "1911": 5945, "1947": 2291, "1921": 3627, "1888": 5, "1963": 11153, "2016": 32, "1895": 120, "1964": 11416, "1977": 14038, "1984": 16571, "2008": 122861, "1997": 38955, "1955": 8007, "1900": 1816, "1989": 21312, "1966": 13711, "1967": 14601, "1950": 4763, "1918": 3781, "1890": 6, "1931": 2507, "1986": 19440, "1905": 800, "1919": 3613, "1960": 11121, "1899": 1787, "1943": 1960, "1969": 14349, "1974": 13736, "1988": 19861, "2007": 119565, "1935": 2467, "1959": 10517, "1903": 2618, "1926": 2847, "1916": 5835, "1978": 14428, "1937": 2795, "1993": 26775, "1908": 2712, "2004": 84593, "1996": 36509, "1924": 2615, "2006": 108429, "1953": 6834, "1952": 6346, "2019": 2, "1941": 2206, "1970": 15000, "1987": 20122, "2011": 160017, "1934": 2493, "1991": 23799, "1946": 1965, "1998": 46583, "1933": 2433, "1897": 1309, "1956": 8628, "1928": 2773}
\ No newline at end of file
/*Calculates the average the gpa for each major over all students/
/*Find the bottom 10 majors in terms of average gpa (the majors from 0.sql that have the 10 lowest GPAs).*/
/*For each major, calculate the fraction of students who have a 4.0.*/
/*Find the college that contributed the most number of students.*/
/*Write a query to find all the distinct cities in the hometown table that have the same name.*/
/*Calculate the number of colleges per-capita (total divided by the population) in each state.*/
/*The number of unique cities in the hometown table that don't have any students in the database.*/
/*List the names of each student with the highest gpa in their home cities from those cities where there are at least 8 students from that city.*/
# SQL Exercises
*Due 5/13/19 11:59 PM*
In this assignment, you will practice writing SQL queries against a synthetically generated
"Graduate Admissions" database. This database contains three tables: a table of students, a table of undergraduate institutions from which they came, and a table of cities from where the students attended high school.
The tables are defined as follows:
```
create table students(id int, --student id number
name varchar(64), --the full name of the student
college_id int, --the id of the college they attended
hometown_id, --the id of their home town
major varchar(64), --their major
gpa float); --their gpa
```
The students table links to the college table and the hometown table with college_id and the hometown_id respectively:
```
cretea table colleges (id int,
rank int, --the rank of the college
name varchar(64), --the full name of the college
city varchar(32)); --the city in which the college is
```
```
create table hometown (id int,
city varchar(32), --the name of the city
scode varchar(32), --the abbrev of the state (coded, e.g., CA)
state varchar(32), --the name of the state
county varchar(32), --the name of the county
population float); --the name of the population of the city
```
You will write SQL queries to answer different questions across this dataset. Unlike the previous assignments, there will be no explicit tests. We will provide some guidance on what to expect but, you will have to convince yourselves that your solutions are correct.
## Getting Started
First, pull the most recent changes from the cmsc13600-public repository:
```
$ git pull
```
Then, copy the `hw2` folder to your submission repository. Change directories to enter your submission repository. Your code will go into each of the `.sql` files. You can add all of them to the repository using `git add`:
```
$ git add *.sql
$ git commit -m'initialized homework'
```
The file `admissions.db` stores all of the data in the database. To query the database you must run the `sqlite3` program:
```
$ sqlite3 admissions.db
SQLite version 3.14.0 2016-07-26 15:17:14
Enter ".help" for usage hints.
sqlite>
```
This will return a prompt in which you can type in your SQL queries. For example,
```
sqlite> select * from colleges where id=0;
0|948|A.T. Still University|Kirksville
sqlite> select * from students where id=0;
0|John Muzquiz|436|9520|Mathematics|3.72663450103766
sqlite> select * from hometown where id=0;
0|88|KY|Kentucky|BARREN|250.0
```
## SQL Assignment
For each of the assigned SQL queries you must write the entire query in its respective file. The query consists of *everything you type in*. For example, above this is `select * from hometown where id=0;`.
### 0.sql
Calculates the average the gpa for each major over all students. The first column of the output must have the major, the second column must have the average of all students with that major titled `agpa`. Testing Hint: As a sanity check for your query there are 98 majors.
### 1.sql
Find the bottom 10 majors in terms of average gpa (the majors from 0.sql that have the 10 lowest GPAs). Then, calculate the number of students with one of these majors. Your result should be a single column titled 'cnt' and single row with the total count. Testing Hint: There are 30000 student records evenly distributed among 98 majors.
### 2.sql
For each major, calculate the fraction of students who have a 4.0. Your result should have the first column as the `major` and the second column called `frac` with the fraction of students. Testing Hint: No major has more than 0.55.
### 3.sql
Find the college that contributed the most number of students. Your result should have the first column as the college's `name` and the second column called `cnt` with the count of students who come from there. Testing Hint: The highest count is less than 100.
### 4a.sql
Write a query to find all the distinct cities (rows with different id's) in the hometown table that have the same name. Hint: there may not be any but write the query any ways.
### 4b.sql
Based on your answer to 4a, how might you match the `college` and `hometown` tables? Write a query to calculate the number of colleges per-capita (total divided by the population) in each state. Keep in mind that we are interested in the total number of colleges in the state divided by the total population of the state. Your result should have two columns the first being the state name `state` and the second being the `colpc` column giving the per capita fraction. Testing Hint: All of the numbers are low.
### 5.sql
Find the number of unique cities in the hometown table that don't have any students in the database. Your result should be a single column 'cnt' and a single row with the number.
### 6.sql
For each city find the student with the highest GPA (including ties). Return the names of those students who are the best in their respective cities only if there are at least 8 students from the city. Your result should have a single column `name` with the students' names.
### 7.sql
Calculate the probability (as a fraction) that two randomly picked students will be from the same city. Your result should have two columns (`numerator`) and (`denominator`) representing this fraction and a single row. You may not hard code any sizes.
## Submission
After you finish the assignment you can submit your code with:
```
$ git push
```
# Extract-Transform-Load
*Due 6/3/19 11:59 PM*
Extract, transform, load (ETL) is the general procedure of copying data from one or more sources into a destination system which represents the data differently from the source(s). In this project, you will write some of the core primitives in an ETL system.
## Getting Started
First, pull the most recent changes from the cmsc13600-public repository:
```
$ git pull
```
Then, copy the `hw3` folder to your submission repository. Change directories to enter your submission repository. Your code will go into the `etl.py` and `etl_programs.py` files. You can the files to the repository using `git add`:
```
$ git add *.py
$ git commit -m'initialized homework'
```
You will additionally have to install the Pandas library to do this assignment:
```
$ pip3 install pandas
```
Feel free to skip this section if you already know how Pandas works. Pandas is a data analysis toolkit for Python that makes it easy to work with tabular data. We organize our tutorial of this library around an exploration of data from the 2015 New York City Street Tree Survey, which is freely available from the New York City open data portal (https://data.cityofnewyork.us). This survey was performed by the New York City Department of Parks and Recreation with help from more than 2000 volunteers. The goal of the survey is to catalog the trees planted on the City right-of-way, typically the space between the sidewalk and the curb, in the five boroughs of New York. The survey data is stored in a CSV file that has 683,789 lines, one per street tree. (Hereafter we will refer to trees rather than street trees for simplicity.) The census takers record many different attributes for each tree, such as the common name of the species, the location of the tree, etc. Of these values, we will use the following:
* boroname: the name of the borough in which the tree resides;
*health: an estimate of the health of the tree: one of good, fair, or poor;
* latitude and longitude : the location of the tree using geographical coordinates;
* spc_common: the common, as opposed to Latin, name of the species;
status: the status of the tree: one of alive, dead, or stump;
* tree_id: a unique identifier
Some fields are not populated for some trees. For example, the health field is not populated for dead trees and stumps and the species field (spc_common) is not populated for stumps and most dead trees.
To use pandas, you can simply import it as follows:
```
>>> import pandas as pd
```
DataFrames are the the main data structure in Pandas. The library function pd.read_csv takes the name of a CSV file and loads it into a data frame. Let’s use this function to load the tree data from a file named 2015StreetTreesCensus_TREES.csv:
```
>>> trees = pd.read_csv("2015StreetTreesCensus_TREES.csv")
```
The variable trees now refers to a Pandas DataFrame. Let’s start by looking at some of the actual data. You can similarly create a DataFrame from lists:
```
>>> df = pd.DataFrame([['Bob', 'Stewart'],
['Anna', 'Davis'],
['Jerry', 'Dole'],
['John', 'Marsh']],
columns=['first_name', 'last_name'])
```
We’ll explain the various ways to access data in detail later. For now, just keep in mind that the columns have names (for example, “Latitude”, “longitude”, “spc_common”, etc) and leverage the intuition you’ve built up about indexing in other data structures.
Here, for example, are a few columns from the first ten rows of the dataset:
```
>>> trees10 = trees[:10]
>>> trees10[["Latitude", "longitude", "spc_common", "health", "boroname"]]
Latitude longitude spc_common health boroname
0 40.723092 -73.844215 red maple Fair Queens
1 40.794111 -73.818679 pin oak Fair Queens
2 40.717581 -73.936608 honeylocust Good Brooklyn
3 40.713537 -73.934456 honeylocust Good Brooklyn
4 40.666778 -73.975979 American linden Good Brooklyn
5 40.770046 -73.984950 honeylocust Good Manhattan
6 40.770210 -73.985338 honeylocust Good Manhattan
7 40.762724 -73.987297 American linden Good Manhattan
8 40.596579 -74.076255 honeylocust Good Staten Island
9 40.586357 -73.969744 London planetree Fair Brooklyn
```
Notice that the result looks very much like a table in which both the columns and the rows are labelled. In this case, the column labels came from the first row in the file and the rows are simply numbered starting at zero.
Here’s the full first row of the dataset with all 41 attributes:
```
>>> trees.iloc[0]
created_at 08/27/2015
tree_id 180683
block_id 348711
the_geom POINT (-73.84421521958048 40.723091773924274)
tree_dbh 3
stump_diam 0
curb_loc OnCurb
status Alive
health Fair
spc_latin Acer rubrum
spc_common red maple
steward None
guards None
sidewalk NoDamage
user_type TreesCount Staff
problems None
root_stone No
root_grate No
root_other No
trnk_wire No
trnk_light No
trnk_other No
brnch_ligh No
brnch_shoe No
brnch_othe No
address 108-005 70 AVENUE
zipcode 11375
zip_city Forest Hills
cb_num 406
borocode 4
boroname Queens
cncldist 29
st_assem 28
st_senate 16
nta QN17
nta_name Forest Hills
boro_ct 4073900
state New York
Latitude 40.7231
longitude -73.8442
x_sp 1.02743e+06
y_sp 202757
Name: 0, dtype: object
```
and here are a few specific values from that row:
```
>>> first_row = trees.iloc[0]
>>> first_row["Latitude"]
40.72309177
>>> first_row["longitude"]
-73.84421522
>>> first_row["boroname"]
'Queens'
```
Notice that the latitude and longitude values are floats, while the borough name is a string. Conveniently, read_csv analyzes each column and if possible, identifies the appropriate type for the data stored in the column. If this analysis cannot determine a more specific type, the data will be represented using strings.
We can also extract data for a specific column:
```
>>> trees10["boroname"]
0 Queens
1 Queens
2 Brooklyn
3 Brooklyn
4 Brooklyn
5 Manhattan
6 Manhattan
7 Manhattan
8 Staten Island
9 Brooklyn
Name: boroname, dtype: object
```
and we can easily do useful things with the result, like count the number of times each unique value occurs:
```
>>> trees10["boroname"].value_counts()
Brooklyn 4
Manhattan 3
Queens 2
Staten Island 1
Name: boroname, dtype: int64
```
Now that you have a some feel for the data, we’ll move on to discussing some useful attributes and methods provided by data frames. The shape attribute yields the number of rows and columns in the data frame:
```
>>> trees.shape
(683788, 42)
```
The data frame has fewer rows (683,788) than lines in the file (683,789), because the header row is used to construct the column labels and does not appear as a regular row in the data frame. To access a row using the row number, that is, its position in the data frame, we use iloc operator and square brackets:
```
>>> trees.iloc[3]
created_at 08/27/2015
block_id 348711
the_geom POINT (-73.84421521958048 40.723091773924274)
tree_dbh 3
stump_diam 0
curb_loc OnCurb
status Alive
health Fair
spc_latin Acer rubrum
spc_common red maple
steward None
guards None
sidewalk NoDamage
user_type TreesCount Staff
problems None
root_stone No
root_grate No
root_other No
trnk_wire No
trnk_light No
trnk_other No
brnch_ligh No
brnch_shoe No
brnch_othe No
address 108-005 70 AVENUE
zipcode 11375
zip_city Forest Hills
cb_num 406
borocode 4
boroname Queens
cncldist 29
st_assem 28
st_senate 16
nta QN17
nta_name Forest Hills
boro_ct 4073900
state New York
Latitude 40.7231
longitude -73.8442
x_sp 1.02743e+06
y_sp 202757
Name: 180683, dtype: object
```
In both cases the result of evaluating the expression has type Pandas Series:
We can extract the values in a specific column using square brackets with the column name as the index:
```
>>> trees10["spc_common"]
tree_id
180683 red maple
200540 pin oak
204026 honeylocust
204337 honeylocust
189565 American linden
190422 honeylocust
190426 honeylocust
208649 American linden
209610 honeylocust
192755 London planetree
Name: spc_common, dtype: object
```
We can also use dot notation to access a column, if the corresponding label conforms to the rules for Python identifiers and does not conflict with the name of a DataFrame attribute or method:
```
>>> trees10.spc_common
tree_id
180683 red maple
200540 pin oak
204026 honeylocust
204337 honeylocust
189565 American linden
190422 honeylocust
190426 honeylocust
208649 American linden
209610 honeylocust
192755 London planetree
Name: spc_common, dtype: object
```
The tree dataset has many columns, most of which we will not be using to answer the questions posed at the beginning of the chapter. As we saw above, we can extract the desired columns using a list as the index:
```
>>> cols_to_keep = ['spc_common', 'status', 'health', 'boroname', 'Latitude', 'longitude']
>>> trees_narrow = trees[cols_to_keep]
>>> trees_narrow.shape
(683788, 6)
```
This new data frame has the same number of rows and the same index as the original data frame, but only six columns instead of the original 41.
If we know in advance that we will be using only a subset of the columns, we can specify the names of the columns of interest to pd.read_csv and get the slimmer data frame to start. Here’s a function that uses this approach to construct the desired data frame:
```
>>> def get_tree_data(filename):
... '''
... Read slim version of the tree data and clean up the labels.
...
... Inputs:
... filename: name of the file with the tree data
...
... Returns: DataFrame
... '''
... cols_to_keep = ['tree_id', 'spc_common', 'status', 'health', 'boroname',
... 'Latitude', 'longitude']
... trees = pd.read_csv(filename, index_col="tree_id",
... usecols=cols_to_keep)
... trees.rename(columns={"Latitude":"latitude"}, inplace=True)
... return trees
...
...
>>> trees = get_tree_data("2015StreetTreesCensus_TREES.csv")
```
A few things to notice about this function: first, the index column, tree_id, needs to be included in the value passed with the usecols parameter. Second, we used the rename method to fix a quirk with the tree data: “Latitude” is the only column name that starts with a capital letter. We fixed this problem by supplying a dictionary that maps the old name of a label to a new name using the columns parameter. Finally, by default, rename constructs a new dataframe. Calling it with the inplace parameter set to True, causes frame updated in place, instead.
We encourage you to read the Pandas API before you do this homework, most of the functions that you will implement are trivial if you have the right Pandas library routine!
https://pandas.pydata.org/pandas-docs/stable/reference/index.html
## Implementing ETL Functions
The ETL class defines basic language primitives for manipulating Pandas
DataFrames. It takes a DataFrame in and outputs a transformed DataFrame. You will implement several of the routines to perform these transformations.
Here is how we intend the `ETL` class to be used. You can create DataFrame and create an ETL class that takes the DataFrame as input.
```
>> df1 = pd.DataFrame([['Bob', 'Stewart'],
['Anna', 'Davis'],
['Jerry', 'Dole'],
['John', 'Marsh']],
columns=["first_name", "last_name"])
>> etl = ETL(df1)
```
For example, the add() function creates a new column with a specified value. We might want to add a new colum to represent ages:
```
>> etl.add("age", 0)
>> etl.df
first_name last_name age
0 Bob Stewart 0
1 Anna Davis 0
2 Jerry Dole 0
3 John Marsh 0
```
### Drop and Copy
As a warm-up, the first functions that you will write are `drop(colname)` which drops a column from the dataset with a specific column name.
```
>> etl.drop(colname="first_name")
>> etl.df
last_name
0 Stewart
1 Davis
2 Dole
3 Marsh
```
and `copy(colname, new_colname)` which duplicates a column and saves it to the new name:
```
>> etl.copy(colname="first_name", new_colname="first_name2")
>> etl.df
first_name last_name first_name2
0 Bob Stewart Bob
1 Anna Davis Anna
2 Jerry Dole Jerry
3 John Marsh John
```
### Split/Merge
Next, you will write a `split(colname, new_colname, splitter)` function. This function takes an input dataframe and splits all values in colname on a delimiter. It puts the substring before the delimiter in colname, and the substring after the delimiter in a new column. For example,
```
>>> df1 = pd.DataFrame([['Bob-Stewart'],
['Anna-Davis'],
['Jerry-Dole'],
['John']],
columns=["name"])
>>> etl = ETL(df1)
>> etl.split("name", "last_name","-")
>> etl.df
name last_name
0 Bob Stewart
1 Anna Davis
2 Jerry Dole
3 John
```
When a value does not contain the delimiter new_colname is an empty string. The `merge` function does the opposite of `split`. It takes `merge(col1, col2, splitter)` replaces col1
with the values of col1 and col2 concatenated and seperated by the delimiter. If the value in either col1 or col2 is an empty string, then the delimiter is ignored:
```
>> etl.df
name last_name
0 Bob Stewart
1 Anna Davis
2 Jerry Dole
3 John
>> pw1.merge("name", "last_name","-")
name last_name
0 Bob-Stewart Stewart
1 Anna-Davis Davis
2 Jerry-Dole Dole
3 John
```
### Format
Next, you will write a `format` function that transforms values in a specified column. Format applies an input function to every value in a column. For example,
```
df1 = pd.DataFrame([['Bob-Stewart'],
['Anna-Davis'],
['Jerry-Dole'],
['John']],
columns=["name"])
etl = ETL(df1)
etl.format("name", lambda x: x.replace("-",","))
>> etl.df
name
0 Bob,Stewart
1 Anna,Davis
2 Jerry,Dole
3 John
```
### Divide
Divide conditionally divides a column, sending values that satisfy the condition into one of two columns. For example, consider the data frame below that has names delimited by two different delimiters. Divide can be used to separate these:
```
df1 = pd.DataFrame([['Bob-Stewart'],
['Anna-Davis'],
['Jerry-Dole'],
['John,Smith']],
columns=["name"])
etl = ETL(df1)
etl.divide("name", "dash", "comma", lambda x: '-' in x)
>> etl.df
name dash comma
0 Bob-Stewart Bob-Stewart
1 Anna-Davis Anna-Davis
2 Jerry-Dole Jerry-Dole
3 John,Smith John,Smith
```
##ETL Programs
Now, you will use the functions that you wrote to write ETL programs. The remainder of this homework must be completed using a sequence of functions from the ETL class. Your code goes into `etl_programs.py`. As an example, suppose we are given the data:
```
df1 = pd.DataFrame([['Bob-Stewart'],
['Anna-Davis'],
['Jerry-Dole'],
['John,Smith']],
columns=["name"])
```
Some of the names are delimited by dashes and some by commas in a single column `name`. We want to to transform this dataframe to have two columns `first_name` and `last_name` with the appropriate names extracted from the dataframe. We could do the following:
```
>> pw1 = ETL(df1)
>> pw1.divide("name", "dash", "comma", lambda x: '-' in x) #divide on a dash
>> pw1.split("dash", "last_name_dash", "-") #split the dash column
>> pw1.split("comma", "last_name_comma", ",") #split the comma column
>> pw1.add("last_name", "")
>> pw1.add("first_name", "")
>> pw1.merge("first_name", "dash", "") #add the first names
>> pw1.merge("first_name", "comma", "")
>> pw1.merge("last_name", "last_name_dash", "") #add the lastnames
>> pw1.merge("last_name", "last_name_comma", "")
>> pw1.drop("name") #drop uncessary columns
>> pw1.drop("dash")
>> pw1.drop("comma")
>> pw1.drop("last_name_dash")
>> pw1.drop("last_name_comma")
>> pw1.df
last_name first_name
0 Stewart Bob
1 Davis Anna
2 Dole Jerry
3 Smith John
```
The following functions are case insensitive.
### phone
You are given an input dataframe as follows:
```
df = pd.DataFrame([['(408)996-758'],
['+1 667 798 0304'],
['(774)998-758'],
['+1 442 030 9595']],
columns=["phoneno"])
```
Write an ETL program that results in a dataframe with two columns: area_code,
phone_number. area_code must be formated as a number with only digits (no parens) and the phone number must be of the form xxx-xxxx.
### date
You are given an input dataframe as follows:
```
df = pd.DataFrame([['03/2/1990'],
['2/14/1964'],
['1990-04-30'],
['7/9/2012'],
['1989-09-13'],
['1994-08-21'],
['1996-11-30'],
['2004-12-23'],
['4/21/2016']]
columns=["date"])
```
Write an ETL program that results in a dataframe with three columns: day, month, year. The day must be in two-digit format i.e, 01, 08. The month must be the full month name, e.g., "May". The year must be in YYYY format.
### name
You are given an input dataframe as follows:
```
df = pd.DataFrame([['Such,Bob', ''],
['Ann', 'Davis'],
['Dole,Jerry', ''],
['Joan', 'Song']],
columns=["first_name", "last_name"])
```
Some of the names are incorrectly formated where the "first_name" is actually the person's (last name,first name) Write an ETL program that correctly formats names
into first_name and last_name, so all the cells are appropriately filled.
## Submission
After you finish the assignment you can submit your code with:
```
$ git push
```
'''
The etl module defines basic language primitives for manipulating Pandas
DataFrames. It takes a DataFrame in and outputs a transformed DataFrame.
You will implement several of the routines to perform these transformations.
Example Usage:
You can create DataFrame and create an ETL class that takes the DataFrame
as input.
>> df1 = pd.DataFrame([['Bob', 'Stewart'],
['Anna', 'Davis'],
['Jerry', 'Dole'],
['John', 'Marsh']],
columns=["first_name", "last_name"])
>> etl = ETL(df1)
The add() function creates a new column with a specified value:
>> etl.add(colname="age", 0)
>> pw1.df
first_name last_name age
0 Bob Stewart 0
1 Anna Davis 0
2 Jerry Dole 0
3 John Marsh 0
'''
import pandas as pd
import re
class ETL:
'''
The class that defines ETL transformations for a single dataframe
'''
def __init__(self, df: pd.DataFrame):
'''
ETL objects are constructed with a source
dataframe. These dataframes are manipulated
in-place.
'''
#how to access the source dataframe
self.df = df
#stores a history of the transformations to the df
self.transforms = []
def add(self, colname, x):
'''
The add(colname, x) function adds a column with the specified name
(colname) and a specified value (x). It adds this value to
all rows of the dataframe. We've implemented this as an
example to show you how to structure your ETL functions.
add *modifies* self.df as well as *returns* it
'''
#Test to see if colname is None, if so use a default colname
self.df[colname] = x
#append your changes to the transform list
self.transforms.append(self.df.copy(deep=True))
return self.df
def drop(self, colname):
'''
The drop(colname) function returns a DataFrame
with the column (colname) removed.
drop *modifies* self.df as well as *returns* it
'''
#YOUR CODE HERE
self.transforms.append(self.df.copy(deep=True))
return self.df
def copy(self, colname, new_colname):
'''
copy(colname, new_colname) duplicates a column and
saves it to the new_colname.
copy *modifies* self.df as well as *returns* it.
'''
#YOUR CODE HERE
self.transforms.append(self.df.copy(deep=True))
return self.df
def split(self, colname, new_colname, splitter):
'''
split(colname, new_colname, splitter) takes a column
splits the value on a delimiter. It replaces colname
with the substrings that appear before the delimiter
and puts the values after the delimiter in the
new_colname. If the string does not contain the delimiter
then new_colname is assigned an empty string.
split *modifies* self.df as well as *returns* it.
'''
#YOUR CODE HERE
self.transforms.append(self.df.copy(deep=True))
return self.df
def merge(self, col1, col2, splitter):
'''
merge(col1, col2, splitter) replaces col1
with the values of col1 and col2 concatenated,
and seperated by the delimiter. The delimiter is
ignored if either df.col1 or df.col2 is an empty
string.
merge *modifies* self.df as well as *returns* it.
'''
#YOUR CODE HERE
self.transforms.append(self.df.copy(deep=True))
return self.df
def format(self, colname, fn):
'''
format applies an input function to every value in colname. fn
is a *function*.
format *modifies* self.df as well as *returns* it.
'''
#YOUR CODE HERE
self.transforms.append(self.df.copy(deep=True))
return self.df
def divide(self, colname, new_colname1, new_colname2, condition):
'''
Divide conditionally divides a column, sending values that
satisfy the condition into one of two columns
(new_colname1 or new_colname2). condition is a Boolean function
of values.
See examples in the writeup.
'''
#YOUR CODE HERE
self.transforms.append(self.df.copy(deep=True))
return self.df
'''
Here, you will write programs that transform dataframes
using the functions that you wrote.
'''
def phone():
'''
Write an ETL program that results in a
dataframe with two columns: area_code, phone_number.
'''
df = pd.DataFrame([['(408)996-758'],
['+1 667 798 0304'],
['(774)998-758'],
['+1 442 030 9595']],
columns=["phoneno"])
etl = ETL(df)
#Your code goes here
return etl.df
def date():
'''
Write an ETL program that results in a
dataframe with three columns: day, month, year.
The day must be in two-digit format i.e, 01, 08.
The month must be the full month name, e.g., "May".
The year must be in YYYY format.
'''
df = pd.DataFrame([['03/2/1990'],
['2/14/1964'],
['1990-04-30'],
['7/9/2012'],
['1989-09-13'],
['1994-08-21'],
['1996-11-30'],
['2004-12-23'],
['4/21/2016']]
columns=["date"])
etl = ETL(df)
#Your code goes here
return etl.df
def name():
'''
Write an ETL program that correctly formats names
into first_name and last_name.
'''
df = pd.DataFrame([['Such,Bob', ''],
['Ann', 'Davis'],
['Dole,Jerry', ''],
['Joan', 'Song']],
columns=["first_name", "last_name"])
etl = ETL(df)
#Your code goes here
return etl.df
\ No newline at end of file
# Sketching
*Due 6/11/19 11:59 PM (for all students)*
*Due 6/6/19 11:59 PM (for all graduating seniors)*
In this assignment, you will revisit the IMDB dataset and explore approximate ways of counting distinct values.
## Getting Started
First, pull the most recent changes from the cmsc13600-public repository:
```
$ git pull
```
Then, copy the `hw4` folder to your submission repository. Change directories to enter your submission repository. Your code will go into `hyperloglog.py` this is the only file that you will modify. Finally, add `hyperloglog.py` using `git add`:
```
$ git add hyperloglog.py
$ git commit -m'initialized homework'
```
Now, you will need to fetch the data used in this assignment. Download title.csv put it in the hw4 folder:
https://www.dropbox.com/s/zl7yt8cl0lvajxg/title.csv?dl=0
DO NOT ADD title.csv to the git repo! After downloading the
dataset, there is a python module provided for you called `core.py`, which reads the dataset. This module loads the data in as
an iterator in two functions `imdb_years()` and `imdb_title_words()`:
```
>> for i in imdb_years():
... print(i)
1992
1986
<so on>
```
Play around with both `imdb_years()` and `imdb_title_words()` to get a feel for how the data works. You will also find it useful to install NumPy for this project:
```
$ pip3 install numpy
```
## Helper Functions
You will first write a series of helper functions to manipulate hash codes.
### hashcode(s)
The first function to implement is `hashcode(s)`. This function takes in a string and returns a a 32-bit unsigned integer. You will use the python function `hash(obj)` to implement this function. Hint: Python uses 64 bit integers and you will find the numpy library useful to converting the hash code into a 32 bit number.
### code2bin(code)
The next function to implement is `code2bin(code)`. This function takes in a 32-bit unsigned code from the previous example and turns it into a binary list of 32 1/0 values.
The list must be ordered from most significant to least significant bit, i.e., the most significant bit is the first element of the list.
### bin2code(lst)
This function takes in a 32-bit binary list and returns a unsigned 32-bit integer; assuming most significant bit first as before. This should be able to retrive your original code value!
### rho(lst)
The last helper function you will write is `rho(lst)` which returns the position of the left-most bit that is one. If there is no bit with the value one, just return the length of lst.
## HyperLogLog Algorithm
The gist of HyperLogLog is that it maintains a compressed array (`self.M`) that summarizes the data. For each record in your dataset, it updates this array. `self.b` determines how big this compressed array is. At the end it tries to reconstruct the distinct count from this array. You will write the `update(s)` function for HyperLogLog. The update function takes an input string `s` and updates self.M accordingly:
1. Calculate the hash code of s
2. Calculate the binary representation of the hashcode (call it c)
3. Split this binary representation into two sublists b- (the first b elements) and b+ (the remaining elements)
4. Use your helper functions to calculate j: the integer representation of (b-), and w: the position of the left-most bit in b+.
5. Update with `self.M[j] = max(self.M[j], w)`
## Testing and Submission
We have provided a basic wrapper in `test.py`, the test is incomplete and is not meant to comprehensively grade your assignment. If you follow directions closely you should usually be within 50 of the true count for `imdb_years()`. After you finish the assignment you can submit your code with:
```
$ git push
```
'''
The core module sets up the data structures and
and references for this programming assignment.
'''
import platform
import os
import json
if platform.system() == 'Windows':
print("This assignment will not work on a windows computer")
exit()
def imdb_title_words():
f = open('title.csv','r')
line = f.readline()
while line != "":
words = line.strip().split(',')[1].split()
for w in words:
yield w
line = f.readline()
f.close()
def imdb_years():
f = open('title.csv','r')
line = f.readline()
cnt = 0
while line != "":
csvsplit = line.strip().split(',')
year = csvsplit[len(csvsplit) - 8]
if year.strip() != "":
yield year
line = f.readline()
cnt += 1
f.close()
"""
The HyperLogLog algorithm is an algorithm designed to count the number
of distinct values in a set when the set is too large to fit in memory.
Like MinHash, it uses probabilistic methods to approximate the true
value of the distinct cardinality.
Write your implementation of the HyperLogLog algorithm here. The outline
of the algorithm can be found in the paper,
"HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm"
by Flajolet et al.
(http://algo.inria.fr/flajolet/Publications/FlFuGaMe07.pdf)
The assignment asks you to implement a simplification of this algorithm. Figure 3 in the
paper describes the whole algorithm
We will test your implementation against the IMDB dataset (title.csv) used in HW1. View
the tests.py file to see how the class will be used. The method skeletons provided are
for your convenience, but only the __init__, count, and update methods will be used for
tests.
Your implementation should run in less than 5 minutes. Do not use Python counting data
structures such as Counter, histograms, or dictionaries adapted for counting purposes.
"""
import numpy as np
# Step 1.
def hashcode(s):
'''
This function takes in a string and returns a a 32-bit
unsigned integer.
'''
#YOUR CODE GOES HERE!!!
pass
# Step 2.
def code2bin(code):
'''
This function takes in a 32-bit unsigned code from
the previous example and turns it into a binary
list of 32 1/0 values. The most significant bit is
the first element of the list.
'''
#YOUR CODE GOES HERE!!!
# Step 3.
def bin2code(lst):
'''
This function takes in a 32-bit binary list
and returns a unsigned 32-bit integer. Assuming
most significant bit first.
'''
#YOUR CODE GOES HERE!!!
#Step 4.
def rho(lst):
'''
Returns the position of the left-most bit
that is one.
'''
#YOUR CODE GOES HERE!!!
class HyperLogLog(object):
'''
HyperLogLog is an approximate distinct count
data structure.
'''
def __init__(self, b):
'''
Takes in an integer parameter b > 4 and less than 16
'''
self.b = b
self.M = [0]*(2 ** b)
#given to you don't worry about it
def get_alpha(self):
m = 2 ** self.b
if m == 16:
return 0.673
elif m == 32:
return 0.697
elif m == 64:
return 0.709
else:
return 0.7213/(1+ 1.079/m)
#given to you don't worry about it
def count(self):
m = 2 ** self.b
a = self.get_alpha()
reg_sum = 0
for j in range(0,m):
reg_sum += 2 ** (- self.M[j])
E = 2*a*(m**2)/reg_sum
return E
#your code
def update(self, s):
#YOUR CODE GOES HERE!!!
from hyperloglog import HyperLogLog
from core import imdb_years
from collections import Counter
def main_test():
y = HyperLogLog(b = 4)
z = Counter()
for i, w in enumerate(imdb_years()):
y.update(w.encode('utf-8'))
z[w] += 1
print("Implemented: {}\nTrue count: {}".format(y.count(), len(z)))
if __name__ == "__main__":
main_test()
# Submitting Homework Assignments
This document describes the basic procedure for completing and submitting homework assignments.
## Initial Setup
All of the coding exercises in this class with use Python3 (NOT Python 2!!!). Python 3 is installed on all of the CSIL machines and you can install it on your own computer by downloading it here:
[https://www.python.org/download/releases/3.0/]
On your personal computer, you probably navigate your hard drive by double clicking on icons. While convenient for simple tasks, this approach is limited. For example, imagine that you want to delete all of the music files over 5 MB that you haven't listened to in over a year. This task is very hard to do with the standard double-click interface but is relatively simple using the terminal. All of the instructions in this class will assume access to a terminal interface whether windows, linux, or macos. It is your responsibility to get familiar with using your available terminal.
There is a great tutorial linked here on accessing the Python interpreter from your command line:
[http://www.cs.bu.edu/courses/cs108/guides/runpython.html]
## Git
The purpose of Git is to manage a project, or a set of files, as they change over time. Git stores this information in a data structure called a repository. A git repository contains, among other things, the following: A set of commit objects. A set of references to commit objects, called heads.
Git is installed on all of the CSIL computers, and to install git on your machine follow the instructions here:
[https://git-scm.com/book/en/v2/Getting-Started-Installing-Git]
Every student in the class has a git repository (a place where you can store completed assignments). This git repository can be accessed from:
[https://mit.cs.uchicago.edu/cmsc13600-spr-19/<your cnetid>.git]
The first thing to do is to open your terminal application, and ``clone`` this repository (NOTE skr is ME, replace it with your CNET id!!!):
```
$ git clone https://mit.cs.uchicago.edu/cmsc13600-spr-19/skr.git cmsc13600-submit
```
Your username and id is your CNET id and CNET password. This will create a new folder that is empty titled cmsc13600-submit. There is similarly a course repository where all of the homework materials will stored. Youshould clone this repository as well:
```
$ git clone https://mit.cs.uchicago.edu/skr/cmsc13600-public.git cmsc13600-materials
```
This will create a new folder titled cmsc13600-materials. This folder will contain your homework assignments. Before you start an assingment you should sync your cloned repository with the online one:
```
$ cd cmsc13600-materials
$ git pull
```
Then, we will tell you which of the pulled materials to copy over to your repository (cmsc13600-submit). Typically, they will be self-contained in a single folder with an obvious title (like hw0).
Try this out on your own! Copy the folder ``using-git`` to your newly cloned submission repository. Enter that repository from the command line and enter the copied ``using-git`` folder. There should be a single file in the folder called ``README.md``. Once you copy over files to your submission repository, you can work on them all you want. Once you are done, you need to add ALL OF THE FILES YOU WISH TO SUBMIT:
```
$ git add README.md
```
After adding your files, to submit your code you must run:
```
$ git commit -m"My submission"
$ git push
```
We will NOT grade any code that is not added, committed, and pushed to your submission repository. You can confirm your submission by visiting the web interface[https://mit.cs.uchicago.edu/cmsc13600-spr-19/skr]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment