Debian Codegraph @

examples/ai/genre-classify/genre-classify.ck

raw
1 //------------------------------------------------------------------------------
2 // name: genre-classify.ck
3 // desc: a real-time genre-classifier using the features extracted using
4 // GTZAN dataset + features-extract.ck
5 //
6 // version: need chuck version 1.5.0.0 or higher
7 // sorting: part of ChAI (ChucK for AI)
8 //
9 // USAGE: run in any real-time mode (default)
10 // > chuck classify-genres.ck
11 //
12 // uncomment the next line to learn more about the KNN2 object:
13 // KNN2.help();
14 //
15 // date: Spring 2023
16 // authors: Ge Wang (https://ccrma.stanford.edu/~ge/)
17 // Yikai Li
18 //------------------------------------------------------------------------------
19
20 // input: pre-extracted features file with labels
21 me.dir() + "data/gtzan-23.txt" => string FEATURES_FILE;
22 // if have arguments, override filename
23 if( me.args() > 0 ) me.arg(0) => FEATURES_FILE;
24 //------------------------------------------------------------------------------
25 // expected features file format:
26 //------------------------------------------------------------------------------
27 // VALUE VALUE ... VALUE LABEL
28 // VALUE VALUE ... VALUE LABEL
29 // ... ... ... ... LABEL
30 // VALUE VALUE ... VALUE LABEL
31 //------------------------------------------------------------------------------
32
33
34 //------------------------------------------------------------------------------
35 // unit analyzer network: this must match the features in the features file
36 //------------------------------------------------------------------------------
37 // audio input into a FFT
38 adc => FFT fft;
39 // a thing for collecting multiple features into one vector
40 FeatureCollector combo => blackhole;
41 // add spectral feature: Centroid
42 fft =^ Centroid centroid =^ combo;
43 // add spectral feature: Flux
44 fft =^ Flux flux =^ combo;
45 // add spectral feature: RMS
46 fft =^ RMS rms =^ combo;
47 // add spectral feature: MFCC
48 fft =^ MFCC mfcc =^ combo;
49
50
51 //-----------------------------------------------------------------------------
52 // setting analysis parameters -- also should match what was used during extration
53 //-----------------------------------------------------------------------------
54 // set number of coefficients in MFCC (how many we get out)
55 // 13 is a commonly used value; using less here for printing
56 20 => mfcc.numCoeffs;
57 // set number of mel filters in MFCC
58 10 => mfcc.numFilters;
59
60 // do one .upchuck() so FeatureCollector knows how many total dimension
61 combo.upchuck();
62 // get number of total feature dimensions
63 combo.fvals().size() => int NUM_DIMENSIONS;
64
65 // set FFT size
66 2048 => fft.size;
67 // set window type and size
68 Windowing.hann(fft.size()) => fft.window;
69 // our hop size (how often to perform analysis)
70 2048::samp => dur HOP;
71
72
73 //------------------------------------------------------------------------------
74 // load feature data; read important global values like numPoints and numCoeffs
75 //------------------------------------------------------------------------------
76 // values to be read from file
77 0 => int numPoints; // number of points in data
78 0 => int numCoeffs; // number of dimensions in data
79 // file read PART 1: read over the file to get numPoints and numCoeffs
80 loadFile( FEATURES_FILE ) @=> FileIO @ fin;
81 // check
82 if( !fin.good() ) me.exit();
83 // check dimension
84 if( numCoeffs != NUM_DIMENSIONS )
85 {
86 // error
87 <<< "[error] expecting:", NUM_DIMENSIONS, "dimensions; but features file has:", numCoeffs >>>;
88 // stop
89 me.exit();
90 }
91
92 // labels of all data points
93 string inLabels[numPoints];
94 // label indices of all data points
95 int inLabelsInt[inLabels.size()];
96 // feature vectors of data points
97 float inFeatures[numPoints][numCoeffs];
98 // keys
99 string labels[0];
100 // use as map: labels to numbers
101 int label2int[0];
102
103 //------------------------------------------------------------------------------
104 // array for storing features
105 //------------------------------------------------------------------------------
106 // how much time to aggregate features for each file
107 // (this does not need to match extraction; might play with this number)
108 .5::second => dur EXTRACT_TIME;
109 // given EXTRACT_TIME and HOP, how many frames per file?
110 (EXTRACT_TIME / HOP) $ int => int numFrames;
111
112 // use this for new input
113 float features[numFrames][numCoeffs];
114 // average values of coefficients across frames
115 float featureMean[numCoeffs];
116 // for printing
117 int lengths[0];
118 // for printing (how much to indent)
119 int indents[0];
120
121
122 //------------------------------------------------------------------------------
123 // read the data
124 //------------------------------------------------------------------------------
125 readData( fin );
126
127
128 //------------------------------------------------------------------------------
129 // set up our KNN object to use for classification
130 // (KNN2 is a fancier version of the KNN object)
131 // -- run KNN2.help(); in a separate program to see its available functions --
132 //------------------------------------------------------------------------------
133 KNN2 knn;
134 // k nearest neighbors
135 10 => int K;
136 // results vector
137 float knnResult[labels.size()];
138 // knn train
139 knn.train( inFeatures, inLabelsInt );
140
141
142
143
144 //------------------------------------------------------------------------------
145 // real-time classification loop
146 //------------------------------------------------------------------------------
147 while( true )
148 {
149 // aggregate features over a period of time
150 for( int frame; frame < numFrames; frame++ )
151 {
152 //-------------------------------------------------------------
153 // a single upchuck() will trigger analysis on everything
154 // connected upstream from combo via the upchuck operator (=^)
155 // the total number of output dimensions is the sum of
156 // dimensions of all the connected unit analyzers
157 //-------------------------------------------------------------
158 combo.upchuck();
159 // get features
160 for( int d; d < NUM_DIMENSIONS; d++)
161 {
162 // store them in current frame
163 combo.fval(d) => features[frame][d];
164 }
165 // advance time
166 HOP => now;
167 }
168
169 // compute means for each coefficient across frames
170 for( int d; d < NUM_DIMENSIONS; d++ )
171 {
172 // zero out
173 0.0 => featureMean[d];
174 // loop over frames
175 for( int j; j < numFrames; j++ )
176 {
177 // add
178 features[j][d] +=> featureMean[d];
179 }
180 // average
181 numFrames /=> featureMean[d];
182 }
183
184 //-------------------------------------------------
185 // predict using KNN2; results filled in knnResults
186 //-------------------------------------------------
187 knn.predict( featureMean, K, knnResult );
188
189 // print results
190 chout <= "-------------------------------------------------" <= IO.newline();
191 // print for each label
192 for( int i; i < knnResult.size(); i++ )
193 {
194 // print label
195 chout <= labels[i] <= ":";
196 // print indentatation
197 for( int ii; ii < indents[i]; ii++ ) { chout <= " "; }
198 // print probability
199 chout <= knnResult[i] <= IO.newline();
200 }
201 }
202 //------------------------------------------------------------------------------
203 // end of real-time classification loop
204 //------------------------------------------------------------------------------
205
206
207
208
209 //------------------------------------------------------------------------------
210 // function: load data file
211 //------------------------------------------------------------------------------
212 fun FileIO loadFile( string filepath )
213 {
214 // reset
215 0 => numPoints;
216 0 => numCoeffs;
217
218 // load data
219 FileIO fio;
220 if( !fio.open( filepath, FileIO.READ ) )
221 {
222 // error
223 <<< "cannot open file:", filepath >>>;
224 // close
225 fio.close();
226 // return
227 return fio;
228 }
229
230 string str;
231 string line;
232 // read file int array
233 while( fio.more() )
234 {
235 // read each line
236 fio.readLine().trim() => str;
237 // check if empty line
238 if( str != "" )
239 {
240 numPoints++;
241 str => line;
242 }
243 }
244
245 // a string tokenizer
246 StringTokenizer tokenizer;
247 // set to last non-empty line
248 tokenizer.set( line );
249 // -1 (to account for label)
250 -1 => numCoeffs;
251 // see how many, including label name
252 while( tokenizer.more() )
253 {
254 tokenizer.next();
255 numCoeffs++;
256 }
257
258 // check
259 if( numPoints == 0 || numCoeffs <= 0 )
260 {
261 <<< "no data in file:", filepath >>>;
262 fio.close();
263 return fio;
264 }
265
266 // print
267 <<< "# of data points:", numPoints, "dimensions:", numCoeffs >>>;
268
269 // done for now
270 return fio;
271 }
272
273
274 //------------------------------------------------------------------------------
275 // function: read the data
276 //------------------------------------------------------------------------------
277 fun void readData( FileIO fio )
278 {
279 // rewind the file reader
280 fio.seek( 0 );
281
282 // read file int array
283 string str;
284 int ci, ri;
285 while( fio => str )
286 {
287 // check for last
288 if( (ci != 0) && ((ci % numCoeffs) == 0) )
289 {
290 // read in label
291 str => inLabels[ri];
292 // set in map
293 1 => label2int[str];
294 // increment row
295 ri++;
296 // reset column
297 0 => ci;
298 }
299 else
300 {
301 // store feature value
302 Std.atof(str) => inFeatures[ri][ci];
303 // increment column
304 ci++;
305 }
306 }
307
308 // get keys from map
309 label2int.getKeys( labels );
310 // assign index
311 for( int i; i < labels.size(); i++ )
312 { i => label2int[labels[i]]; }
313 // convert in labels to ints
314 for( int i; i < inLabels.size(); i++ )
315 {
316 // get index as int
317 label2int[inLabels[i]] => inLabelsInt[i];
318 }
319
320 // max length
321 0 => int maxLength;
322 // get lengths of label names for printing
323 for( int i; i < labels.size(); i++ )
324 {
325 // compare with max length
326 if( labels[i].length() > maxLength )
327 labels[i].length() => maxLength;
328 // append to array
329 lengths << labels[i].length();
330 }
331
332 // get lengths of label names for printing
333 for( int i; i < lengths.size(); i++ )
334 {
335 // get indent for length
336 indents << (maxLength + 1 ) - lengths[i];
337 }
338 }