forked from thesashi7/animalclassification-cs599
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreparedata.py
179 lines (161 loc) · 7.05 KB
/
preparedata.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
import csv
import numpy as np
from keras.utils import np_utils
import numpy as np
from sklearn.model_selection import train_test_split
#
# Labels for cat and dog
cat = 1
dog = 0
##############################################################################
# FeatureLoader class to load csv audio features
# Loads audio features for species classification extracted from mainly
# two different extractors; PyAudio and Librosa
#
##############################################################################
class FeatureLoader:
def __init__(self,newFilepath=[]):
self.filepath = newFilepath
####################################################################################
# Function to load features.csv file
# These csv files must contain audio features extracted using librosa
# along with the label at the end colum
#
def loadLibrosaCSV(self):
file = open(self.filepath, 'r') # Open file
csv_file = csv.reader(file) # Create CSV reader
data = list() # Create empty Data list
target = list() # Create empty target list
for row in csv_file: # Rows contain target split into two
if (len(row) == 0): # Skip empty rows
continue
data.append(row[:len(row) - 1])
if (row[len(row) - 1] == 'cat'):
target.append(cat)
else:
target.append(dog)
# target.append(row[len(row) - 1])
return np.asarray(data, dtype=np.float64), np.asarray(target,
dtype=np.int64) # Return tuple containing
####################################################################################
# Function to load train-x.csv or train-y.csv
# These csv files must contain audio features extracted using pyaudioanalysis
# or the target labels
#
def loadPyCSV(self):
return np.genfromtxt(self.filepath, delimiter=',')
###################################################################################
#@files : Two files containing audio features for classification
# Ideally one file is for only features and the other is for only label
#
def loadFeatures(self, files=[]):
data = []
target = []
if(len(files)==1):
self.filepath = files[0]
data, target = self.loadLibrosaCSV()
elif(len(files)==2):
self.filepath = files[0]
data = self.loadPyCSV()
self.filepath = files[1]
target = self.loadPyCSV()
return data,target
#######################################################################################
#
# FeatureWriter class to write features to a CSV file
# Especially supports combining features of two different classes like cat,dog
#
# Like: Input = cat.csv, dog.csv
# Output = train-x.csv,train-y.csv
# In addition provides the option of creating different training and test dat for input features
# See writeTrainAndTestFromTwoPy(...) for more details
#
class FeatureWriter:
def __init__(self, newFeatures=[]):
self.features = newFeatures
################################################################################
# @file_name: Name of the csv file that you want to write the featues to
#
def write_csv(self, file_name="test-data"):
with open(file_name + ".csv", 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE)
# print(type(features[0]))
if (isinstance(self.features[0], np.ndarray)):
for fv in self.features:
print fv
writer.writerow(fv)
else: # only one feature vector
writer.writerow(self.features)
#################################################################################
# This is to combine training data of cats and dogs audio features extracted
# using PyAudioAnalysis or cat,dog features without label
#
# @field1 : cat audio feature csv file
# @field1 : dog audio feature csv file
#
def writeFromTwoPy(self, file1,file2):
cat_data = np.genfromtxt(file1,delimiter=',')
dog_data = np.genfromtxt(file2,delimiter=',')
print cat_data.shape
print dog_data.shape
cat_label = np.ones([cat_data.shape[0],1])
dog_label = np.zeros([dog_data.shape[0],1])
cat_data = np.append(cat_data, cat_label, 1)
dog_data = np.append(dog_data, dog_label, 1)
train_data = np.concatenate((cat_data,dog_data))
np.random.shuffle(train_data)
print train_data.shape
train_y = np.empty([train_data.shape[0],1])
i=0
while i < train_data.shape[0]:
train_y[i]=[train_data[i][train_data.shape[1]-1]]
i+=1
train_data = np.delete(train_data, np.s_[train_data.shape[1]-1:train_data.shape[1]], axis=1)
print train_data.shape
self.features = train_data
self.write_csv( "data/train-x")
self.features = train_y
self.write_csv("data/train-y")
#################################################################################
# This is to combine training data of cats and dogs audio features extracted
# using PyAudioAnalysis
# In addition creates separate training and testing csv files
#
# Example: Input = cat.csv, dog.csv
# Output = train-x.csv, train-y.csv, test-x.csv, test-y.csv
#
# @field1 : cat audio feature csv file
# @field1 : dog audio feature csv file
#
def writeTrainAndTestFromTwoPy(self,file1,file2, name="high"):
cat_data = np.genfromtxt(file1, delimiter=',')
dog_data = np.genfromtxt(file2, delimiter=',')
print cat_data.shape
print dog_data.shape
cat_label = np.ones([cat_data.shape[0],1])
dog_label = np.zeros([dog_data.shape[0],1])
cat_data = np.append(cat_data, cat_label, 1)
dog_data = np.append(dog_data, dog_label, 1)
data = np.concatenate((cat_data, dog_data))
np.random.shuffle(data)
target = np.empty([data.shape[0], 1])
i = 0
while i < data.shape[0]:
target[i] = data[i][data.shape[1] - 1]
i += 1
data = np.delete(data, np.s_[data.shape[1] - 1: data.shape[1]], axis=1)
# Split the data into two parts: training data and testing data
train_data, test_data, train_target, test_target = train_test_split(
data, (target[:, np.newaxis]), test_size=0.2, random_state=42)
test_target = test_target.reshape((test_target.shape[0],1))
train_target = train_target.reshape((train_target.shape[0], 1))
self.features = train_data
self.write_csv("data/"+name+"-train-x")
self.features = train_target
self.write_csv("data/"+name+"-train-y")
self.features = test_data
self.write_csv("data/"+name+"-test-x")
self.features = test_target
self.write_csv("data/"+name+"-test-y")
#combineTrainData()
#createTrainAndTestData()