마지막으로 결과를 분석한다.

    train_pred = model.predict(X_train)
    train_rmse = np.sqrt(mean_squared_error(y_train, train_pred))
    test_pred = model.predict(X_test)
    test_rmse = np.sqrt(mean_squared_error(y_test, test_pred))
    print("Train RMSE: {:0.2f}".format(train_rmse))
    print("Test RMSE: {:0.2f}".format(test_rmse))
     
    def predict_random(df_prescaled, X_test, model):
        sample = X_test.sample(n=1, random_state=np.random.randint(low=0, high=10000))
        idx = sample.index[0]
        actual_fare = df_prescaled.loc[idx,'fare_amount']
        day_names = ['Monday','Tuesday','Wednesday','Thursday','Friday', 'Saturday','Sunday']
        day_of_week = day_names[df_prescaled.loc[idx,'day_of_week']]
        hour = df_prescaled.loc[idx,'hour']
        predicted_fare = model.predict(sample)[0][0]
        rmse = np.sqrt(np.square(predicted_fare-actual_fare))
        print("Trip Details: {}, {}:00hrs".format(day_of_week, hour))
        print("Actual fare: ${:0.2f}".format(actual_fare))
        print("Predicted fare: ${:0.2f}".format(predicted_fare))
        print("RMSE: ${:0.2f}".format(rmse))
     
    predict_random(df_prescaled, X_test, model)

    여기까지 예제 코드를 모두 살펴봤다. 데이터 전처리와 특징 공학 과정을 utils.py에 헬퍼 함수로 구현한 덕분에 main.py를 비교적 간결하게 작성할 수 있다. 이처럼 헬퍼 함수를 사용해 코드를 모듈화하면 머신 러닝의 각 단계에 더 집중할 수 있다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.