forked from Ansar390/BBB-PEP-Prediction
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboundary_viz_bbb.py
285 lines (239 loc) · 8.47 KB
/
boundary_viz_bbb.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
# -*- coding: utf-8 -*-
"""boundary_Viz_bbb.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1rdlb5rlppmGpekp4MwooaNJd9_ZJsCbP
"""
# Commented out IPython magic to ensure Python compatibility.
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import re
import os
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import multilabel_confusion_matrix
from statistics import mean
import math
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve, auc, roc_auc_score
from sklearn.metrics import roc_curve
from sklearn.metrics import matthews_corrcoef
import seaborn as sns
import matplotlib.pyplot as plt
from collections import Counter
import seaborn as sns
from sklearn.manifold import TSNE
from __future__ import print_function
import time
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
# %matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
# from google.colab import drive
# drive.mount('/content/drive/')
# %cd /content/drive/My Drive/urdu sentiments
train=pd.read_csv('/content/train_data77up.csv')
test=pd.read_csv('/content/test_data23up.csv')
df = pd.concat([train,test], axis=0)
df=df.reset_index(drop=True)
# train=pd.read_csv('trainHYBRID.csv')
# test=pd.read_csv('testHYBRID.csv')
# y_train=train['class']
# X_train=train.drop(['Unnamed: 0','class'],axis=1)
# y_test=test['class']
# X_test=test.drop(['Unnamed: 0','class'],axis=1)
from sklearn.preprocessing import StandardScaler
#dataset = pd.read_csv('df.csv', sep=',')
dataset = df
X1 = dataset.drop(['target'],axis=1)
Y1 =dataset['target']
X1 = X1.to_numpy()
Y1 = Y1.to_numpy()
std_scale = StandardScaler().fit(X1)
X1 = std_scale.transform(X1)
X1 = np.nan_to_num(X1.astype('float32'))
X=X1
y=Y1
# train=pd.read_csv('/content/premrna_train.csv')
# test=pd.read_csv('/content/premrna_test.csv')
df = pd.concat([train,test], axis=0)
df=df.reset_index()
# df=df.drop(['index'],axis=1)
# y_train=train['class']
# X_train=train.drop(['class'],axis=1)
# y_test=test['class']
# X_test=test.drop(['class'],axis=1)
# # df = pd.read_csv('ctgan.csv')
# df = df.sample(frac=1)
# y = df['class']
# x=df.drop(['class'],axis=1)
from sklearn.preprocessing import LabelEncoder
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
x = df.apply(le.fit_transform)
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
scaler.get_params()
x=scaler.fit_transform(x)
pca_50 = PCA(n_components=50)
pca_result_50 = pca_50.fit_transform(X)
print('Cumulative explained variation for 50 principal components: {}'.format(np.sum(pca_50.explained_variance_ratio_)))
pca_result_50
time_start = time.time()
tsne = TSNE(n_components=2, verbose=0, perplexity=50, n_iter=300)
tsne_pca_results = tsne.fit_transform(pca_result_50)
print('t-SNE done! Time elapsed: {} seconds'.format(time.time()-time_start))
# visualise again and highlight actual classes of data
target_ids = range(len(y))
plt.figure(figsize=(10, 8))
colours = ['purple','orange' ]
label = ['TE','NON-TE' ]
for i, c, label in zip(target_ids, colours, label):
plt.scatter(tsne_pca_results[y == i, 0], tsne_pca_results[y == i, 1], c=c, label=label, alpha=0.3, linewidths = 2 )
pass
plt.legend()
plt.show()
# visualise again and highlight actual classes of data
target_ids = range(len(y))
plt.figure(figsize=(10, 8))
colours = ['purple','orange','g','yellow','red','black','m','r','y','teal','pink','green','y']
label = ['Copia','Gypsy','Pao','Line','L1','Sine','Harbinger','hAt','Mutator','Tc-Marnier','Cacta','Mite','Heli']
for i, c, label in zip(target_ids, colours, label):
plt.scatter(tsne_pca_results[y == i, 0], tsne_pca_results[y == i, 1], c=c, label=label, alpha=0.3, linewidths = 2 )
pass
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from lightgbm import LGBMClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
import xgboost as xgb
from xgboost import XGBClassifier
h=0.2
names = [
"Random Forest",
"LGBM",
"ET",
"XGB",
]
from sklearn.linear_model import LogisticRegression
classifiers = [
RandomForestClassifier(max_depth=5, n_estimators=100),
LGBMClassifier(),
ExtraTreesClassifier(),
XGBClassifier() ,
LogisticRegression()
]
X, y = tsne_pca_results,y
rng = np.random.RandomState(2)
X += 2 * rng.uniform(size=X.shape)
linearly_separable = (X, y)
datasets = [
make_moons(noise=0.3, random_state=0),
make_circles(noise=0.2, factor=0.5, random_state=1),
linearly_separable,
]
figure = plt.figure(figsize=(27, 9))
i = 1
# iterate over datasets
for ds_cnt, ds in enumerate(datasets):
# preprocess dataset, split into training and test part
X, y = ds
X = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.4, random_state=42
)
x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# just plot the dataset first
cm = plt.cm.RdBu
cm_bright = ListedColormap(["#FF0000", "#0000FF"])
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
if ds_cnt == 0:
ax.set_title("Input data")
# Plot the training points
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k")
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xticks(())
ax.set_yticks(())
i += 1
# iterate over classifiers
for name, clf in zip(names, classifiers):
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, x_max]x[y_min, y_max].
if hasattr(clf, "decision_function"):
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
else:
Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
# Put the result into a color plot
Z = Z.reshape(xx.shape)
ax.contourf(xx, yy, Z, cmap=cm, alpha=0.8)
# Plot the training points
ax.scatter(
X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright, edgecolors="k"
)
# Plot the testing points
ax.scatter(
X_test[:, 0],
X_test[:, 1],
c=y_test,
cmap=cm_bright,
edgecolors="k",
alpha=0.6,
)
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xticks(())
ax.set_yticks(())
if ds_cnt == 0:
ax.set_title(name)
ax.text(
xx.max() - 0.3,
yy.min() + 0.3,
("%.2f" % score).lstrip("0"),
size=15,
horizontalalignment="right",
)
i += 1
plt.figure(figsize=(20, 20), dpi=600)
plt.tight_layout()
plt.show()
sns.scatterplot(
x=tsne_pca_results[:, 0], y=tsne_pca_results[:, 1],
hue=y,
data=X,
legend="full",
alpha=0.3
).set(title="Feature Space Visualization of Raw Data")