0% found this document useful (0 votes)
19 views4 pages

Logistic Regression for Salary Prediction

This document discusses using logistic regression for classification in Python. It performs the following steps: 1. Preprocesses the categorical data by converting it to numeric values. 2. Splits the data into training and test sets for model building and evaluation. 3. Fits a logistic regression model on the training set and evaluates it on the test set by calculating performance metrics like accuracy and confusion matrix. 4. Tries improving the model by removing insignificant variables but finds the accuracy decreases and misclassifications increase.

Uploaded by

mohan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

Logistic Regression for Salary Prediction

This document discusses using logistic regression for classification in Python. It performs the following steps: 1. Preprocesses the categorical data by converting it to numeric values. 2. Splits the data into training and test sets for model building and evaluation. 3. Fits a logistic regression model on the training set and evaluates it on the test set by calculating performance metrics like accuracy and confusion matrix. 4. Tries improving the model by removing insignificant variables but finds the accuracy decreases and misclassifications increase.

Uploaded by

mohan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Data Analysis in python-3

'''
Logistics Regression:
It is a machine learning classification algorithm used to predict
the probability of a categorical dependent variable. It is used to
build
a classifier model based on the available data but first we have to
convert the
categorical data to numbers(0 and 1), because machine learning does
not
work with the categorical data then after processing we can convert
them back to categorical.
'''
#reindexing the salary status names to 0,1 using .map function as
integer encoding
data2['SalStat']=data2['SalStat'].map({' less than or equal to
50,000':0,' greater than 50,000':1})
print(data2['SalStat'])
#now converting the other categorical values into dummy variables using
pandas get_dummies function
new_data=pd.get_dummies(data2,drop_first=True) #which splits the number
of categories present in a column into many columns and their values to
0,1.
#now next step is to store the column names of new_data as list
columns_list=list(new_data.columns) #storiing new_data columns names as
a lsit
print(columns_list)
#next step is to separate the input variables from the data
features=list(set(columns_list)-set(['SalStat'])) #features as input
variable having excluded SalStat.
print(features)
#next step is to store the output values in y(dependent variable) using
.values(which is used to extract values)
#from a data frame(new_data)
y=new_data['SalStat'].values #Extracting SalStat values from new_data
to y(output variable)
print(y)
#similarly
x=new_data[features].values #Extracting the values corresponding to
features(column names) from new_data
#and storing them in x(input variable)
print(x)
#next step is to split the data into train and test sets using
train_test_split command
train_x,test_x,train_y,test_y=train_test_split(x,y,test_size=0.3,random
_state=0) #test_size=0.3 is the proportion of the data set used(30%)
for testing
#and random_state=0 takes the same set of inputs all the times
otherwise it will take any ramdom sets.
#therefore here the test set will take around 30% of the data and train
set around 70%.
#next step is to make an instance of logistic-regression classifier
model using logisticRegression function
logistic=LogisticRegression() #logistic-regression classifier model
#then we will fit the model on train set data using fit function onto
the above instance of the model.
[Link](train_x,train_y)
#now we can extract some of the attributes from this logistic-
regression classifier model
logistic.coef_ #coeffient values of all the variables
logistic.intercept_ #intercept of logistic-regression model
#now we have built the model to classify the salary status of
individuals less than or equal to 50000 or greater than 50000.
#and now we have to check the performance of this model with test data
set for its predictions.
prediction=[Link](test_x) #prediction of salary status from
test data frame
print(prediction)
#now we will use the confusion matrix to evaluate the performance of
above model
#confusion_matrix is a table to evaluate the performance of a
classification model
#confusion_matrix gives the output as number of correct predictions and
number of incorrect predictions
#and it will sumup all the values classwise.
confusion_matrix=confusion_matrix(test_y,prediction) #its columns
represent actual classes like less than/equal to 50000 and greater than
50000
#rows represents predicted values
print(confusion_matrix) #the diagonal values gives correctly
classifiied values and off-diagornal values give incorrect values(miss-
classified).
#as this model have not classified all the observations correctily,
therfore we need accurancy measure.
accuracy_score=accuracy_score(test_y,prediction) #to check the accurecy
of the model.
print(accuracy_score) #thus we get 84% of predictions correctly.
#now we can also check the miss-classified values from the prediction
print('miss-classified values: %d',(test_y!=prediction).sum()) #thus we
got miss-classified values=1427
'''
nwo we can imporve the accurancy of this model by reducing the
insignificant input variables so that it can reduce the miss-classified
output values.
'''
#so we have to make a new model again by removing all the insignificant
input variables.
#reindexing the salary status names to 0,1 using .map function as
integer encoding as done earlier above
data2['SalStat']=data2['SalStat'].map({' less than or equal to
50,000':0,' greater than 50,000':1})
print(data2['SalStat'])
#we can find that gender, natiive country, race and job type are
insignificant
cols=['gender','nativecountry','race','JobType'] #create a list of the
insignificant variables
new_data=[Link](cols,axis=1) #removing 4 columns form the data2 and
saving it to new_data
new_data=pd.get_dummies(new_data,drop_first=True) #repeating the same
command as earlier
columns_list=list(new_data.columns)
features=list(set(columns_list)-set(['SalStat']))
y=new_data['SalStat'].values
x=new_data[features].values
train_x,test_x,train_y,test_y=train_test_split(x,y,test_size=0.3,random
_state=0)
logistic=LogisticRegression()
[Link](train_x,train_y)
logistic.coef_
logistic.intercept_
prediction=[Link](test_x)
print(prediction)
confusion_matrix=confusion_matrix(test_y,prediction)
print(confusion_matrix)
accuracy_score=accuracy_score(test_y,prediction)
print(accuracy_score)
print('miss-classified values: %d',(test_y!=prediction).sum())
#thus removing the insignificant variables does'nt improved the
prediction, the accuracy slightly decreased
#and the miss-classified values increased.

Common questions

Powered by AI

The logistic regression model's classification performance is evaluated using a confusion matrix and accuracy score. The confusion matrix provides a table showing the number of correct and incorrect predictions, where the diagonal values represent correctly classified observations and the off-diagonal values indicate misclassified observations . The accuracy score, calculated as the proportion of correct predictions out of the total predictions, measures the model's overall effectiveness. In the given context, an accuracy score of 84% was achieved .

Dummy variables are used in logistic regression to handle categorical data with multiple categories. These variables transform categorical data into a series of binary columns, each indicating the presence or absence of a category. This transformation allows categorical variables to be included in the regression analysis. Dummy variables are created using the pandas get_dummies function, which generates binary columns from each category in the original dataset, assigning the value 1 for presence and 0 for absence .

The confusion matrix reveals detailed insights into the model's classification performance by comparing predicted vs. actual outcomes. It is constructed by tabulating test data predictions against true values, with columns representing actual classes and rows representing predicted classes. The diagonal values indicate correctly classified instances, while off-diagonal values indicate errors. Constructed using the confusion_matrix function, it provides a clear breakdown of the model's strengths and weaknesses in prediction. In this context, it elucidates how many test observations were correctly versus incorrectly labeled, further aiding in calculating performance metrics like accuracy .

Accuracy score, which measures the proportion of correctly predicted observations out of the total, has limitations as it does not account for class imbalance. High accuracy can be misleading if a dominant class is prevalent. Hence, additional metrics such as precision, recall, F1-score, and ROC-AUC are recommended for comprehensive evaluation. Precision indicates the ratio of true positive predictions against all positive predictions, recall measures the ability to identify actual positives, F1-score harmonizes precision and recall, and ROC-AUC evaluates the model's discrimination ability [Inferred from Source 2 insights on model evaluation].

During the fitting process of logistic regression on training data, the model estimates the coefficients (weights) for each input feature such that the logistic function best fits the training data. These coefficients represent the change in the log-odds of the dependent variable being 1 for a one-unit increase in the predictor variable while holding other variables constant. They indicate the strength and direction of the association between each predictor and the outcome. A positive coefficient suggests that as the feature value increases, the probability of the dependent variable being 1 increases, while a negative coefficient suggests the opposite .

Logistic regression requires categorical dependent variables to be converted into numerical format because it is a type of machine learning algorithm that predicts the probability of categorical outcomes. Machine learning models, including logistic regression, operate using mathematical equations that require numerical data. Therefore, categorical data must be encoded into numerical values such as 0 and 1. This transformation allows the model to perform mathematical computations and build a classifier based on the processed data .

The random_state parameter in dataset splitting ensures the reproducibility of the train-test split. When set to a specific number, it seeds the randomness, allowing the same split to be generated each time the code is run. This consistency is crucial for model evaluation, as it ensures that performance metrics are comparable across different runs or model configurations . Without a fixed random_state, each execution could lead to a different split, complicating the comparison of model outcomes.

In this scenario, removing insignificant input variables from the logistic regression model did not improve prediction accuracy. Although the intent was to enhance the model by reducing complexity and potentially minimizing misclassified outputs, the results showed a slight decrease in accuracy and an increase in misclassified values. This outcome suggests that other factors or variables might play a more significant role in influencing the prediction accuracy, and removing certain variables may inadvertently lose valuable information that the model used for prediction .

A logistic regression model might perform differently after removing variables due to potential loss of relevant information, increased bias, or changes in predictor interactions. Variables contribute not just individually, but might also have an interactive effect with other variables. Considerations for selecting variables should include their significance in hypothesis tests, their multicollinearity with other predictors, and their theoretical justification. Removing variables should be guided by domain knowledge, statistical tests (like p-values), and understanding of the data, ensuring that each variable offers meaningful explanatory power without causing multicollinearity or redundancy .

The data preparation for a logistic regression model involves several key steps: First, the categorical dependent variable is re-indexed using a mapping function to convert categories into numerical values (e.g., 0 and 1). Then, other categorical features are converted into dummy variables using the pandas get_dummies function, which splits the categories into multiple columns with binary numerical values . Subsequently, the feature and output variables are separated by excluding the dependent variable (SalStat) from the feature set and storing their respective values. Finally, the data is split into training and testing sets using the train_test_split command, typically setting a proportion such as 70% training and 30% testing .

You might also like