-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocessor.py
157 lines (97 loc) · 3.23 KB
/
preprocessor.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
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, normalize
from sklearn.decomposition import PCA
def preprocess( FILE , TARGET , UNWANTED ):
FILE = 'uploads/' + FILE
f = open(FILE , 'r+')
HEADER , SEP = findHeaderAndSEP(f)
f.close()
# Open File
data = pd.read_csv(FILE , sep=SEP , header=HEADER )
#Remove Unwanted
data = data.drop(UNWANTED , axis=1)
# Keep Data with Finite Target
if TARGET is not None:
try:
data = data[ np.isfinite( data[TARGET] ) ]
except:
pass
#Remove more than half missing data
data = data.dropna(thresh=0.5,axis=1)
#Seperating X and Y
if TARGET is not None:
Y = data[TARGET]
X = data.drop([TARGET] , axis = 1)
data = X
# One Hot Encode String data
def encode_and_bind(original_dataframe, feature_to_encode):
dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
res = pd.concat([original_dataframe, dummies], axis=1)
res = res.drop([feature_to_encode] , axis=1)
return res
columns = data.columns
for c in columns:
if data[c].dtype == 'object':
data = encode_and_bind(data , c)
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
data = imputer.fit_transform(data)
if TARGET is None:
return data
# Train-Test Split
x_train,x_test,y_train,y_test = train_test_split( data ,Y,test_size=.34)
return x_train,x_test,y_train,y_test
def findHeaderAndSEP(f):
# Finds Seperator
line = f.readline().strip()
SEP = None
if ',' in line:
SEP = ','
elif ':' in line:
SEP = ':'
elif ';' in line:
SEP = ';'
line1 = line.split(SEP)
line2 = f.readline().strip().split(SEP)
if SEP is None:
SEP = '\s+'
types1 = []
types2 = []
# Finds Header
for l in line1:
try:
float(l)
types1.append('float')
except:
types1.append('str')
for l in line2:
try:
float(l)
types2.append('float')
except:
types2.append('str')
HEADER = None
for a , b in zip( types1 , types2 ):
if a != b:
HEADER = 0
break
# print("HEADER, SEP", HEADER , SEP)
return HEADER , SEP
def xnormalize(X):
# Scaling the data to bring all the attributes to a comparable level
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Normalizing the data so that
# the data approximately follows a Gaussian distribution
X_normalized = normalize(X_scaled)
# Converting the numpy array into a pandas DataFrame
X_normalized = pd.DataFrame(X_normalized)
pca = PCA(n_components = 2)
X_principal = pca.fit_transform(X_normalized)
X_principal = pd.DataFrame(X_principal)
X_principal.columns = ['P1', 'P2']
return X_principal
# preprocess('uploads/data.txt', 'quality' , [])