<jupyter_start><jupyter_text>INTRODUCTION- Data contain different variable that are sub classified further:- 1.Demographics of the Employee 2.Tenure Information 3.Historical data regarding performance- Using these data we will going to find out whether employee will stay in the company and also will see another pattern with respect to time period of person stay in the company. There are other aspects also see in the notebook you can check in visualization part.- Using this data HR department will find out easily what type of candidate they need to take for particular job role. LIBRARIES<jupyter_code># This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes = True)
%matplotlib inline<jupyter_output><empty_output><jupyter_text>IMPORT_DATA 2.Import Data<jupyter_code>train = pd.read_csv('/kaggle/input/predicting-employee-attrition/train_data.csv')
train.head()<jupyter_output><empty_output><jupyter_text>DATA_PREPROCESSING 3. Data Preprocessing<jupyter_code>train.isnull().sum()
train['Target']=np.where(train['LastWorkingDate'].isnull(),0,1)
train.head()
emp_groupby = train.groupby(['Emp_ID'])['Emp_ID','Age','Gender','City','Education_Level','Salary','Joining Designation','Designation',
                       'Quarterly Rating','Target'].tail(1)
emp_groupby
emp_groupby.reset_index(inplace = True,drop = True)
emp_groupby
total_busi_groupby = train.groupby('Emp_ID').agg({'Total Business Value':'sum'})
total_busi_groupby
total_busi_groupby.reset_index(drop = True,inplace = True)
final = pd.concat([total_busi_groupby,emp_groupby],axis = 1,join = 'inner')
final
corr = final.corr()

plt.figure(figsize = (20,8))
sns.heatmap(corr,annot = True,cmap = 'rocket')<jupyter_output><empty_output><jupyter_text>DATA_VISUALIZATION 4.Data Visualization<jupyter_code>sns.catplot('Gender','Total Business Value',hue = 'Education_Level',data = final,col = 'Education_Level',col_wrap = 2)
sns.catplot('Education_Level','Salary',data = final,hue = 'Gender',col = 'City',col_wrap = 2)
plt.subplots(figsize=(20,10))

plt.subplot(231)
sns.countplot('Gender',data = final)

plt.subplot(232)
sns.countplot('Education_Level',data = final)

plt.subplot(233)
sns.countplot('Joining Designation',data = final)

plt.subplot(234)
sns.countplot('Designation',data = final)

plt.figure(figsize = (20,8))
sns.countplot('City',data = final,palette= 'rocket')
sns.countplot('Target',data = final)
final['Quarterly Rating'].unique()
final ['Gender'] = pd.get_dummies(final['Gender'],drop_first = True)
final
from sklearn.preprocessing import LabelEncoder

label = LabelEncoder()

final['City'] = label.fit_transform(final['City'])

final['Education_Level'] = label.fit_transform(final['Education_Level'])
final.head()
sns.boxplot('Total Business Value',data = final)
Q1 = final['Total Business Value'].quantile(0.25)
Q3 = final['Total Business Value'].quantile(0.75)
IQR = Q3 - Q1

filter = (final['Total Business Value'] >= Q1 - 1.5 * IQR) & (final['Total Business Value']<= Q3 + 1.5 *IQR)
train1 = final.loc[filter]  
print("data loss percentage {}%".format(((len(final) - len(train1))/len(final))*100))
sns.boxplot('Salary',data = final)
Q1 = final['Salary'].quantile(0.25)
Q3 = final['Salary'].quantile(0.75)
IQR = Q3 - Q1

filter = (final['Salary'] >= Q1 - 1.5 * IQR) & (final['Salary']<= Q3 + 1.5 *IQR)
train2 = final.loc[filter]  
print("data loss percentage {}%".format(((len(final) - len(train2))/len(final))*100))
train2.shape
## Get the Fraud and the normal dataset 

not_stay= (train2['Target']== 0 )

stay= (train2['Target']== 1 )

std_x = train2.loc[:,['Total Business Value','Age','Gender','City','Education_Level','Salary','Joining Designation','Designation','Quarterly Rating']]
std_x.shape
y = train2.iloc[:,-1]
y.head()
from imblearn.under_sampling import NearMiss

# Implementing Undersampling for Handling Imbalanced 
nm = NearMiss()
X_res,y_res=nm.fit_resample(std_x,y)
X_res.shape,y_res.shape<jupyter_output><empty_output><jupyter_text>DATA_VALIDATION 5. Data Validation<jupyter_code>from sklearn.model_selection import train_test_split

#Split data into Train and test format
x_train,x_test,y_train,y_test = train_test_split(X_res,y_res,test_size = 0.25,random_state =105)

print('Shape of Training Xs:{}'.format(x_train.shape))
print('shape of Test:{}'.format(x_test.shape))
#pip install lazypredict<jupyter_output><empty_output><jupyter_text>MODEL_BUILDING 6. Model Building<jupyter_code>from lazypredict.Supervised import LazyClassifier


clf = LazyClassifier(verbose=0,ignore_warnings=True, custom_metric=None)
models,predictions = clf.fit(x_train, x_test, y_train, y_test)

print(models)
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier()

clf.fit(x_train,y_train)
y_predicted = clf.predict(x_test)
score = clf.score(x_test,y_test)
print(score)<jupyter_output>0.8125<jupyter_text>CONFUSION_MATRIX 7. Confusion Matirx<jupyter_code>from sklearn.metrics import confusion_matrix
#Confusion Matrix
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, y_predicted)
np.set_printoptions(precision=2)
cnf_matrix
from sklearn.metrics import classification_report
print(classification_report(y_test,y_predicted))
test = pd.read_csv('/kaggle/input/predicting-employee-attrition/test_data.csv')

test.shape
test_f = pd.merge(test,final,on = 'Emp_ID')
test_f<jupyter_output><empty_output><jupyter_text>TEST_PREDICTION 8. Prediction on Test Data<jupyter_code>test_final = test_f.drop(['Emp_ID','Target'],axis = 1)
test_final.head()
test_predicted = clf.predict(test_final)
test_predicted.shape
submission=pd.read_csv('/kaggle/input/predicting-employee-attrition/sample_submission.csv')

submission
submission['Target']=test_predicted


submission.to_csv('Random_forest.csv',index=False)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12906595046254848, 'fraction_numerical': 0.01566696508504924, 'mean_word_length': 6.923167848699763, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 34, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '255323', 'license': 'Apache-2.0', 'n_tokens_mistral': 2380, 'n_tokens_neox': 2249, 'n_words': 516, 'path': 'employee-attrition-prediction.ipynb', 'repo_name': 'kedar750/Employee-Attrition-Prediction', 'size': '6702'}