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: 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.
```
>> i1 = [ 1,7,2,4,6, ... ] # iterable There is a great tutorial linked here on accessing the Python interpreter from your command line:
>> i2 = [ 3,6,7,2,1, ... ] # iterable [http://www.cs.bu.edu/courses/cs108/guides/runpython.html]
>> i3 = [ 10,6,1,2,3, ... ] # iterable
``` ## 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 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:
three iterators. The order is not important
``` ```
>> for i in threeWayIter: $ git clone https://mit.cs.uchicago.edu/skr/cmsc13600-public.git cmsc13600-materials
... print(i)
[2,2,2]
[1,1,1]
[6,6,6]
``` ```
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:
## 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:
``` ```
$ cd cmsc13600-materials
$ git pull $ 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 add README.md
$ git commit -m'initialized homework'
``` ```
After adding your files, to submit your code you must run:
## 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:
``` ```
$ git commit -m"My submission"
$ git push $ 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
```
'''
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