You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1604 lines
46 KiB

#include <algorithm>
#include <random>
#include <math.h>
#include "basicProcessingUnit.h"
#include "../layers/avgpoolLayer.h"
#include "../layers/batchnormLayer.h"
#include "../layers/connectedLayer.h"
#include "../layers/convolutionalLayer.h"
#define LOG( X ) m_pLog->Log( "PU", this, X )
#define LOG_ERROR( X ) m_pLog->Log( "PU", this, _LOG_ERROR, X )
#define SLOG( X ) me->m_pLog->Log( "PU-THREAD", NULL, X )
#define SLOG_ERROR( X ) me->m_pLog->Log( "PU-THREAD", NULL, _LOG_ERROR, X )
cortexProcessingUnit::cortexProcessingUnit(){
m_pLog = basicLogCollection::getInstance();
};
void cortexProcessingUnit::incrementLayer(cortexLayer *l, int steps){
uint32_t num = l->m_nOutputVol*steps;
l->m_pOutput += num;
l->m_pDelta += num;
l->m_pX += num;
l->m_pXNorm += num;
#ifdef GPU
l->m_pGpuOutput += num;
l->m_pGpuDelta += num;
l->m_pGpuX += num;
l->m_pGpuXNorm += num;
#endif
};
void *cortexProcessingUnit::load_thread(void *ptr){
cortexTHREAD_ARGS *a;
cortexProcessingUnit *me;
a = (cortexTHREAD_ARGS*)ptr;
if (a == NULL){
basicLogCollection::getInstance()->Log("PU-THREAD", NULL, _LOG_ERROR,"NO PARAMETERS PASSED to THREAD!");
free(ptr);
return NULL;
};
me = (cortexProcessingUnit *)a->me;
if (me == NULL) {
basicLogCollection::getInstance()->Log("PU-THREAD", NULL, _LOG_ERROR, "No Self-Object Specified!");
free(ptr);
return NULL;
};
if (a->exposure == 0) a->exposure = 1.f;
if (a->saturation == 0) a->saturation = 1.f;
if (a->aspect == 0) a->aspect = 1.f;
if (a->type == OLD_CLASSIFICATION_DATA){
a->d = me->load_data_old(a->paths, a->labels, a->w, a->h);
} else if (a->type == REGRESSION_DATA){
a->d = me->load_data_regression(a->paths, a->min, a->max, a->size, a->angle, a->aspect, a->hue, a->saturation, a->exposure);
} else if (a->type == CLASSIFICATION_DATA){
a->d = me->load_data_augment(a->paths, a->labels, a->hierarchy, a->min, a->max, a->size, a->angle, a->aspect, a->hue, a->saturation, a->exposure, a->center);
} else if (a->type == SUPER_DATA){
a->d = me->load_data_super(a->paths, a->w, a->h, a->scale);
} else if (a->type == WRITING_DATA){
a->d = me->load_data_writing(a->paths, a->w, a->h, a->out_w, a->out_h);
} else if (a->type == INSTANCE_DATA){
a->d = me->load_data_iseg(a->paths, a->w, a->h, a->classes, a->num_boxes, a->coords, a->min, a->max, a->angle, a->aspect, a->hue, a->saturation, a->exposure);
} else if (a->type == SEGMENTATION_DATA){
a->d = me->load_data_seg(a->paths, a->w, a->h, a->classes, a->min, a->max, a->angle, a->aspect, a->hue, a->saturation, a->exposure, a->scale);
} else if (a->type == REGION_DATA){
a->d = me->load_data_region(a->paths, a->w, a->h, a->num_boxes, a->classes, a->jitter, a->hue, a->saturation, a->exposure);
} else if (a->type == DETECTION_DATA){
a->d = me->load_data_detection(a->paths, a->n, a->m, a->w, a->h, a->num_boxes, a->classes, a->jitter, a->hue, a->saturation, a->exposure);
} else if (a->type == SWAG_DATA){
a->d = me->load_data_swag(a->paths, a->classes, a->jitter);
} else if (a->type == COMPARE_DATA){
a->d = me->load_data_compare(a->paths, a->classes, a->w, a->h);
} else if (a->type == IMAGE_DATA){
a->im = new cortexImage();
a->im->fillFromFile(a->path, 0, 0);
a->resized = new cortexImage();
a->resized->fillFromFile(a->path, 0, 0);
a->resized->resize(a->w, a->h);
//*(a->resized) = resize_image(*(a->im), a->w, a->h);
} else if (a->type == LETTERBOX_DATA){
a->im->fillFromFile(a->path, 0, 0);
a->resized = new cortexImage();
a->resized->fillFromFile(a->path, 0, 0);
a->resized->resize(a->w, a->h);
//*(a->resized) = letterbox_image(*(a->im), a->w, a->h);
} else if (a->type == TAG_DATA){
a->d = me->load_data_tag(a->paths, a->classes, a->min, a->max, a->size, a->angle, a->aspect, a->hue, a->saturation, a->exposure);
};
free(ptr);
return NULL;
};
THREAD_HANDLE cortexProcessingUnit::load_data_in_thread(cortexTHREAD_ARGS args){
THREAD_HANDLE thread;
#ifdef WIN_THREAD
DWORD m_dwThreadID;
#endif
cortexTHREAD_ARGS *ptr = (cortexTHREAD_ARGS*)malloc(sizeof(cortexTHREAD_ARGS));
if (ptr != NULL){
*ptr = args;
#ifdef PTHREAD
if(pthread_create(&thread, 0, load_thread, ptr)) LOG_ERROR("Thread creation failed");
#else
thread = CreateThread(
NULL,
0,
(LPTHREAD_START_ROUTINE)load_thread,
(LPVOID)ptr,
0,
&m_dwThreadID);
#endif
};
return thread;
};
void cortexProcessingUnit::load_data_blocking(cortexTHREAD_ARGS *args){
cortexTHREAD_ARGS **ptr = (cortexTHREAD_ARGS **) malloc(sizeof(cortexTHREAD_ARGS*));
if(ptr != NULL){
*ptr = args;
load_thread(ptr);
};
};
void cortexProcessingUnit::print_letters(float *pred, uint32_t n){
for ( uint32_t i = 0; i < n; ++i ){
int index = 0;// max_index(pred + i*NUMCHARS, NUMCHARS);
printf("%c", int_to_alphanum(index));
}
printf("\n");
};
float cortexProcessingUnit::constrain(float min, float max, float a){
if (a < min) return min;
if (a > max) return max;
return a;
};
float cortexProcessingUnit::mag_array(float *a, uint32_t n){
float sum = 0.f;
for (uint32_t i = 0; i < n; ++i){
//sum += a[i] * a[i];
sum += fabs(a[i]);// *a[i];
};
//return (float)sqrt(sum);
return sum;
};
float cortexProcessingUnit::mag2_array(float *a, uint32_t n){
float sum = 0.f;
for (uint32_t i = 0; i < n; ++i){
//sum += a[i] * a[i];
sum += fabs(a[i]);// *a[i];
};
//return (float)sqrt(sum);
return sum*sum;
};
cortexMATRIX cortexProcessingUnit::concat_matrix(cortexMATRIX m1, cortexMATRIX m2){
uint32_t i, count = 0;
cortexMATRIX m;
m.cols = m1.cols;
m.rows = m1.rows+m2.rows;
m.values = (float**)calloc(m1.rows + m2.rows, sizeof(float*));
for(i = 0; i < m1.rows; ++i){
m.values[count++] = m1.values[i];
};
for(i = 0; i < m2.rows; ++i){
m.values[count++] = m2.values[i];
};
return m;
};
//cortexDATA load_data_captcha( cortexList *paths, int m, int k, int w, int h)
cortexDATA *cortexProcessingUnit::load_data_captcha(cortexList *paths, uint32_t n, uint32_t m, uint32_t k, uint32_t w, uint32_t h){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL) return NULL;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if( d != NULL){
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X = load_image_paths(random_paths, w, h);
d->Y = make_matrix((uint32_t)random_paths->size(), k*NUMCHARS);
int i;
i = 0;
for (cortexList::iterator index = random_paths->begin(); index < random_paths->end(); ++index){
fill_truth_captcha((*index), k, d->Y.values[i]);
i++;
};
};
free_cortexList( random_paths );
free_cortexList( paths );
return d;
};
//cortexDATA load_data_captcha_encode(cortexList *paths, int m, int w, int h)
cortexDATA *cortexProcessingUnit::load_data_captcha_encode(cortexList *paths, uint32_t n, uint32_t m, uint32_t w, uint32_t h){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL) return NULL;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X = load_image_paths(random_paths, w, h);
d->X.cols = 17100;
d->Y = d->X;
};
free_cortexList( random_paths );
free_cortexList( paths );
return d;
};
//cortexDATA *load_data_detection(cortexList *paths, int m, int w, int h, int boxes, int classes, float jitter, float hue, float saturation, float exposure)
cortexDATA *cortexProcessingUnit::load_data_detection(cortexList *paths, uint32_t n, uint32_t m, uint32_t w, uint32_t h, uint32_t boxes, uint32_t classes, float jitter, float hue, float saturation, float exposure){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL) return NULL;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if( d != NULL ){
int i;
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X.rows = (uint32_t)random_paths->size();
d->X.values = (float**)calloc(d->X.rows, sizeof(float*));
d->X.cols = h*w * 3;
d->Y = make_matrix((uint32_t)random_paths->size(), 5 * boxes);
i = 0;
for (cortexList::iterator index = random_paths->begin(); index < random_paths->end(); index++){
cortexImage *orig;
orig = new cortexImage();
orig->fillFromFile((*index), 0, 0);
cortexImage *sized;
sized = new cortexImage();
sized->makeEmpty(w, h, orig->c);
sized->fill(.5f);
float dw = jitter * orig->w;
float dh = jitter * orig->h;
float new_ar = (orig->w + rand_uniform(-dw, dw)) / (orig->h + rand_uniform(-dh, dh));
float scale = rand_uniform(.25, 2);
float nw, nh;
if (new_ar < 1){
nh = scale * h;
nw = nh * new_ar;
}
else {
nw = scale * w;
nh = nw / new_ar;
}
float dx = rand_uniform(0.f, (float)(w - nw));
float dy = rand_uniform(0.f, (float)(h - nh));
orig->place((int)nw, (int)nh, (int)dx, (int)dy, sized);
sized->randomDistort(hue, saturation, exposure);
bool flip = (rand() % 2) != 0;
if( flip ) sized->flip();
d->X.values[i] = sized->data;
fill_truth_detection((*index), boxes, d->Y.values[i], classes, flip, -dx / w, -dy / h, nw / w, nh / h);
delete(orig);
i++;
};
};
free_cortexList( random_paths );
free_cortexList( paths );
return d;
};
//cortexDATA *load_data_old(cortexList *paths, int m, cortexList *labels, int w, int h)
cortexDATA *cortexProcessingUnit::load_data_old(cortexList *paths, cortexList *labels, uint32_t w, uint32_t h){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL)return NULL;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X = load_image_paths(random_paths, w, h);
d->Y = load_labels_paths(random_paths, labels, 0);
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_tag(cortexList *paths, uint32_t k, uint32_t min, uint32_t max, uint32_t size, float angle, float aspect, float hue, float saturation, float exposure){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
memset(d, 0, sizeof(cortexDATA));
d->width = size;
d->height = size;
d->bShallow = 0;
d->X = *load_image_augment_paths(random_paths, min, max, size, angle, aspect, hue, saturation, exposure, 0);
d->Y = load_tags_paths(random_paths, k);
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexMATRIX *cortexProcessingUnit::load_image_augment_paths(cortexList *paths, uint32_t min, uint32_t max, uint32_t size, float angle, float aspect, float hue, float saturation, float exposure, uint32_t center){
cortexMATRIX *X;
int i;
X = (cortexMATRIX*)malloc(sizeof(cortexMATRIX));
if( X != NULL ){
X->rows = (uint32_t) paths->size();
X->values = (float**)calloc(X->rows, sizeof(float*));
X->cols = 0;
i = 0;
for (cortexList::iterator index = paths->begin(); index < paths->end(); index++){
cortexImage *im;
im = new cortexImage();
im->fillFromFile((*index), 0, 0);
if(center){
im->centerCrop( size, size);
} else {
im->randomAugment( angle, aspect, min, max, size, size );
};
bool flip = (rand()%2) != 0;
if (flip) im->flip();// flip_image(crop);
im->randomDistort( hue, saturation, exposure );
/*
show_image(im, "orig");
show_image(crop, "crop");
cvWaitKey(0);
*/
X->values[i] = im->data;
X->cols = im->h*im->w*im->c;
i++;
};
};
return X;
};
cortexDATA *cortexProcessingUnit::load_data_super(cortexList *paths, uint32_t w, uint32_t h, uint32_t scale){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if(random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if( d != NULL ){
int i;
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X.rows = (uint32_t)paths->size();
d->X.values = (float**)calloc(paths->size(), sizeof(float*));
d->X.cols = w*h * 3;
d->Y.rows = (uint32_t)paths->size();
d->Y.values = (float**)calloc(paths->size(), sizeof(float*));
d->Y.cols = w*scale * h*scale * 3;
i = 0;
for (cortexList::iterator index = paths->begin(); index < paths->end(); ++index){
cortexImage *im;
im = new cortexImage();
if( im != NULL ){
im->fillFromFile((*index), 0, 0);
im->randomCrop(w*scale, h*scale);
bool flip = ( rand() % 2 ) != 0;
if (flip) im->flip();
cortexImage *im2;
im2 = new cortexImage(im);
if( im2 != NULL ){
im2->resize(w, h);
d->X.values[i] = im2->data;
d->Y.values[i] = im->data;
delete(im2);
};
delete(im);
};
i++;
};
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_augment(cortexList *paths, cortexList *labels, cortexTREE *hierarchy, uint32_t min, uint32_t max, uint32_t size, float angle, float aspect, float hue, float saturation, float exposure, uint32_t center){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if(random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if( d != NULL ){
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X = *load_image_augment_paths(paths, min, max, size, angle, aspect, hue, saturation, exposure, center);
d->Y = load_labels_paths(paths, labels, hierarchy);
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_regression(cortexList *paths, uint32_t min, uint32_t max, uint32_t size, float angle, float aspect, float hue, float saturation, float exposure){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if(random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if( d != NULL ){
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X = *load_image_augment_paths(random_paths, min, max, size, angle, aspect, hue, saturation, exposure, 0);
d->Y = load_regression_labels_paths(random_paths);
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_go(char *filename){
FILE *fp;
if( filename == NULL ){
LOG_ERROR( "Invalid filename supplied!" );
return NULL;
};
fp = fopen(filename, "rb");
if( fp == NULL ){
LOG_ERROR( "Can not open file filename!" );
return NULL;
};
cortexMATRIX X = make_matrix(3363059, 361);
cortexMATRIX y = make_matrix(3363059, 361);
int row, col;
char *label;
int count = 0;
while((label = fgetl(fp))){
int i;
if(count == X.rows){
X = resize_matrix(X, count*2);
y = resize_matrix(y, count*2);
}
sscanf(label, "%d %d", &row, &col);
char *board = fgetl(fp);
int index = row*19 + col;
y.values[count][index] = 1;
for(i = 0; i < 19*19; ++i){
float val = 0;
if(board[i] == '1') val = 1;
else if(board[i] == '2') val = -1;
X.values[count][i] = val;
}
++count;
free(label);
free(board);
}
X = resize_matrix(X, count);
y = resize_matrix(y, count);
cortexDATA *d;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X = X;
d->Y = y;
fclose(fp);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_writing(cortexList *paths, uint32_t w, uint32_t h, uint32_t out_w, uint32_t out_h){
cortexList *random_paths = get_random_paths( paths );
cortexList *replace_paths = find_replace_paths(random_paths, ".png", "-label.png");
cortexDATA *d = (cortexDATA *)malloc(sizeof(cortexDATA));
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X = load_image_paths(paths, w, h);
d->Y = load_image_paths_gray(replace_paths, out_w, out_h);
free_cortexList(replace_paths);
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
void cortexProcessingUnit::get_random_batch(cortexDATA *d, uint32_t n, float *X, float *Y){
for (uint32_t j = 0; j < n; ++j){
int index = rand() % d->X.rows;
memcpy(X + j*d->X.cols, d->X.values[index], d->X.cols*sizeof(float));
memcpy(Y + j*d->Y.cols, d->Y.values[index], d->Y.cols*sizeof(float));
};
};
cortexDATA *cortexProcessingUnit::get_data_part(cortexDATA *d, uint32_t part, uint32_t total){
cortexDATA *p = (cortexDATA *)malloc(sizeof(cortexDATA));
if( p!= NULL ){
memset(p, 0, sizeof(cortexDATA));
p->bShallow = true;
p->X.rows = d->X.rows * (part + 1) / total - d->X.rows * part / total;
p->Y.rows = d->Y.rows * (part + 1) / total - d->Y.rows * part / total;
p->X.cols = d->X.cols;
p->Y.cols = d->Y.cols;
p->X.values = d->X.values + d->X.rows * part / total;
p->Y.values = d->Y.values + d->Y.rows * part / total;
};
return p;
};
cortexDATA *cortexProcessingUnit::get_random_data(cortexDATA *d, uint32_t num){
cortexDATA *r = (cortexDATA *)malloc(sizeof(cortexDATA));
if( r!=NULL ){
memset(r, 0, sizeof(cortexDATA));
r->bShallow = true;
r->X.rows = num;
r->Y.rows = num;
r->X.cols = r->X.cols;
r->Y.cols = r->Y.cols;
r->X.values = (float**)calloc(num, sizeof(float *));
r->Y.values = (float**)calloc(num, sizeof(float *));
for(size_t i = 0; i < num; ++i){
int index = rand() % d->X.rows;
r->X.values[i] = d->X.values[index];
r->Y.values[i] = d->Y.values[index];
};
};
return r;
};
cortexDATA *cortexProcessingUnit::load_categorical_data_csv(char *filename, uint32_t target, uint32_t k){
cortexDATA *d;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if( d!= NULL ){
memset(d, 0, sizeof(cortexDATA));
d->bShallow = 0;
cortexMATRIX X = csv_to_matrix(filename);
float *truth_1d = pop_column(&X, target);
float **truth = one_hot_encode(truth_1d, X.rows, k);
cortexMATRIX Y;
Y.rows = X.rows;
Y.cols = k;
Y.values = truth;
d->X = X;
d->Y = Y;
free(truth_1d);
};
return d;
};
void cortexProcessingUnit::normalize_data_rows(cortexDATA *d){
};
void cortexProcessingUnit::scale_data_rows(cortexDATA *d, float s){
};
void cortexProcessingUnit::translate_data_rows(cortexDATA *d, float s){
};
void cortexProcessingUnit::randomize_data(cortexDATA *d){
};
cortexDATA **cortexProcessingUnit::split_data(cortexDATA *d, uint32_t part, uint32_t total){
cortexDATA **split = (cortexDATA **)calloc(2, sizeof(cortexDATA*));
if( split != NULL ){
cortexDATA *train = (cortexDATA *)malloc(sizeof(cortexDATA));
if( train == NULL ) {
free(split);
return NULL;
};
cortexDATA *test = (cortexDATA *)malloc(sizeof(cortexDATA));
if( test == NULL ){
free( split );
free( train );
return NULL;
};
memset(train, 0, sizeof(cortexDATA));
memset(test, 0, sizeof(cortexDATA));
uint32_t start = part*d->X.rows / total;
uint32_t end = (part + 1)*d->X.rows / total;
train->bShallow = test->bShallow = true;
test->X.rows = test->Y.rows = end - start;
train->X.rows = train->Y.rows = d->X.rows - (end - start);
train->X.cols = test->X.cols = d->X.cols;
train->Y.cols = test->Y.cols = d->Y.cols;
train->X.values = (float**)calloc(train->X.rows, sizeof(float*));
train->Y.values = (float**)calloc(train->Y.rows, sizeof(float*));
test->X.values = (float**)calloc(test->X.rows, sizeof(float*));
test->Y.values = (float**)calloc(test->Y.rows, sizeof(float*));
for(size_t i = 0; i < start; ++i){
train->X.values[i] = d->X.values[i];
train->Y.values[i] = d->Y.values[i];
};
for(size_t i = start; i < end; ++i){
test->X.values[i - start] = d->X.values[i];
test->Y.values[i - start] = d->Y.values[i];
};
for(size_t i = end; i < d->X.rows; ++i){
train->X.values[i - (end - start)] = d->X.values[i];
train->Y.values[i - (end - start)] = d->Y.values[i];
};
split[0] = train;
split[1] = test;
};
return split;
};
cortexDATA *cortexProcessingUnit::concat_data(cortexDATA *d1, cortexDATA *d2){
cortexDATA *out;
out = (cortexDATA *)malloc(sizeof(cortexDATA));
if( out!= NULL ){
memset(out, 0, sizeof(cortexDATA));
out->bShallow = true;
out->X = concat_matrix(d1->X, d2->X);
out->Y = concat_matrix(d1->Y, d2->Y);
};
return out;
};
cortexDATA *cortexProcessingUnit::concat_datas(cortexDATA *d, uint32_t n){
cortexDATA *out;
out = (cortexDATA *)malloc(sizeof(cortexDATA));
if( out!=NULL ){
memset(out, 0, sizeof(cortexDATA));
for(size_t i = 0; i < n; ++i){
cortexDATA *nw = concat_data(&d[i], out);
free_data(out);
out = nw;
};
};
return out;
};
void cortexProcessingUnit::fill_truth(char *path, cortexList *labels, /*size_t k,*/ float *truth){
int i = 0, count = 0;
memset(truth, 0, labels->size()*sizeof(float));
for (cortexList::iterator index = labels->begin(); index < labels->end(); ++index){
if (strstr(path, (*index))){
truth[i] = 1.0f;
++count;
};
i++;
};
#ifdef _DEBUG
if (count != 1 && (labels->size() != 1 || count != 0)){
char tBuffer[1024];
sprintf(tBuffer, "Too many or too few labels: %d, %s", count, path);
LOG(tBuffer);
};
#endif
};
cortexList *cortexProcessingUnit::get_random_paths(cortexList *paths, uint32_t limit){
cortexList *mList;
mList = new cortexList();
if (mList != NULL){
//MUTEX_LOCK(mutex);
//mList->assign(paths->size(), NULL);
if (limit == 0 || limit > (uint32_t)paths->size()) limit = (uint32_t)paths->size();
for (cortexList::iterator index = paths->begin(); index < paths->end(); index++) mList->push_back( *index );
std::random_shuffle(mList->begin(), mList->end());
//MUTEX_UNLOCK(&mutex);
} else LOG_ERROR("Memmory Allocation Error!");
return mList;
};
cortexList *cortexProcessingUnit::find_replace_paths(cortexList *paths, char *find, char *replace){
cortexList *mList;
mList = new cortexList();
if (mList != NULL){
for (cortexList::iterator index = paths->begin(); index < paths->end(); index++){
char replaced[4096];
find_replace((*index), find, replace, replaced);
mList->push_back(copy_string(replaced));
};
};
return mList;
};
cortexDATA *cortexProcessingUnit::load_data_compare(cortexList *paths, uint32_t classes, uint32_t w, uint32_t h, uint32_t limit){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths, 2 * limit); // get_random_paths(paths, 2 * n, m);
if (random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
uint32_t i, j;
uint32_t n;
n = ((uint32_t)random_paths->size()) >> 1;
memset(d, 0, sizeof(cortexDATA));
d->bShallow = false;
d->X.rows = n;
d->X.values = (float**)calloc(d->X.rows, sizeof(float*));
d->X.cols = h*w * 6;
uint32_t k = 2 * (classes);
d->Y = make_matrix(n, k);
for (i = 0; i < n; ++i){
cortexImage im1;
cortexImage im2;
im1.fillFromFile(random_paths->at(i * 2), w, h);
im2.fillFromFile(random_paths->at(i * 2 + 1), w, h);
d->X.values[i] = (float*)calloc(d->X.cols, sizeof(float));
memcpy(d->X.values[i], im1.data, h*w * 3 * sizeof(float));
memcpy(d->X.values[i] + h*w * 3, im2.data, h*w * 3 * sizeof(float));
int id;
float iou;
char imlabel1[4096];
char imlabel2[4096];
find_replace(random_paths->at(i * 2), "imgs", "labels", imlabel1);
find_replace(imlabel1, "jpg", "txt", imlabel1);
FILE *fp1 = fopen(imlabel1, "r");
while (fscanf(fp1, "%d %f", &id, &iou) == 2){
if (d->Y.values[i][2 * id] < iou) d->Y.values[i][2 * id] = iou;
};
find_replace(random_paths->at(i * 2+1), "imgs", "labels", imlabel2);
find_replace(imlabel2, "jpg", "txt", imlabel2);
FILE *fp2 = fopen(imlabel2, "r");
while (fscanf(fp2, "%d %f", &id, &iou) == 2){
if (d->Y.values[i][2 * id + 1] < iou) d->Y.values[i][2 * id + 1] = iou;
};
for (j = 0; j < classes; ++j){
if (d->Y.values[i][2 * j] > .5 && d->Y.values[i][2 * j + 1] < .5){
d->Y.values[i][2 * j] = 1;
d->Y.values[i][2 * j + 1] = 0;
} else if (d->Y.values[i][2 * j] < .5 && d->Y.values[i][2 * j + 1] > .5){
d->Y.values[i][2 * j] = 0;
d->Y.values[i][2 * j + 1] = 1;
} else {
d->Y.values[i][2 * j] = SECRET_NUM;
d->Y.values[i][2 * j + 1] = SECRET_NUM;
};
};
fclose(fp1);
fclose(fp2);
//free_image(im1);
//free_image(im2);
};
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_seg(cortexList *paths, uint32_t w, uint32_t h, uint32_t classes, uint32_t min, uint32_t max, float angle, float aspect, float hue, float saturation, float exposure, bool div){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
memset(d, 0, sizeof(cortexDATA));
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_iseg(cortexList *paths, uint32_t w, uint32_t h, uint32_t classes, uint32_t boxes, uint32_t coords, uint32_t min, uint32_t max, float angle, float aspect, float hue, float saturation, float exposure){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
memset(d, 0, sizeof(cortexDATA));
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_region(cortexList *paths, uint32_t w, uint32_t h, uint32_t size, uint32_t classes, float jitter, float hue, float saturation, float exposure){
cortexList *random_paths;
cortexDATA *d;
random_paths = get_random_paths(paths);
if (random_paths == NULL){
free_cortexList(paths);
return NULL;
};
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
memset(d, 0, sizeof(cortexDATA));
};
free_cortexList(random_paths);
free_cortexList(paths);
return d;
};
cortexDATA *cortexProcessingUnit::load_data_swag(cortexList *paths, uint32_t classes, float jitter){
cortexDATA *d;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
if (d != NULL){
memset(d, 0, sizeof(cortexDATA));
int index = rand() % paths->size();
char *random_path = paths->at(index);
cortexImage *orig;
orig = new cortexImage();
orig->fillFromFile(random_path, 0, 0);
int h = orig->h;
int w = orig->w;
cortexDATA *d;
d = (cortexDATA *)malloc(sizeof(cortexDATA));
memset(d, 0, sizeof(cortexDATA));
d->bShallow = 0;
d->width = w;
d->height = h;
d->X.rows = 1;
d->X.values = (float**)calloc(d->X.rows, sizeof(float*));
d->X.cols = h*w * 3;
int k = (4 + classes) * 30;
d->Y = make_matrix(1, k);
int dw = (int)(w*jitter);
int dh = (int)(h*jitter);
int pleft = (int)rand_uniform((float)-dw, (float)dw);
int pright = (int)rand_uniform((float)-dw, (float)dw);
int ptop = (int)rand_uniform((float)-dh, (float)dh);
int pbot = (int)rand_uniform((float)-dh, (float)dh);
int swidth = w - pleft - pright;
int sheight = h - ptop - pbot;
float sx = (float)(swidth / w);
float sy = (float)(sheight / h);
bool flip = ( rand() % 2 ) != 0;
orig->crop(pleft, ptop, swidth, sheight);
float dx = ((float)pleft / w) / sx;
float dy = ((float)ptop / h) / sy;
orig->resize(w, h);
if (flip) orig->flip();
d->X.values[0] = orig->data;
fill_truth_swag(random_path, d->Y.values[0], classes, (float)dx, (float)dy, 1.f / sx, 1.f / sy, flip);
delete(orig);
};
return d;
};
cortexMATRIX cortexProcessingUnit::load_regression_labels_paths(cortexList *paths){
cortexMATRIX y = make_matrix((uint32_t)paths->size(), 1);
uint32_t i;
i = 0;
for (cortexList::iterator index = paths->begin(); index < paths->end(); index++){
char labelpath[4096];
find_replace((*index), "images", "targets", labelpath);
find_replace(labelpath, "JPEGImages", "targets", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".png", ".txt", labelpath);
FILE *file = fopen(labelpath, "r");
fscanf(file, "%f", &(y.values[i][0]));
fclose(file);
i++;
};
return y;
};
cortexMATRIX cortexProcessingUnit::load_labels_paths(cortexList *paths, cortexList *labels, cortexTREE *hierarchy){
cortexMATRIX y = make_matrix((uint32_t)paths->size(), (uint32_t)labels->size());
int i;
i = 0;
for (cortexList::iterator index = paths->begin(); index < paths->end(); index++){
fill_truth((*index), labels, y.values[i]);
if (hierarchy){
fill_hierarchy(y.values[i], (uint32_t)labels->size(), hierarchy);
}
i++;
};
return y;
};
cortexMATRIX cortexProcessingUnit::load_tags_paths(cortexList *paths, uint32_t k){
cortexMATRIX y = make_matrix((uint32_t)paths->size(), k);
int i;
int count = 0;
i = 0;
for (cortexList::iterator index = paths->begin(); index < paths->end(); index){
char label[4096];
find_replace((*index), "imgs", "labels", label);
find_replace(label, "_iconl.jpeg", ".txt", label);
FILE *file = fopen(label, "r");
if (!file){
find_replace(label, "labels", "labels2", label);
file = fopen(label, "r");
if (!file) continue;
}
++count;
uint32_t tag;
while (fscanf(file, "%d", &tag) == 1){
if (tag < k){
y.values[i][tag] = 1;
};
};
fclose(file);
};
printf( "%d/%d\n", count, (uint32_t) paths->size());
return y;
};
void cortexProcessingUnit::fill_truth_swag(char *path, float *truth, uint32_t classes, float dx, float dy, float sx, float sy, bool flip){
char labelpath[4096];
find_replace(path, "images", "labels", labelpath);
find_replace(labelpath, "JPEGImages", "labels", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
uint32_t count = 0;
cortexBOXLABEL *boxes = read_boxes(labelpath, &count);
randomize_boxes(boxes, count);
correct_boxes(boxes, count, dx, dy, sx, sy, flip);
float x, y, w, h;
uint32_t i, id;
for (i = 0; i < count && i < 30; ++i) {
x = boxes[i].x;
y = boxes[i].y;
w = boxes[i].w;
h = boxes[i].h;
id = boxes[i].id;
if (w < .0 || h < .0) continue;
int index = (4 + classes) * i;
truth[index++] = x;
truth[index++] = y;
truth[index++] = w;
truth[index++] = h;
if (id < classes) truth[index + id] = 1;
}
free(boxes);
};
void cortexProcessingUnit::fill_hierarchy(float *truth, uint32_t k, cortexTREE *hierarchy){
for (size_t j = 0; j < k; ++j){
if (truth[j]){
uint32_t parent = hierarchy->parent[j];
while (parent >= 0){
truth[parent] = 1.0f;
parent = hierarchy->parent[parent];
};
};
};
size_t count = 0;
for (size_t j = 0; j < hierarchy->groups; ++j){
//printf("%d\n", count);
bool mask = true;
for (size_t i = 0; i < hierarchy->group_size[j]; ++i){
if (truth[count + i]){
mask = false;
break;
};
};
if( mask ){
for (size_t i = 0; i < hierarchy->group_size[j]; ++i){
truth[count + i] = SECRET_NUM;
};
};
count += hierarchy->group_size[j];
};
};
void cortexProcessingUnit::fill_truth_captcha(char *path, uint32_t n, float *truth){
char *begin = strrchr(path, '/');
++begin;
size_t i;
for (i = 0; i < (int)strlen(begin) && i < n && begin[i] != '.'; ++i){
int index = alphanum_to_int(begin[i]);
if (index > 35) printf("Bad %c\n", begin[i]);
truth[i*NUMCHARS + index] = 1;
};
for (; i < n; ++i){
truth[i*NUMCHARS + NUMCHARS - 1] = 1;
};
};
void cortexProcessingUnit::fill_truth_detection(char *path, uint32_t num_boxes, float *truth, uint32_t classes, bool flip, float dx, float dy, float sx, float sy){
char labelpath[4096];
find_replace(path, "images", "labels", labelpath);
find_replace(labelpath, "JPEGImages", "labels", labelpath);
find_replace(labelpath, "raw", "labels", labelpath);
find_replace(labelpath, ".jpg", ".txt", labelpath);
find_replace(labelpath, ".png", ".txt", labelpath);
find_replace(labelpath, ".JPG", ".txt", labelpath);
find_replace(labelpath, ".JPEG", ".txt", labelpath);
uint32_t count = 0;
cortexBOXLABEL *boxes = read_boxes(labelpath, &count);
randomize_boxes(boxes, count);
correct_boxes(boxes, count, dx, dy, sx, sy, flip);
if (count > num_boxes) count = num_boxes;
float x, y, w, h;
size_t id, i;
for (i = 0; i < count; ++i) {
x = boxes[i].x;
y = boxes[i].y;
w = boxes[i].w;
h = boxes[i].h;
id = boxes[i].id;
if ((w < .001 || h < .001)) continue;
truth[i * 5 + 0] = x;
truth[i * 5 + 1] = y;
truth[i * 5 + 2] = w;
truth[i * 5 + 3] = h;
truth[i * 5 + 4] = (float)id;
}
free(boxes);
};
cortexMATRIX cortexProcessingUnit::load_image_paths_gray(cortexList *paths, uint32_t w, uint32_t h){
cortexMATRIX X;
uint32_t i;
X.rows = (uint32_t)paths->size();
X.values = (float**)calloc(X.rows, sizeof(float*));
X.cols = 0;
i = 0;
for (cortexList::iterator index = paths->begin(); index < paths->end(); index++){
cortexImage *im;
im = new cortexImage();
im->fillFromFile((*index), w, h);
im->grayscale();
X.values[i] = im->data;
X.cols = im->h*im->w*im->c;
i++;
};
return X;
};
cortexMATRIX cortexProcessingUnit::load_image_paths(cortexList *paths, uint32_t w, uint32_t h){
cortexMATRIX X;
uint32_t i;
X.rows = (uint32_t)paths->size();
X.values = (float**)calloc(X.rows, sizeof(float*));
X.cols = 0;
i = 0;
for (cortexList::iterator index = paths->begin(); index < paths->end(); index++){
cortexImage *im;
im = new cortexImage();
im->fillFromFile((*index), w, h);
X.values[i] = im->data;
X.cols = im->h*im->w*im->c;
i++;
};
return X;
};
cortexBOXLABEL *cortexProcessingUnit::read_boxes(char *filename, uint32_t *n){
cortexBOXLABEL *boxes = (cortexBOXLABEL*)calloc(1, sizeof(cortexBOXLABEL));
FILE *file = fopen(filename, "r");
if (!file) return NULL;
float x, y, h, w;
uint32_t id;
uint32_t count = 0;
while (fscanf(file, "%d %f %f %f %f", &id, &x, &y, &w, &h) == 5){
boxes = (cortexBOXLABEL*)realloc(boxes, (count + 1)*sizeof(cortexBOXLABEL));
boxes[count].id = id;
boxes[count].x = x;
boxes[count].y = y;
boxes[count].h = h;
boxes[count].w = w;
boxes[count].left = x - w / 2;
boxes[count].right = x + w / 2;
boxes[count].top = y - h / 2;
boxes[count].bottom = y + h / 2;
++count;
}
fclose(file);
*n = count;
return boxes;
};
void cortexProcessingUnit::randomize_boxes(cortexBOXLABEL *b, uint32_t n){
for (uint32_t i = 0; i < n; ++i){
cortexBOXLABEL swap = b[i];
int index = rand() % n;
b[i] = b[index];
b[index] = swap;
};
};
void cortexProcessingUnit::correct_boxes(cortexBOXLABEL *boxes, uint32_t n, float dx, float dy, float sx, float sy, bool flip){
for (uint32_t i = 0; i < n; ++i){
if (boxes[i].x == 0 && boxes[i].y == 0) {
boxes[i].x = 999999;
boxes[i].y = 999999;
boxes[i].w = 999999;
boxes[i].h = 999999;
continue;
};
boxes[i].left = boxes[i].left * sx - dx;
boxes[i].right = boxes[i].right * sx - dx;
boxes[i].top = boxes[i].top * sy - dy;
boxes[i].bottom = boxes[i].bottom* sy - dy;
if (flip){
float swap = boxes[i].left;
boxes[i].left = 1.f - boxes[i].right;
boxes[i].right = 1.f - swap;
};
boxes[i].left = constrain(0, 1, boxes[i].left);
boxes[i].right = constrain(0, 1, boxes[i].right);
boxes[i].top = constrain(0, 1, boxes[i].top);
boxes[i].bottom = constrain(0, 1, boxes[i].bottom);
boxes[i].x = (boxes[i].left + boxes[i].right) / 2;
boxes[i].y = (boxes[i].top + boxes[i].bottom) / 2;
boxes[i].w = (boxes[i].right - boxes[i].left);
boxes[i].h = (boxes[i].bottom - boxes[i].top);
boxes[i].w = constrain(0, 1, boxes[i].w);
boxes[i].h = constrain(0, 1, boxes[i].h);
};
};
void cortexProcessingUnit::free_data(cortexDATA *d){
if (!d->bShallow){
free_matrix(d->X);
free_matrix(d->Y);
} else{
free(d->X.values);
free(d->Y.values);
};
};
void cortexProcessingUnit::free_data(cortexDATA d){
if (!d.bShallow){
free_matrix(d.X);
free_matrix(d.Y);
} else{
free(d.X.values);
free(d.Y.values);
};
};
bool cortexProcessingUnit::col2im_add_pixel(float *im, uint32_t height, uint32_t width, uint32_t channels, uint32_t row, uint32_t col, uint32_t channel, uint32_t pad, float val){
row -= pad;
col -= pad;
if (row < 0 || col < 0 || row >= height || col >= width) return false;
im[col + width*(row + height*channel)] += val;
return true;
};
//This one might be too, can't remember.
void cortexProcessingUnit::col2im(float* data_col,
uint32_t channels, uint32_t height, uint32_t width,
uint32_t ksize, uint32_t stride, uint32_t pad, float* data_im){
uint32_t c, h, w;
uint32_t height_col = (height + 2 * pad - ksize) / stride + 1;
uint32_t width_col = (width + 2 * pad - ksize) / stride + 1;
uint32_t channels_col = channels * ksize * ksize;
for (c = 0; c < channels_col; ++c) {
uint32_t w_offset = c % ksize;
uint32_t h_offset = (c / ksize) % ksize;
uint32_t c_im = c / ksize / ksize;
for (h = 0; h < height_col; ++h) {
for (w = 0; w < width_col; ++w) {
uint32_t im_row = h_offset + h * stride;
uint32_t im_col = w_offset + w * stride;
uint32_t col_index = (c * height_col + h) * width_col + w;
float val = data_col[col_index];
col2im_add_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad, val);
};
};
};
};
float cortexProcessingUnit::im2col_get_pixel(float *im, uint32_t height, uint32_t width, uint32_t channels,
uint32_t row, uint32_t col, uint32_t channel, uint32_t pad){
row -= pad;
col -= pad;
if (row < 0 || col < 0 ||
row >= height || col >= width) return 0;
return im[col + width*(row + height*channel)];
}
//From Berkeley Vision's Caffe!
//https://github.com/BVLC/caffe/blob/master/LICENSE
void cortexProcessingUnit::im2col(float* data_im,
uint32_t channels, uint32_t height, uint32_t width,
uint32_t ksize, uint32_t stride, uint32_t pad, float* data_col){
uint32_t c, h, w;
uint32_t height_col = (height + 2 * pad - ksize) / stride + 1;
uint32_t width_col = (width + 2 * pad - ksize) / stride + 1;
uint32_t channels_col = channels * ksize * ksize;
for (c = 0; c < channels_col; ++c) {
uint32_t w_offset = c % ksize;
uint32_t h_offset = (c / ksize) % ksize;
uint32_t c_im = c / ksize / ksize;
for (h = 0; h < height_col; ++h) {
for (w = 0; w < width_col; ++w) {
uint32_t im_row = h_offset + h * stride;
uint32_t im_col = w_offset + w * stride;
uint32_t col_index = (c * height_col + h) * width_col + w;
data_col[col_index] = im2col_get_pixel(data_im, height, width, channels,
im_row, im_col, c_im, pad);
};
};
};
};
char *cortexProcessingUnit::getActivationString(ACTIVATION a){
switch (a){
case LOGISTIC:
return "logistic";
case LOGGY:
return "loggy";
case RELU:
return "relu";
case ELU:
return "elu";
case RELIE:
return "relie";
case RAMP:
return "ramp";
case LINEAR:
return "linear";
case TANH:
return "tanh";
case PLSE:
return "plse";
case LEAKY:
return "leaky";
case STAIR:
return "stair";
case HARDTAN:
return "hardtan";
case LHTAN:
return "lhtan";
default:
break;
};
return "relu";
};
ACTIVATION cortexProcessingUnit::getActivation(char *s){
if (strcmp(s, "logistic") == 0) return LOGISTIC;
if (strcmp(s, "loggy") == 0) return LOGGY;
if (strcmp(s, "relu") == 0) return RELU;
if (strcmp(s, "elu") == 0) return ELU;
if (strcmp(s, "relie") == 0) return RELIE;
if (strcmp(s, "plse") == 0) return PLSE;
if (strcmp(s, "hardtan") == 0) return HARDTAN;
if (strcmp(s, "lhtan") == 0) return LHTAN;
if (strcmp(s, "linear") == 0) return LINEAR;
if (strcmp(s, "ramp") == 0) return RAMP;
if (strcmp(s, "leaky") == 0) return LEAKY;
if (strcmp(s, "tanh") == 0) return TANH;
if (strcmp(s, "stair") == 0) return STAIR;
char tBuffer[256];
sprintf(tBuffer, "Couldn't find activation function %s, going with ReLU\n", s);
LOG_ERROR(tBuffer);
return RELU;
};
static inline float stair_activate(float x){
int n = (int)floor(x);
if (n % 2 == 0) return (float)floor(x / 2.f);
else return (float)((x - n) + floor(x / 2.f));
};
static inline float hardtan_activate(float x){
if (x < -1) return -1;
if (x > 1) return 1;
return x;
};
static inline float linear_activate(float x){ return x; };
static inline float logistic_activate(float x){ return (float)(1.f / (1.f + exp(-x))); };
static inline float loggy_activate(float x){ return (float)(2.f / (1.f + exp(-x)) - 1.f); };
static inline float relu_activate(float x){ return x*(x > 0.f); };
static inline float elu_activate(float x){ return (float)((x >= 0.f)*x + (x < 0.f)*(exp(x) - 1.f)); };
static inline float relie_activate(float x){ return (x>0.f) ? x : .01f*x; };
static inline float ramp_activate(float x){ return x*(x > 0.f) + .1f*x; };
static inline float leaky_activate(float x){ return (x > 0.f) ? x : .1f*x; };
static inline float tanh_activate(float x){ return (float)((exp(2.f*x) - 1.f) / (exp(2.f*x) + 1.f)); };
static inline float plse_activate(float x){
if (x < -4.f) return .01f * (x + 4.f);
if (x > 4.f) return .01f * (x - 4.f) + 1.f;
return .125f*x + .5f;
};
static inline float lhtan_activate(float x){
if (x < 0.f) return .001f*x;
if (x > 1.f) return .001f*(x - 1.f) + 1.f;
return x;
};
static inline float lhtan_gradient(float x){
if (x > 0.f && x < 1.f) return 1.f;
return .001f;
};
static inline float hardtan_gradient(float x){
if (x > -1.f && x < 1.f) return 1.f;
return 0.f;
};
static inline float linear_gradient(float x){ return 1.f; };
static inline float logistic_gradient(float x){ return (1.f - x)*x; };
static inline float loggy_gradient(float x){
float y = (x + 1.f) / 2.f;
return 2.f*(1.f - y)*y;
};
static inline float stair_gradient(float x){
if (floor(x) == x) return 0.f;
return 1.f;
};
static inline float relu_gradient(float x){ return (float)(x > 0.f); };
static inline float elu_gradient(float x){ return (x >= 0.f) + (x < 0.f)*(x + 1.f); };
static inline float relie_gradient(float x){ return (x>0.f) ? 1.f : .01f; };
static inline float ramp_gradient(float x){ return (x > 0.f) + .1f; };
static inline float leaky_gradient(float x){ return (x > 0.f) ? 1.f : .1f; };
static inline float tanh_gradient(float x){ return 1.f - x*x; };
static inline float plse_gradient(float x){ return (x < 0.f || x > 1.f) ? .01f : .125f; };
float cortexProcessingUnit::makeActivated(float x, ACTIVATION a){
switch (a){
case LINEAR:
return linear_activate(x);
case LOGISTIC:
return logistic_activate(x);
case LOGGY:
return loggy_activate(x);
case RELU:
return relu_activate(x);
case ELU:
return elu_activate(x);
case RELIE:
return relie_activate(x);
case RAMP:
return ramp_activate(x);
case LEAKY:
return leaky_activate(x);
case TANH:
return tanh_activate(x);
case PLSE:
return plse_activate(x);
case STAIR:
return stair_activate(x);
case HARDTAN:
return hardtan_activate(x);
case LHTAN:
return lhtan_activate(x);
};
return 0;
};
bool cortexProcessingUnit::makeActivatedArray(float *x, const uint32_t n, const ACTIVATION a){
for (uint32_t i = 0; i < n; ++i){
x[i] = makeActivated(x[i], a);
};
return true;
};
float cortexProcessingUnit::makeGradient(float x, ACTIVATION a){
switch (a){
case LINEAR:
return linear_gradient(x);
case LOGISTIC:
return logistic_gradient(x);
case LOGGY:
return loggy_gradient(x);
case RELU:
return relu_gradient(x);
case ELU:
return elu_gradient(x);
case RELIE:
return relie_gradient(x);
case RAMP:
return ramp_gradient(x);
case LEAKY:
return leaky_gradient(x);
case TANH:
return tanh_gradient(x);
case PLSE:
return plse_gradient(x);
case STAIR:
return stair_gradient(x);
case HARDTAN:
return hardtan_gradient(x);
case LHTAN:
return lhtan_gradient(x);
};
return 0.f;
};
bool cortexProcessingUnit::makeGradientArray(float *x, uint32_t n, ACTIVATION a, float *delta){
for (uint32_t i = 0; i < n; ++i){
delta[i] *= makeGradient(x[i], a);
};
return true;
};
void cortexProcessingUnit::transposeMatrix(float *a, int rows, int cols){
float *transpose = (float*)calloc(rows*cols, sizeof(float));
int x, y;
for (x = 0; x < rows; ++x){
for (y = 0; y < cols; ++y){
transpose[y*rows + x] = a[x*cols + y];
}
}
memcpy(a, transpose, rows*cols*sizeof(float));
free(transpose);
}
float cortexProcessingUnit::calcSumArray(float *a, size_t n){
float sum = 0;
for (size_t i = 0; i < n; ++i) sum += a[i];
return sum;
};
float cortexProcessingUnit::calcMeanArray(float *a, size_t n){
return calcSumArray(a, n) / n;
};
float cortexProcessingUnit::calcVarianceArray(float *a, size_t n){
float sum = 0;
float mean = calcMeanArray( a, n );
for (size_t i = 0; i < n; ++i) sum += (a[i] - mean)*(a[i] - mean);
return sum / n;
};
inline int cortexProcessingUnit::calcConstrain(int a, int min, int max){
if (a < min) return min;
if (a > max) return max;
return a;
};
inline float cortexProcessingUnit::calcConstrain(float a, float min, float max){
if (a < min) return min;
if (a > max) return max;
return a;
};
size_t cortexProcessingUnit::calcMaxIndex(float *a, size_t n){
if (n <= 0) return -1;
int i, max_i = 0;
float max = a[0];
for (i = 1; i < n; ++i){
if (a[i] > max){
max = a[i];
max_i = i;
}
}
return max_i;
};
int cortexProcessingUnit::calcRandInt(int min, int max){
if (max < min){
int s = min;
min = max;
max = s;
}
int r = (rand() % (max - min + 1)) + min;
return r;
};
// From http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
float cortexProcessingUnit::calcRandNormal(void){
static int haveSpare = 0;
static double rand1, rand2;
if (haveSpare){
haveSpare = 0;
return (float)(sqrt(rand1) * sin(rand2));
};
haveSpare = 1;
rand1 = rand() / ((double)RAND_MAX);
if (rand1 < 1e-100) rand1 = 1e-100;
rand1 = -2 * log(rand1);
rand2 = (rand() / ((double)RAND_MAX)) * TWO_PI;
return (float)(sqrt(rand1) * cos(rand2));
};
/*
float rand_normal()
{
int n = 12;
int i;
float sum= 0;
for(i = 0; i < n; ++i) sum += (float)rand()/RAND_MAX;
return sum-n/2.;
}
*/
size_t cortexProcessingUnit::calcRandIndex(void){
return ((size_t)(rand() & 0xff) << 56) |
((size_t)(rand() & 0xff) << 48) |
((size_t)(rand() & 0xff) << 40) |
((size_t)(rand() & 0xff) << 32) |
((size_t)(rand() & 0xff) << 24) |
((size_t)(rand() & 0xff) << 16) |
((size_t)(rand() & 0xff) << 8) |
((size_t)(rand() & 0xff) << 0);
};
float cortexProcessingUnit::calcRandUniform(float min, float max){
if (max < min){
float swap = min;
min = max;
max = swap;
}
return ((float)rand() / RAND_MAX * (max - min)) + min;
};
float cortexProcessingUnit::calcRandScale(float s){
float scale = calcRandUniformStrong(1, s);
if( calcRandomGen() % 2 ) return scale;
return 1.f / scale;
};
float cortexProcessingUnit::calcRandUniformStrong(float min, float max){
if (max < min) {
float swap = min;
min = max;
max = swap;
};
return (calcRandomFloat() * (max - min)) + min;
};
uint32_t cortexProcessingUnit::calcRandomGen(void){
unsigned int rnd = 0;
#ifndef WIN32
rand_s(&rnd);
#else
rnd = rand();
#endif
return rnd;
};
float cortexProcessingUnit::calcRandomFloat(void){
#ifdef WIN32
return ((float)calcRandomGen() / (float)UINT_MAX);
#else
return ((float)calcRandomGen() / (float)RAND_MAX);
#endif
};
#undef LOG
#undef LOG_ERROR
#undef SLOG
#undef SLOG_ERROR