-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_discriminant_analysis_abalone_dataset.py
362 lines (265 loc) · 9.68 KB
/
linear_discriminant_analysis_abalone_dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 14:54:21 2020
@author: 79456
"""
# Linear Discriminant Analysis (LDA)
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
# Importing the dataset
df = pd.read_csv('abalone.csv')
X = df.iloc[:, 1:7].values
y = df.iloc[:, 8].values
df.columns = ['Sex','Length','Diameter','Height','Whole weight','Shucked weight','Viscera weight','Shell weight','Rings']
# To display the top 5 rows
df.head(5)
# To display the bottom 5 rows
df.tail(5)
# Checking the data type
df.dtypes
# Renaming the column names
df = df.rename(columns={'Diameter':'Diam','Sex' : 'Gender','Viscera weight' : 'Viscera_weight','Shell weight' : 'Shell_weight','Shucked weight' : 'Shucked_weight'})
df.head(5)
# Dropping irrelevant columns
df = df.drop(['Viscera_weight','Shucked_weight'],axis=1)
df.head(5)
# Total number of rows and columns
df.shape
# Rows containing duplicate data
duplicate_rows_df = df[df.duplicated()]
print('number of duplicate rows: ', duplicate_rows_df.shape)
# Used to count the number of rows before removing the data
df.count()
#checking for non-null values
df.info()
# Dropping the duplicates
df = df.drop_duplicates()
df.head(5)
df.count()
# Finding the null values.
print(df.isnull().sum())
# Dropping the missing values.
df = df.dropna()
df.count()
# After dropping the values
print(df.isnull().sum())
#Detecting Outliers
sns.boxplot(x=df['Length'])
sns.boxplot(x=df['Diam'])
sns.boxplot(x=df['Height'])
sns.boxplot(x=df['Whole weight'])
sns.boxplot(x=df['Rings'])
Q1 = df.quantile(0.25)
Q3 = df.quantile(0.75)
IQR = Q3 - Q1
print(IQR)
df = df[~((df < (Q1-1.5 * IQR)) |(df > (Q3 + 1.5 * IQR))).any(axis=1)]
df.shape
df.Shell_weight.describe()
######Univariate Analysis
######################
#Categorical Unordered Univariate Analysis:
'''
An unordered variable is a categorical variable that has no defined order.
'''
# Let's calculate the percentage of each category.
df.Gender.value_counts(normalize=True)
#plot the bar graph of percentage job categories
df.Gender.value_counts(normalize=True).plot.barh()
plt.show()
#Categorical Ordered Univariate Analysis:
'''
Ordered variables are those variables that have a natural rank of order.
'''
#calculate the percentage of each education category.
df.Rings.value_counts(normalize=True)
#plot the pie chart of education categories
df.Rings.value_counts(normalize=True).plot.pie()
plt.show()
'''
This is how we analyze univariate categorical analysis.
If the column or variable is of numerical then we’ll analyze by calculating its mean,
median, std, etc.
We can get those values by using the describe function.
'''
df.Shell_weight.describe()
######Bivariate Analysis
'''
a) Numeric-Numeric Analysis:
Analyzing the two numeric variables from a dataset is known as numeric-numeric analysis.
We can analyze it in three different ways.
'''
# Plotting a Histogram
df.Gender.value_counts().nlargest(40).plot(kind='bar', figsize=(10,5))
plt.title('Number of values /Gender' )
plt.ylabel('Num of Values')
plt.xlabel('Gender')
df.Rings.value_counts().nlargest(40).plot(kind='bar', figsize=(10,5))
plt.title('Number of values /Rings' )
plt.ylabel('Num of Values')
plt.xlabel('Rings')
df.Shell_weight.value_counts().nlargest(40).plot(kind='bar', figsize=(10,5))
plt.title('Number of values /Rings' )
plt.ylabel('Num of Values')
plt.xlabel('Shell_weight')
#plot the pie chart of categories
df.Rings.value_counts(normalize=True).plot.pie()
plt.show()
#plot the pie chart of categories
df.Gender.value_counts(normalize=True).plot.pie()
plt.show()
###Scatter Plot
# Plotting a scatter plot
#we see trend line between Rings and shell weight
fig, ax = plt.subplots(figsize=(10,6))
ax.scatter(df['Rings'], df['Shell_weight'])
ax.set_xlabel('Rings')
ax.set_ylabel('Shell_weight')
plt.show()
#plot the scatter plot
plt.scatter(df.Rings,df.Shell_weight)
plt.show()
#plot the scatter plot
df.plot.scatter(x="Rings",y="Shell_weight")
plt.show()
#Pair Plot
#plot the pair plot
sns.pairplot(data = df, vars=['Rings','Shell_weight','Gender'])
plt.show()
# Correlation Matrix
'''
Since we cannot use more than two variables as x-axis and y-axis in Scatter and Pair Plots,
it is difficult to see the relation between three numerical variables in a single graph.
In those cases, we’ll use the correlation matrix.
'''
plt.figure(figsize=(20,10))
c= df.corr()
sns.heatmap(c,cmap='BrBG',annot=True)
c
#######Numeric - Categorical Analysis
'''
Analyzing the one numeric variable and one categorical variable from a dataset is
known as numeric-categorical analysis.
We analyze them mainly using mean, median, and box plots.
'''
#mean value shell weight / rings
df.groupby('Shell_weight')['Rings'].mean()
#median value
df.groupby('Shell_weight')['Rings'].median()
#plot the box plot
sns.boxplot(df.Rings, df.Shell_weight)
plt.show()
sns.boxplot(df.Gender, df.Shell_weight)
plt.show()
#####Categorical — Categorical Analysis
#create numerical data type
df['Rings'] = np.where(df.Rings >= 10)
df.response_rate.value_counts()
#plot the bar graph with average value
df.groupby('Rings')['Shell_weight'].mean().plot.bar()
plt.show()
df.groupby('Gender')['Shell_weight'].mean().plot.bar()
plt.show()
#### Multivariate Analysis
result = pd.pivot_table(data=df, index='Rings', columns='Gender',values='Shell_weight')
print(result)
#create heat map of education vs marital vs response_rate
sns.heatmap(result, annot=True, cmap = 'RdYlGn', center=0.117)
plt.show()
print(df['Shell_weight'].describe())
plt.figure(figsize=(9, 8))
sns.distplot(df['Shell_weight'], color='g', bins=100, hist_kws={'alpha': 0.4});
###Numerical data distribution
list(set(df.dtypes.tolist()))
df_num = df.select_dtypes(include = ['float64', 'int64'])
df_num.head()
df_num.hist(figsize=(16, 20), bins=50, xlabelsize=8, ylabelsize=8)
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Applying LDA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
lda = LDA(n_components = 2)
X_train = lda.fit_transform(X_train, y_train)
X_test = lda.transform(X_test)
# Training the Logistic Regression model on the Training set
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, y_train)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix, accuracy_score
y_pred = classifier.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
accuracy_score(y_test, y_pred)
# Visualising the Training set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green', 'blue')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green', 'blue'))(i), label = j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('LD1')
plt.ylabel('LD2')
plt.legend()
plt.show()
# Visualising the Test set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green', 'blue')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green', 'blue'))(i), label = j)
plt.title('Logistic Regression (Test set)')
plt.xlabel('LD1')
plt.ylabel('LD2')
plt.legend()
plt.show()
dataset["Diameter"] = dataset["Diameter"].astype(float)
dataset["Rings"] = dataset["Rings"].astype(int)
height = dataset.iloc[3:20,3]
rings = dataset.iloc[3:20:,8]
sex = dataset.iloc[1:20:,0]
dataset.info(verbose=True)
dataset_droped = dataset.drop('Sex',axis = 1)
dataset_dic = {"Height" : dataset_1,"Rings" : dataset_2}
df = pd.DataFrame (dataset_dic, columns = ['Height','Rings'])
dataset.rename_axis("RINGS", axis=8)
sns.histplot(data=dataset, x=dataset["Diameter"], hue=dataset["Rings"], multiple="stack")
sns.kdeplot(data=dataset,x="Height", y="Rings", multiple="stack")
sns.kdeplot(data = dataset_droped, x="Height", y = "Rings")
sns.kdeplot(data = dataset_droped,x=sex)
sns.lmplot(x = "Sex", y= "Rings", data = dataset)
sns.kdeplot(dataset.Diameter,dataset.Rings,shade=True,shade_lowest=False,cmap='Reds')
sns.kdeplot(dataset.Diameter,dataset.Rings,cmap='Reds')
f, axes = plt.subplots(1,2)
sns.kdeplot(dataset.Diameter,dataset.Rings,cmap='Reds',ax = axes[0])
sns.kdeplot(dataset.Shell_weight,dataset.Rings,cmap='Reds',ax = axes[1])
for i in dataset_1:
if i == i.find("M"):
print(i)
try:
list1 = map (float, dataset_1)
list2 = map(int, dataset_2)
except ValueError:
print ("Error")
sns.kdeplot(data=dataset,x=list1, hue=list2, multiple="stack")