Создание прогноза из модели, генерируемой алгоритмом дерева решений - PullRequest
1 голос
/ 26 октября 2019

Я пытался сделать прогноз, который состоит из DataFrame из модели, которую я сделал с использованием алгоритма дерева решений.

Я получил оценку для моей модели, которая составляет 0,96. Затем я попытался использовать модель, чтобы сделать прогноз от людей из DataFrame, которые остались, но получили ошибку. Цель состоит в том, чтобы предсказать людей, которые покинут компанию в будущем, на основе DataFrame, которые останутся.

Как достичь этой цели?

Итак, что я сделал:

  1. Прочитайте DF из моего github и разделите их на людей, которые ушли, а не оставили
df = pd.read_csv('https://raw.githubusercontent.com/bhaskoro-muthohar/DataScienceLearning/master/HR_comma_sep.csv')

leftdf = df[df['left']==1]
notleftdf =df[df['left']==0]
Подготовка данных для генерации модели
df.salary = df.salary.map({'low':0,'medium':1,'high':2})
df.salary
X = df.drop(['left','sales'],axis=1)
y = df['left']
разделение поезда и тестовых наборов
import numpy as np
from sklearn.model_selection import train_test_split


#splitting the train and test sets
X_train, X_test, y_train, y_test= train_test_split(X,y,random_state=0, stratify=y)
Тренируйся
from sklearn import tree
clftree = tree.DecisionTreeClassifier(max_depth=3)
clftree.fit(X_train,y_train)
Оценка модели
y_pred = clftree.predict(X_test)
print("Test set prediction:\n {}".format(y_pred))
print("Test set score: {:.2f}".format(clftree.score(X_test, y_test)))

Результат

Оценка тестового набора: 0,96

Затем я пытаюсь сделать прогноз, используя DataFrame от людей, которые еще не покинули компанию
X_new = notleftdf.drop(['left','sales'],axis=1)

#Map salary to 0,1,2
X_new.salary = X_new.salary.map({'low':0,'medium':1,'high':2})
X_new.salary
prediction_will_left = clftree.predict(X_new)
print("Prediction: {}".format(prediction_will_left))
print("Predicted target name: {}".format(
    notleftdf['left'][prediction_will_left]
))

Ошибка, которую я получил:

KeyError: "None of [Int64Index([0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n            ...\n            0, 0, 0, 0, 0, 0, 1, 0, 0, 0],\n           dtype='int64', length=11428)] are in the [index]"

Как ее решить?

PS: Для полной ссылки на скрипт здесь

1 Ответ

1 голос
/ 26 октября 2019

Может быть, вы ищете что-то вроде этого. (Автономный скрипт после загрузки файла данных в тот же каталог.)

from sklearn import tree
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd


def process_df_for_ml(df):
    """
    Process a dataframe for model training/prediction use.

    Returns X/y tensors.
    """

    df = df.copy()
    # Map salary to 0,1,2
    df.salary = df.salary.map({"low": 0, "medium": 1, "high": 2})
    # dropping left and sales X for the df, y for the left
    X = df.drop(["left", "sales"], axis=1)
    y = df["left"]
    return (X, y)

# Read and reindex CSV.
df = pd.read_csv("HR_comma_sep.csv")
df = df.reindex()

# Train a decision tree.
X, y = process_df_for_ml(df)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y)
clftree = tree.DecisionTreeClassifier(max_depth=3)
clftree.fit(X_train, y_train)

# Test the decision tree on people who haven't left yet.
notleftdf = df[df["left"] == 0].copy()
X, y = process_df_for_ml(notleftdf)
# Plug in a new column with ones and zeroes from the prediction.
notleftdf["will_leave"] = clftree.predict(X)
# Print those with the will-leave flag on.
print(notleftdf[notleftdf["will_leave"] == 1])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...