In [ ]:
import json
import gzip
import math
from collections import defaultdict
import numpy
from sklearn import linear_model
import random
import statistics
In [ ]:
def assertFloat(x):
    assert type(float(x)) == float

def assertFloatList(items, N):
    assert len(items) == N
    assert [type(float(x)) for x in items] == [float]*N
In [ ]:
answers = {}
In [ ]:
z = gzip.open("train.json.gz")
In [ ]:
dataset = []
for l in z:
    d = eval(l)
    dataset.append(d)
In [ ]:
z.close()
In [ ]:
### Question 1
In [ ]:
def MSE(y, ypred):
    
In [ ]:
def MAE(y, ypred):
    
In [ ]:
reviewsPerUser = defaultdict(list)
reviewsPerItem = defaultdict(list)

for d in dataset:
    u,i = d['userID'],d['gameID']
    reviewsPerUser[u].append(d)
    reviewsPerItem[i].append(d)
    
for u in reviewsPerUser:
    reviewsPerUser[u].sort(key=lambda x: x['date'])
    
for i in reviewsPerItem:
    reviewsPerItem[i].sort(key=lambda x: x['date'])
In [ ]:
def feat1(d):
    
In [ ]:
X = 
y = 
In [ ]:
mod = 
mod.fit(X,y)
predictions = 
In [ ]:
 
In [ ]:
answers['Q1'] = [theta_1, mse_q1]
In [ ]:
assertFloatList(answers['Q1'], 2)
In [ ]:
### Question 2
In [ ]:
 
In [ ]:
def feat2(d):
    
In [ ]:
X = [feat2(d) for d in dataset]
In [ ]:
mod = linear_model.LinearRegression(fit_intercept=False)
mod.fit(X,y)
predictions = mod.predict(X)
In [ ]:
 
In [ ]:
answers['Q2'] = mse_q2
In [ ]:
assertFloat(answers['Q2'])
In [ ]:
### Question 3
In [ ]:
def feat3(d):
    
In [ ]:
X = [feat3(d) for d in dataset]
In [ ]:
mod = linear_model.LinearRegression(fit_intercept=False)
mod.fit(X,y)
predictions = mod.predict(X)
In [ ]:
 
In [ ]:
answers['Q3'] = mse_q3
In [ ]:
assertFloat(answers['Q3'])
In [ ]:
### Question 4
In [ ]:
def feat4(d):
    
In [ ]:
X = [feat4(d) for d in dataset]
y = 
In [ ]:
mod = linear_model.LinearRegression(fit_intercept=False)
mod.fit(X,y)
predictions = mod.predict(X)
In [ ]:
mse = 
mae = 
In [ ]:
 
In [ ]:
answers['Q4'] = [mse, mae, "explain which is better"]
In [ ]:
assertFloatList(answers['Q4'][:2], 2)
In [ ]:
### Question 5
In [ ]:
 
In [ ]:
y_trans = 
In [ ]:
mod = linear_model.LinearRegression(fit_intercept=False)
mod.fit(X,y_trans)
predictions_trans = mod.predict(X)
In [ ]:
mse_trans = # MSE using the transformed variable
In [ ]:
 
In [ ]:
predictions_untrans = # Undoing the transformation
In [ ]:
mse_untrans = 
In [ ]:
answers['Q5'] = [mse_trans, mse_untrans]
In [ ]:
assertFloatList(answers['Q5'], 2)
In [ ]:
### Question 6
In [ ]:
def feat6(d):
    
In [ ]:
X = [feat6(d) for d in dataset]
y = [len(d['text']) for d in dataset]
In [ ]:
Xtrain, Xvalid, Xtest = X[:len(X)//2], X[len(X)//2:(3*len(X))//4], X[(3*len(X))//4:]
ytrain, yvalid, ytest = y[:len(X)//2], y[len(X)//2:(3*len(X))//4], y[(3*len(X))//4:]
In [ ]:
models = {}
mses = {}
bestC = None

for c in [1, 10, 100, 1000, 10000]:
    
In [ ]:
 
In [ ]:
predictions_test = 
In [ ]:
mse_valid = 
In [ ]:
mse_test = 
In [ ]:
answers['Q6'] = [bestC, mse_valid, mse_test]
In [ ]:
assertFloatList(answers['Q6'], 3)
In [ ]:
### Question 7
In [ ]:
times = [d['hours_transformed'] for d in dataset]
median = statistics.median(times)
In [ ]:
 
In [ ]:
notPlayed = 
nNotPlayed = 
In [ ]:
answers['Q7'] = [median, nNotPlayed]
In [ ]:
assertFloatList(answers['Q7'], 2)
In [ ]:
### Question 8
In [ ]:
def feat8(d):
    
In [ ]:
X = [feat8(d) for d in dataset]
y = [d['hours_transformed'] > median for d in dataset]
In [ ]:
mod = linear_model.LogisticRegression(class_weight='balanced')
mod.fit(X,y)
predictions = mod.predict(X) # Binary vector of predictions
In [ ]:
def rates(predictions, y):
    
    return TP, TN, FP, FN
In [ ]:
TP, TN, FP, FN = rates(predictions, y)
In [ ]:
BER = 
In [ ]:
answers['Q8'] = [TP, TN, FP, FN, BER]
In [ ]:
assertFloatList(answers['Q8'], 5)
In [ ]:
### Question 9
In [ ]:
precision = 
recall = 
In [ ]:
 
In [ ]:
precs = []
recs = []

for i in [5, 10, 100, 1000]:
    
In [ ]:
answers['Q9'] = precs
In [ ]:
assertFloatList(answers['Q9'], 4)
In [ ]:
### Question 10
In [ ]:
y_trans = [d['hours_transformed'] for d in dataset]
In [ ]:
mod = linear_model.LinearRegression(fit_intercept=False)
mod.fit(X,y_trans)
predictions_trans = mod.predict(X)
In [ ]:
predictions_thresh = # Using a fixed threshold to make predictions
In [ ]:
TP, TN, FP, FN = 
In [ ]:
BER = 
In [ ]:
answers['Q10'] = [your_threshold, BER]
In [ ]:
assertFloatList(answers['Q10'], 2)
In [ ]:
### Question 11
In [ ]:
dataTrain = dataset[:int(len(dataset)*0.9)]
dataTest = dataset[int(len(dataset)*0.9):]
In [ ]:
userMedian = defaultdict(list)
itemMedian = defaultdict(list)

# Compute medians on training data
In [ ]:
 
In [ ]:
answers['Q11'] = [itemMedian['g35322304'], userMedian['u55351001']]
In [ ]:
assertFloatList(answers['Q11'], 2)
In [ ]:
### Question 12
In [ ]:
def f12(u,i):
    # Function returns a single value (0 or 1)
In [ ]:
preds = [f12(d['userID'], d['gameID']) for d in dataTest]
In [ ]:
y = 
In [ ]:
accuracy = 
In [ ]:
answers['Q12'] = accuracy
In [ ]:
assertFloat(answers['Q12'])
In [ ]:
### Question 13
In [ ]:
usersPerItem = defaultdict(set) # Maps an item to the users who rated it
itemsPerUser = defaultdict(set) # Maps a user to the items that they rated
itemNames = {}

for d in dataset:
    user,item = d['userID'], d['gameID']
    usersPerItem[item].add(user)
    itemsPerUser[user].add(item)
In [ ]:
def Jaccard(s1, s2):
    
In [ ]:
def mostSimilar(i, func, N):
    
In [ ]:
ms = mostSimilar(dataset[0]['gameID'], Jaccard, 10)
In [ ]:
answers['Q13'] = [ms[0][0], ms[-1][0]]
In [ ]:
assertFloatList(answers['Q13'], 2)
In [ ]:
### Question 14
In [ ]:
def mostSimilar14(i, func, N):
    
In [ ]:
ratingDict = {}

for d in dataset:
    u,i = d['userID'], d['gameID']
    lab = # Set the label based on a rule
    ratingDict[(u,i)] = lab
In [ ]:
def Cosine(i1, i2):
    # Between two items
In [ ]:
ms = mostSimilar14(dataset[0]['gameID'], Cosine, 10)
In [ ]:
answers['Q14'] = [ms[0][0], ms[-1][0]]
In [ ]:
assertFloatList(answers['Q14'], 2)
In [ ]:
### Question 15
In [ ]:
ratingDict = {}

for d in dataset:
    u,i = d['userID'], d['gameID']
    lab = # Set the label based on a rule
    ratingDict[(u,i)] = lab
In [ ]:
ms = mostSimilar14(dataset[0]['gameID'], Cosine, 10)
In [ ]:
answers['Q15'] = [ms[0][0], ms[-1][0]]
In [ ]:
assertFloatList(answers['Q15'], 2)
In [ ]:
f = open("answers_midterm.txt", 'w')
f.write(str(answers) + '\n')
f.close()
In [ ]: