コーセラ| Pythonでの応用機械学習(ミシガン大学)| 課題4

   すべての課題関連リンク:
  Coursera | Pythonでの応用機械学習(ミシガン大学)| Assignment1
  Coursera | Pythonでの応用機械学習(ミシガン大学)| Assignment2
  Coursera | Pythonでの応用機械学習(ミシガン大学)| Assignment3
  Coursera | Applied Pythonでの機械学習(ミシガン大学)|課題4
   時間があるときにすべてのコードをgithubに配置する(需要がある)
   ところで、自分のブログを宣伝してください。今後のCSDNの記事は自分のブログに投稿されます。

コーセラ| Pythonでの応用機械学習(ミシガン大学)| 課題4

   話を続けてください、これは難しいことではありませんが、要件を満たすのに長い時間がかかりました。みんな参考です〜


現在、このノートブックのバージョン1.1見ています。ノートブックとデータファイルをダウンロードしたり、CourseraプラットフォームでJupyterノートブックのヘルプを入手したりするには、Jupyter NotebookFAQコースリソースにアクセスしてください


課題4-資産維持の罰金の理解と予測

この割り当ては、ミシガンデータサイエンスチーム(MDSTからのデータチャレンジに基づいています

ミシガンデータサイエンスチーム(MDST)とミシガン学際統計科学学生シンポジウム(MSSISS)は、デトロイト市と提携して、デトロイトが直面している最も差し迫った問題の1つであるblightの解決を支援しています。市は、所有物を劣化した状態に保つことを許可した個人に、ブライト違反を発行します。デトロイト市は毎年、住民に数百万ドルの罰金を科しており、毎年、これらの罰金の多くは未払いのままです。未払いのブライト罰金を科すのは費用がかかり退屈なプロセスであるため、市は知りたがっています。ブライトチケットのコンプライアンスをどのように高めることができるでしょうか。

この質問に答える最初のステップは、居住者がいつ、なぜブライトチケットに従わないのかを理解することです。ここで予測モデリングが役立ちます。この割り当てでは、特定のブライトチケットが時間どおりに支払われるかどうかを予測することがタスクです。

この割り当てのすべてのデータは、デトロイトオープンデータポータルを通じて提供されています。この割り当てのモデルのトレーニングに使用できるのは、Courseraディレクトリにすでに含まれているデータのみです。それでも、他のデトロイトデータセットのデータを調べて、特徴の作成とモデルの選択に役立てることをお勧めします。次の関連データセットを確認することをお勧めします。


モデルのトレーニングと検証に使用する2つのデータファイルtrain.csvとtest.csvを提供します。これら2つのファイルの各行は、1つのブライトチケットに対応し、各チケットがいつ、なぜ、誰に発行されたかに関する情報が含まれています。ターゲット変数はコンプライアンスです。これは、チケットがヒアリングデータの早期、期限内、または1か月以内に支払われた場合は真、ヒアリング日以降にチケットが支払われたかまったく支払われなかった場合はFalse、違反者が見つかった場合はNullです。責任を負いません。コンプライアンス、およびテスト時に使用できないその他のいくつかの変数は、train.csvにのみ含まれています。

注:違反者が責任を負わないことが判明したすべてのチケットは、評価時に考慮されません。これらは、視覚化のための追加のデータソースとして、および教師なしおよび半教師ありアプローチを可能にするために、トレーニングセットに含まれています。ただし、これらはテストセットには含まれていません。


ファイルの説明(モデルのトレーニングにはこのデータのみを使用してください!)

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.

データフィールド

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ドルの料金
late_fee-責任ある判断に割り当てられた10%の料金
discount_amount-割引が適用された場合、
clean_up_cost-DPWのクリーンアップまたは落書きの削除費用
judgment_amount-すべての罰金と料金の
合計grafitti_status-落書き違反のフラグ

train.csvのみ

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

評価

あなたの予測は、対応するブライトチケットが時間通りに支払われる確率として与えられます。

この割り当ての評価指標は、ROC曲線下面積(AUC)です。

成績は、分類子に対して計算されたAUCスコアに基づきます。AUROCが0.7のモデルがこの割り当てに合格すると、0.75を超えるとフルポイントを獲得します。


この割り当てでは、を使用してデトロイトのブライトチケットコンプライアンスを予測するモデルをトレーニングする関数を作成しますreadonly/train.csvこのモデルを使用して、一連の長さ61001を返します。データは、対応する各チケットreadonly/test.csvが支払われる確率であり、インデックスはticket_idです。

例:

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

ヒント

  • オートグレーダーに送信する前に、コードが機能していることを確認してください。

  • 結果を印刷して、何か奇妙なことがあるかどうかを確認します(たとえば、すべての確率が同じです)。

  • 通常、合計実行時間は10分未満である必要があります。この質問では、ニューラルネットワーク関連の分類子(MLPClassifierなど)を使用しないでください。

  • グローバル変数を避けるようにしてください。blight_model以外の関数がある場合は、それらの関数をblight_modelのスコープ内に移動する必要があります。

  • 理解できないことがある場合は、第4週のディスカッションフォーラムで固定されたスレッドを参照してください。

コード

import pandas as pd
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import roc_auc_score
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import GridSearchCV

def blight_model():
    # Load and clean data
    train_data = pd.read_csv('train.csv', encoding = 'ISO-8859-1')
    test_data = pd.read_csv('test.csv')
    address =  pd.read_csv('addresses.csv')
    latlons = pd.read_csv('latlons.csv')
    address_lalo = address.set_index('address').join(latlons.set_index('address'), how='left').dropna().reset_index(drop=False)
    
    train_data=pd.merge(train_data, address_lalo, on='ticket_id').set_index('ticket_id')
    test_data=pd.merge(test_data, address_lalo, on='ticket_id',how='left').set_index('ticket_id')
    test_data['lat'].fillna(method='pad', inplace=True)
    test_data['lon'].fillna(method='pad', inplace=True)
    
    train_data = train_data[(train_data['compliance'] == 0) | (train_data['compliance'] == 1)]
    train_data['compliance']=train_data['compliance'].astype(int)
    
    # Calculate time gap
    from datetime import datetime
    def time_gap(hearing_date_str, ticket_issued_date_str):
        if not hearing_date_str or type(hearing_date_str)!=str: return 73
        hearing_date = datetime.strptime(hearing_date_str, "%Y-%m-%d %H:%M:%S")
        ticket_issued_date = datetime.strptime(ticket_issued_date_str, "%Y-%m-%d %H:%M:%S")
        gap = hearing_date - ticket_issued_date
        return gap.days
    train_data['time_gap'] = train_data.apply(lambda row: time_gap(row['hearing_date'], row['ticket_issued_date']), axis=1)
    test_data['time_gap'] = test_data.apply(lambda row: time_gap(row['hearing_date'], row['ticket_issued_date']), axis=1)
    
    # Reomove train only columns
    trainOnly_columns = [
        'payment_amount', 'payment_date', 'payment_status', 'balance_due',
        'collection_status', 'compliance_detail'
    ]
    train_data.drop(trainOnly_columns, axis=1, inplace=True)
    
    # Feature used to train
    feature_columns = [
        'agency_name',
        'violation_street_name',
        'state',
        'violation_code',
        'late_fee',
        'fine_amount',
        'discount_amount',
        'judgment_amount',
        'lat',
        'lon',
        'time_gap'#'ticket_issued_date', 'hearing_date'
    ]

    convert_columns = {
    
    
        'agency_name':'category',
        'violation_street_name':'category',
        'state':'category',
        'violation_code':'category',
        'disposition':'category',
    }
    
    for df in [train_data,test_data]:
        for col, col_type in convert_columns.items():
            if col in df:
                if col_type == 'category':
                    df[col] = df[col].astype(col_type)
                    
    # Convert cetegory columns to integers
    cat_columns = train_data.select_dtypes(['category']).columns
    for df in [train_data,test_data]:
        df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)

    # Spilt
    X = train_data[feature_columns].copy()
    y = train_data['compliance']
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
    

    test = test_data[feature_columns].copy()
    
    # Train the model
    GBC = GradientBoostingClassifier(learning_rate = 0.1, max_depth = 5, random_state = 0).fit(X_train, y_train)
    
    y_score_GBC = GBC.decision_function(X_test)
    fpr_GBC, tpr_GBC, _ = roc_curve(y_test, y_score_GBC)
    roc_auc_GBC  = auc(fpr_GBC, tpr_GBC)
    accuracy_GBC = GBC.score(X_test, y_test)
    print("accuracy = {:.4f}   AUC = {:.4f}".format(accuracy_GBC,  roc_auc_GBC))
    
    y_proba = GBC.predict_proba(test)[:,1]
    test['compliance'] = y_proba
    
    return test['compliance']

    
    # Another way
    #     grid_values = {'learning_rate': [0.01, 0.1], 'max_depth': [3, 5]}
    #     clf = GradientBoostingClassifier(random_state = 0)
    #     grid_clf_auc = GridSearchCV(clf, param_grid = grid_values, scoring = 'roc_auc')
    #     grid_clf_auc.fit(X_train, y_train)

    #     probs = grid_clf_auc.predict_proba(test)[:, 1]
    #     result = pd.Series(probs, index=test.index)

    #     return result
blight_model()
accuracy = 0.9346   AUC = 0.7943

ticket_id
284932    0.085164
285362    0.017509
285361    0.071615
285338    0.081694
285346    0.093148
            ...   
376496    0.018970
376497    0.018970
376499    0.071046
376500    0.071046
369851    0.294378
Name: compliance, Length: 61001, dtype: float64

AutoGraderの結果


0.787592334899のAUCには、1.0の合計成績のうち1.0の値が与えられました。

おすすめ

転載: blog.csdn.net/weixin_43360896/article/details/111084033