You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.


Assignment 4 - Understanding and Predicting Property Maintenance Fines

This assignment is based on a data challenge from the Michigan Data Science Team (MDST).

The Michigan Data Science Team (MDST) and the Michigan Student Symposium for Interdisciplinary Statistical Sciences (MSSISS) have partnered with the City of Detroit to help solve one of the most pressing problems facing Detroit - blight. Blight violations are issued by the city to individuals who allow their properties to remain in a deteriorated condition. Every year, the city of Detroit issues millions of dollars in fines to residents and every year, many of these fines remain unpaid. Enforcing unpaid blight fines is a costly and tedious process, so the city wants to know: how can we increase blight ticket compliance?

The first step in answering this question is understanding when and why a resident might fail to comply with a blight ticket. This is where predictive modeling comes in. For this assignment, your task is to predict whether a given blight ticket will be paid on time.

All data for this assignment has been provided to us through the Detroit Open Data Portal. Only the data already included in your Coursera directory can be used for training the model for this assignment. Nonetheless, we encourage you to look into data from other Detroit datasets to help inform feature creation and model selection. We recommend taking a look at the following related datasets:


We provide you with two data files for use in training and validating your models: train.csv and test.csv. Each row in these two files corresponds to a single blight ticket, and includes information about when, why, and to whom each ticket was issued. The target variable is compliance, which is True if the ticket was paid early, on time, or within one month of the hearing data, False if the ticket was paid after the hearing date or not at all, and Null if the violator was found not responsible. Compliance, as well as a handful of other variables that will not be available at test-time, are only included in train.csv.

Note: All tickets where the violators were found not responsible are not considered during evaluation. They are included in the training set as an additional source of data for visualization, and to enable unsupervised and semi-supervised approaches. However, they are not included in the test set.


File descriptions (Use only this data for training your model!)

readonly/train.csv - the training set (all tickets issued 2004-2011)
readonly/test.csv - the test set (all tickets issued 2012-2016)
readonly/addresses.csv & readonly/latlons.csv - mapping from ticket id to addresses, and from addresses to lat/lon coordinates. 
 Note: misspelled addresses may be incorrectly geolocated.


Data fields

train.csv & test.csv

ticket_id - unique identifier for tickets
agency_name - Agency that issued the ticket
inspector_name - Name of inspector that issued the ticket
violator_name - Name of the person/organization that the ticket was issued to
violation_street_number, violation_street_name, violation_zip_code - Address where the violation occurred
mailing_address_str_number, mailing_address_str_name, city, state, zip_code, non_us_str_code, country - Mailing address of the violator
ticket_issued_date - Date and time the ticket was issued
hearing_date - Date and time the violator's hearing was scheduled
violation_code, violation_description - Type of violation
disposition - Judgment and judgement type
fine_amount - Violation fine amount, excluding fees
admin_fee - $20 fee assigned to responsible judgments

state_fee - $10 fee assigned to responsible judgments late_fee - 10% fee assigned to responsible judgments discount_amount - discount applied, if any clean_up_cost - DPW clean-up or graffiti removal cost judgment_amount - Sum of all fines and fees grafitti_status - Flag for graffiti violations

train.csv only

payment_amount - Amount paid, if any
payment_date - Date payment was made, if it was received
payment_status - Current payment status as of Feb 1 2017
balance_due - Fines and fees still owed
collection_status - Flag for payments in collections
compliance [target variable for prediction] 
 Null = Not responsible
 0 = Responsible, non-compliant
 1 = Responsible, compliant
compliance_detail - More information on why each ticket was marked compliant or non-compliant



Evaluation

Your predictions will be given as the probability that the corresponding blight ticket will be paid on time.

The evaluation metric for this assignment is the Area Under the ROC Curve (AUC).

Your grade will be based on the AUC score computed for your classifier. A model which with an AUROC of 0.7 passes this assignment, over 0.75 will recieve full points.


For this assignment, create a function that trains a model to predict blight ticket compliance in Detroit using readonly/train.csv. Using this model, return a series of length 61001 with the data being the probability that each corresponding ticket from readonly/test.csv will be paid, and the index being the ticket_id.

Example:

ticket_id
   284932    0.531842
   285362    0.401958
   285361    0.105928
   285338    0.018572
             ...
   376499    0.208567
   376500    0.818759
   369851    0.018528
   Name: compliance, dtype: float32

Hints

  • Make sure your code is working before submitting it to the autograder.

  • Print out your result to see whether there is anything weird (e.g., all probabilities are the same).

  • Generally the total runtime should be less than 10 mins. You should NOT use Neural Network related classifiers (e.g., MLPClassifier) in this question.

  • Try to avoid global variables. If you have other functions besides blight_model, you should move those functions inside the scope of blight_model.

  • Refer to the pinned threads in Week 4's discussion forum when there is something you could not figure it out.

In [12]:
import pandas as pd
import numpy as np
from sklearn.linear_model import LogisticRegression

def blight_model():
    
    train = pd.read_csv('train.csv', encoding = 'ISO-8859-1', low_memory = False)
    test = pd.read_csv('test.csv', encoding = 'ISO-8859-1', low_memory = False)
    addresses = pd.read_csv('addresses.csv')
    latlons = pd.read_csv('latlons.csv')
    
    train = train[pd.notnull(train['compliance'])]
    train = train.merge(addresses, on = 'ticket_id').merge(latlons, on = 'address')
    train = train[pd.notnull(train['lat'])]
    train.set_index(['ticket_id'], inplace=True)
    X_train = train[['agency_name',
                     'disposition',
                     'fine_amount',
                     'discount_amount',
                     'judgment_amount',
                     'lat',
                     'lon']]
    y_train = train.iloc[:,32]
    

    test = test.merge(addresses, on = 'ticket_id').merge(latlons, on = 'address')
    test.set_index(['ticket_id'], inplace=True)
    test = test[['agency_name',
                 'disposition',
                 'fine_amount',
                 'discount_amount',
                 'judgment_amount',
                 'lat',
                 'lon']]
    
    replace_test = list(test[pd.isnull(test['lat'])].index)
    X_train = pd.get_dummies(X_train, columns=["agency_name", "disposition"], prefix=["ag", "di"])
    X_train.insert(loc = 10, column = 'di_Responsible (Fine Waived) by Admis', value = [0] * len(X_train))
    X_train.insert(loc = 12, column = 'di_Responsible - Compl/Adj by Default', value = [0] * len(X_train))
    X_train.insert(loc = 13, column = 'di_Responsible - Compl/Adj by Determi', value = [0] * len(X_train))
    X_train['di_Responsible by Dismissal'] = 0
  
    test = pd.get_dummies(test, columns=["agency_name", "disposition"], prefix=["ag", "di"])
    test.insert(loc = 8, column = 'ag_Health Department', value = [0] * len(test))
    test.insert(loc = 9, column = 'ag_Neighborhood City Halls', value = [0] * len(test))

    import re
    for x in list(range(len(latlons))):
        if re.search(r'20417 bramford', latlons.iloc[x]['address']):
            bramford_lat_1 = latlons.iloc[x][1]
            bramford_lon_1 = latlons.iloc[x][2]
        elif re.search(r'20430 bramford', latlons.iloc[x]['address']):
            test.at[replace_test[0], 'lat'] = (bramford_lat_1 + latlons.iloc[x][1]) / 2
            test.at[replace_test[0], 'lon'] = (bramford_lon_1 + latlons.iloc[x][2]) / 2
        elif re.search(r'8325 joy rd', latlons.iloc[x]['address']):
            test.at[replace_test[1], 'lat'] = latlons.iloc[x][1]
            test.at[replace_test[1], 'lon'] = latlons.iloc[x][2]
        elif re.search(r'1201 elijah mccoy', latlons.iloc[x]['address']):
            test.at[replace_test[2], 'lat'] = latlons.iloc[x][1]
            test.at[replace_test[2], 'lon'] = latlons.iloc[x][2]
        elif re.search(r'12038 prairie,', latlons.iloc[x]['address']):
            test.at[replace_test[3], 'lat'] = latlons.iloc[x][1]
            test.at[replace_test[3], 'lon'] = latlons.iloc[x][2]
        #elif re.search(r'6200 16th st', latlons.iloc[x]['address']):
            test.at[replace_test[4], 'lat'] = latlons.iloc[x][1]
            test.at[replace_test[4], 'lon'] = latlons.iloc[x][2]
        
    y_predict = LogisticRegression(max_iter = 1000).fit(X_train, y_train).predict_proba(test)[:,1]
    answer = pd.DataFrame(y_predict, index = test.index)
    return X_train
In [13]:
blight_model()
Out[13]:
fine_amount discount_amount judgment_amount lat lon ag_Buildings, Safety Engineering & Env Department ag_Department of Public Works ag_Detroit Police Department ag_Health Department ag_Neighborhood City Halls di_Responsible (Fine Waived) by Admis di_Responsible (Fine Waived) by Deter di_Responsible - Compl/Adj by Default di_Responsible - Compl/Adj by Determi di_Responsible by Admission di_Responsible by Default di_Responsible by Determination di_Responsible by Dismissal
ticket_id
22056 250.0 0.0 305.0 42.390729 -83.124268 1 0 0 0 0 0 0 0 0 0 1 0 0
77242 500.0 0.0 580.0 42.390729 -83.124268 1 0 0 0 0 0 0 0 0 0 1 0 0
77243 250.0 0.0 305.0 42.390729 -83.124268 1 0 0 0 0 0 0 0 0 0 1 0 0
138219 100.0 0.0 140.0 42.390729 -83.124268 0 1 0 0 0 0 0 0 0 0 1 0 0
177558 300.0 0.0 360.0 42.390729 -83.124268 1 0 0 0 0 0 0 0 0 0 1 0 0
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
284874 100.0 0.0 140.0 42.439131 -83.070548 0 0 1 0 0 0 0 0 0 0 1 0 0
285091 50.0 0.0 85.0 42.394788 -83.214473 0 1 0 0 0 0 0 0 0 0 1 0 0
285508 0.0 0.0 0.0 42.393397 -83.211176 0 1 0 0 0 0 1 0 0 0 0 0 0
285106 200.0 0.0 250.0 42.440228 -83.154829 0 1 0 0 0 0 0 0 0 0 1 0 0
285125 500.0 0.0 580.0 42.366529 -83.141897 0 1 0 0 0 0 0 0 0 0 1 0 0

159878 rows × 18 columns