A small project using Keras and Keras Auto-Tuner API to build a logistic regression model to predict whether a user will purchase an item or not based on historic user data on Age, Gender, Salary and Purchase Status
importpandasaspddf=pd.read_csv('../Social-Network-Ads/Social_Network_Ads.csv')
# check for number of null entriesprint('Data is packed'ifnotdf.isnull().values.any() else'Data contains missing values')
df.head()
frommatplotlib.colorsimportListedColormap# Age vs salary. Men are blue points, Females are Red points and No Buyers are black pointssalaries=df['EstimatedSalary']
ages=df['Age']
genders=df['Gender']
buy_stats=df['Purchased']
colors= [1ifgenders[i] =='Male'andbuy_stats[i] ==1else2ifgenders[i] =='Female'andbuy_stats[i] ==1else0foriinrange(len(df['User ID'].tolist()))]
cmap=ListedColormap(['black','blue','red'])
classes= ['Not Bought', 'Male', 'Female']
plt.clf()
fig=plt.figure()
fig.suptitle("Impact of salary and age")
scatter=plt.scatter(salaries, ages, c=colors, cmap=cmap)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
plt.xlabel('Salary-->')
plt.ylabel('Age-->')
plt.show()
<Figure size 432x288 with 0 Axes>
Preprocessing the data
Data Cleaning and Scaling
# User ID is irrelevantdf=df.drop(['User ID'], axis=1)
# We can change Male and Female to 0 or 1df['Gender'] =df['Gender'].apply(lambdagender: 0ifgender=='Male'else1)
# Normalize Age and EstimatedSalary based on mean and range# value = (val - mean)/(max - min)# Salary Normalizationimportmathsalaries=df['EstimatedSalary']
mean_salary=min(salaries) +max(salaries) /len(salaries)
salary_range=max(salaries) -min(salaries)
norm_salaries= [(salary-mean_salary) /salary_rangeforsalaryinsalaries]
# Age normalizationages=df['Age']
mean_age=min(ages) +max(ages) /len(ages)
age_range=max(ages) -min(ages)
norm_ages= [(age-mean_age) /age_rangeforageinages]
# Assign to dfdf['Age'] =norm_agesdf['EstimatedSalary'] =norm_salariesdf.head()
# Use 60% data as training data and 20% as validation data and 20% as test datay=df.pop('Purchased').to_numpy()
X=df.to_numpy()
# Splitfromsklearn.model_selectionimporttrain_test_split# Train+Validation and Test splitX_train, X_test, y_train, y_test=train_test_split(X, y, test_size=0.2)
# Train and Validation splitX_train, X_valid, y_train, y_valid=train_test_split(X_train, y_train, test_size=0.25)