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.

1159 lines
35 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "darknet.h"
  2. #include <assert.h>
  3. namespace DN{
  4. float *get_regression_values(char **labels, int n)
  5. {
  6. float *v = (float*)calloc(n, sizeof(float));
  7. int i;
  8. for(i = 0; i < n; ++i){
  9. char *p = strchr(labels[i], ' ');
  10. *p = 0;
  11. v[i] =(float)atof(p+1);
  12. }
  13. return v;
  14. }
  15. void train_classifier(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear)
  16. {
  17. int i;
  18. float avg_loss = -1;
  19. char *base = basecfg(cfgfile);
  20. printf("%s\n", base);
  21. printf("%d\n", ngpus);
  22. network *nets =(network*)calloc(ngpus, sizeof(network));
  23. srand((unsigned int)time(0));
  24. int seed = rand();
  25. for(i = 0; i < ngpus; ++i){
  26. srand(seed);
  27. #ifdef GPU
  28. cuda_set_device(gpus[i]);
  29. #endif
  30. nets[i] = load_network(cfgfile, weightfile, clear);
  31. nets[i].learning_rate *= ngpus;
  32. }
  33. srand((unsigned int)time(0));
  34. network net = nets[0];
  35. int imgs = net.batch * net.subdivisions * ngpus;
  36. printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay);
  37. list *options = read_data_cfg(datacfg);
  38. char *backup_directory = option_find_str(options, "backup", "/backup/");
  39. char *label_list = option_find_str(options, "labels", "data/labels.list");
  40. char *train_list = option_find_str(options, "train", "data/train.list");
  41. int classes = option_find_int(options, "classes", 2);
  42. char **labels = get_labels(label_list);
  43. list *plist = get_paths(train_list);
  44. char **paths = (char **)list_to_array(plist);
  45. printf("%d\n", plist->size);
  46. int N = plist->size;
  47. double time;
  48. load_args args;
  49. memset(&args, 0, sizeof(load_args));
  50. args.w = net.w;
  51. args.h = net.h;
  52. args.threads = 64;
  53. args.hierarchy = net.hierarchy;
  54. args.min = net.min_crop;
  55. args.max = net.max_crop;
  56. args.angle = net.angle;
  57. args.aspect = net.aspect;
  58. args.exposure = net.exposure;
  59. args.saturation = net.saturation;
  60. args.hue = net.hue;
  61. args.size = net.w;
  62. args.paths = paths;
  63. args.classes = classes;
  64. args.n = imgs;
  65. args.m = N;
  66. args.labels = labels;
  67. args.type = CLASSIFICATION_DATA;
  68. data train;
  69. data buffer;
  70. #ifdef __linux__
  71. pthread_t load_thread;
  72. #else
  73. HANDLE load_thread;
  74. #endif
  75. args.d = &buffer;
  76. load_thread = load_data(args);
  77. int epoch = (*net.seen)/N;
  78. while(((int)get_current_batch(net)) < net.max_batches || net.max_batches == 0){
  79. time = what_time_is_it_now();
  80. #ifdef __linux__
  81. pthread_join(load_thread, 0);
  82. #else
  83. WaitForSingleObject(load_thread, INFINITE);
  84. CloseHandle(load_thread);
  85. #endif
  86. train = buffer;
  87. load_thread = load_data(args);
  88. printf("Loaded: %lf seconds\n", what_time_is_it_now()-time);
  89. time = what_time_is_it_now();
  90. float loss = 0;
  91. #ifdef GPU
  92. if(ngpus == 1){
  93. loss = train_network(net, train);
  94. } else {
  95. loss = train_networks(nets, ngpus, train, 4);
  96. }
  97. #else
  98. loss = train_network(net, train);
  99. #endif
  100. if(avg_loss == -1) avg_loss = loss;
  101. avg_loss = avg_loss*.9f + loss*.1f;
  102. printf("%ld, %.3f: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net.seen)/N, loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, *net.seen);
  103. free_data(train);
  104. if(((int)*net.seen)/N > epoch){
  105. epoch = *net.seen/N;
  106. char buff[256];
  107. sprintf(buff, "%s/%s_%d.weights",backup_directory,base, epoch);
  108. save_weights(net, buff);
  109. }
  110. if(get_current_batch(net)%1000 == 0){
  111. char buff[256];
  112. sprintf(buff, "%s/%s.backup",backup_directory,base);
  113. save_weights(net, buff);
  114. }
  115. }
  116. char buff[256];
  117. sprintf(buff, "%s/%s.weights", backup_directory, base);
  118. save_weights(net, buff);
  119. free_network(net);
  120. free_ptrs((void**)labels, classes);
  121. free_ptrs((void**)paths, plist->size);
  122. free_list(plist);
  123. free(base);
  124. }
  125. /*
  126. void train_classifier(char *datacfg, char *cfgfile, char *weightfile, int clear)
  127. {
  128. srand(time(0));
  129. float avg_loss = -1;
  130. char *base = basecfg(cfgfile);
  131. printf("%s\n", base);
  132. network net = parse_network_cfg(cfgfile);
  133. if(weightfile){
  134. load_weights(&net, weightfile);
  135. }
  136. if(clear) *net.seen = 0;
  137. int imgs = net.batch * net.subdivisions;
  138. printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay);
  139. list *options = read_data_cfg(datacfg);
  140. char *backup_directory = option_find_str(options, "backup", "/backup/");
  141. char *label_list = option_find_str(options, "labels", "data/labels.list");
  142. char *train_list = option_find_str(options, "train", "data/train.list");
  143. int classes = option_find_int(options, "classes", 2);
  144. char **labels = get_labels(label_list);
  145. list *plist = get_paths(train_list);
  146. char **paths = (char **)list_to_array(plist);
  147. printf("%d\n", plist->size);
  148. int N = plist->size;
  149. clock_t time;
  150. load_args args = {0};
  151. args.w = net.w;
  152. args.h = net.h;
  153. args.threads = 8;
  154. args.min = net.min_crop;
  155. args.max = net.max_crop;
  156. args.angle = net.angle;
  157. args.aspect = net.aspect;
  158. args.exposure = net.exposure;
  159. args.saturation = net.saturation;
  160. args.hue = net.hue;
  161. args.size = net.w;
  162. args.hierarchy = net.hierarchy;
  163. args.paths = paths;
  164. args.classes = classes;
  165. args.n = imgs;
  166. args.m = N;
  167. args.labels = labels;
  168. args.type = CLASSIFICATION_DATA;
  169. data train;
  170. data buffer;
  171. pthread_t load_thread;
  172. args.d = &buffer;
  173. load_thread = load_data(args);
  174. int epoch = (*net.seen)/N;
  175. while(get_current_batch(net) < net.max_batches || net.max_batches == 0){
  176. time=clock();
  177. pthread_join(load_thread, 0);
  178. train = buffer;
  179. load_thread = load_data(args);
  180. printf("Loaded: %lf seconds\n", sec(clock()-time));
  181. time=clock();
  182. #ifdef OPENCV
  183. if(0){
  184. int u;
  185. for(u = 0; u < imgs; ++u){
  186. image im = float_to_image(net.w, net.h, 3, train.X.vals[u]);
  187. show_image(im, "loaded");
  188. cvWaitKey(0);
  189. }
  190. }
  191. #endif
  192. float loss = train_network(net, train);
  193. free_data(train);
  194. if(avg_loss == -1) avg_loss = loss;
  195. avg_loss = avg_loss*.9 + loss*.1;
  196. printf("%d, %.3f: %f, %f avg, %f rate, %lf seconds, %d images\n", get_current_batch(net), (float)(*net.seen)/N, loss, avg_loss, get_current_rate(net), sec(clock()-time), *net.seen);
  197. if(*net.seen/N > epoch){
  198. epoch = *net.seen/N;
  199. char buff[256];
  200. sprintf(buff, "%s/%s_%d.weights",backup_directory,base, epoch);
  201. save_weights(net, buff);
  202. }
  203. if(get_current_batch(net)%100 == 0){
  204. char buff[256];
  205. sprintf(buff, "%s/%s.backup",backup_directory,base);
  206. save_weights(net, buff);
  207. }
  208. }
  209. char buff[256];
  210. sprintf(buff, "%s/%s.weights", backup_directory, base);
  211. save_weights(net, buff);
  212. free_network(net);
  213. free_ptrs((void**)labels, classes);
  214. free_ptrs((void**)paths, plist->size);
  215. free_list(plist);
  216. free(base);
  217. }
  218. */
  219. void validate_classifier_crop(char *datacfg, char *filename, char *weightfile)
  220. {
  221. int i = 0;
  222. network net = parse_network_cfg(filename);
  223. if(weightfile){
  224. load_weights(&net, weightfile);
  225. }
  226. srand((unsigned int)time(0));
  227. list *options = read_data_cfg(datacfg);
  228. char *label_list = option_find_str(options, "labels", "data/labels.list");
  229. char *valid_list = option_find_str(options, "valid", "data/train.list");
  230. int classes = option_find_int(options, "classes", 2);
  231. int topk = option_find_int(options, "top", 1);
  232. char **labels = get_labels(label_list);
  233. list *plist = get_paths(valid_list);
  234. char **paths = (char **)list_to_array(plist);
  235. int m = plist->size;
  236. free_list(plist);
  237. clock_t time;
  238. float avg_acc = 0;
  239. float avg_topk = 0;
  240. int splits = m/1000;
  241. int num = (i+1)*m/splits - i*m/splits;
  242. data val, buffer;
  243. load_args args;
  244. memset(&args, 0, sizeof(load_args));
  245. args.w = net.w;
  246. args.h = net.h;
  247. args.paths = paths;
  248. args.classes = classes;
  249. args.n = num;
  250. args.m = 0;
  251. args.labels = labels;
  252. args.d = &buffer;
  253. args.type = OLD_CLASSIFICATION_DATA;
  254. #ifdef __linux__
  255. pthread_t load_thread = load_data_in_thread(args);
  256. #else
  257. HANDLE load_thread = load_data_in_thread(args);
  258. #endif
  259. for(i = 1; i <= splits; ++i){
  260. time=clock();
  261. #ifdef __linux__
  262. pthread_join(load_thread, 0);
  263. #else
  264. WaitForSingleObject(load_thread, INFINITE);
  265. CloseHandle(load_thread);
  266. #endif
  267. val = buffer;
  268. num = (i+1)*m/splits - i*m/splits;
  269. char **part = paths+(i*m/splits);
  270. if(i != splits){
  271. args.paths = part;
  272. load_thread = load_data_in_thread(args);
  273. }
  274. printf("Loaded: %d images in %lf seconds\n", val.X.rows, sec(clock()-time));
  275. time=clock();
  276. float *acc = network_accuracies(net, val, topk);
  277. avg_acc += acc[0];
  278. avg_topk += acc[1];
  279. printf("%d: top 1: %f, top %d: %f, %lf seconds, %d images\n", i, avg_acc/i, topk, avg_topk/i, sec(clock()-time), val.X.rows);
  280. free_data(val);
  281. }
  282. }
  283. void validate_classifier_10(char *datacfg, char *filename, char *weightfile)
  284. {
  285. int i, j;
  286. network net = parse_network_cfg(filename);
  287. set_batch_network(&net, 1);
  288. if(weightfile){
  289. load_weights(&net, weightfile);
  290. }
  291. srand((unsigned int)time(0));
  292. list *options = read_data_cfg(datacfg);
  293. char *label_list = option_find_str(options, "labels", "data/labels.list");
  294. char *valid_list = option_find_str(options, "valid", "data/train.list");
  295. int classes = option_find_int(options, "classes", 2);
  296. int topk = option_find_int(options, "top", 1);
  297. char **labels = get_labels(label_list);
  298. list *plist = get_paths(valid_list);
  299. char **paths = (char **)list_to_array(plist);
  300. int m = plist->size;
  301. free_list(plist);
  302. float avg_acc = 0;
  303. float avg_topk = 0;
  304. int *indexes = (int*)calloc(topk, sizeof(int));
  305. for(i = 0; i < m; ++i){
  306. int cls = -1;
  307. char *path = paths[i];
  308. for(j = 0; j < classes; ++j){
  309. if(strstr(path, labels[j])){
  310. cls = j;
  311. break;
  312. }
  313. }
  314. int w = net.w;
  315. int h = net.h;
  316. int shift = 32;
  317. image im = load_image_color(paths[i], w+shift, h+shift);
  318. image images[10];
  319. images[0] = crop_image(im, -shift, -shift, w, h);
  320. images[1] = crop_image(im, shift, -shift, w, h);
  321. images[2] = crop_image(im, 0, 0, w, h);
  322. images[3] = crop_image(im, -shift, shift, w, h);
  323. images[4] = crop_image(im, shift, shift, w, h);
  324. flip_image(im);
  325. images[5] = crop_image(im, -shift, -shift, w, h);
  326. images[6] = crop_image(im, shift, -shift, w, h);
  327. images[7] = crop_image(im, 0, 0, w, h);
  328. images[8] = crop_image(im, -shift, shift, w, h);
  329. images[9] = crop_image(im, shift, shift, w, h);
  330. float *pred =(float*)calloc(classes, sizeof(float));
  331. for(j = 0; j < 10; ++j){
  332. float *p = network_predict(net, images[j].data);
  333. if(net.hierarchy) hierarchy_predictions(p, net.outputs, net.hierarchy, 1, 1);
  334. axpy_cpu(classes, 1, p, 1, pred, 1);
  335. free_image(images[j]);
  336. }
  337. free_image(im);
  338. top_k(pred, classes, topk, indexes);
  339. free(pred);
  340. if(indexes[0] == cls) avg_acc += 1;
  341. for(j = 0; j < topk; ++j){
  342. if(indexes[j] == cls) avg_topk += 1;
  343. }
  344. printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
  345. }
  346. }
  347. void validate_classifier_full(char *datacfg, char *filename, char *weightfile)
  348. {
  349. int i, j;
  350. network net = parse_network_cfg(filename);
  351. set_batch_network(&net, 1);
  352. if(weightfile){
  353. load_weights(&net, weightfile);
  354. }
  355. srand((unsigned int)time(0));
  356. list *options = read_data_cfg(datacfg);
  357. char *label_list = option_find_str(options, "labels", "data/labels.list");
  358. char *valid_list = option_find_str(options, "valid", "data/train.list");
  359. int classes = option_find_int(options, "classes", 2);
  360. int topk = option_find_int(options, "top", 1);
  361. char **labels = get_labels(label_list);
  362. list *plist = get_paths(valid_list);
  363. char **paths = (char **)list_to_array(plist);
  364. int m = plist->size;
  365. free_list(plist);
  366. float avg_acc = 0;
  367. float avg_topk = 0;
  368. int *indexes = (int*)calloc(topk, sizeof(int));
  369. int size = net.w;
  370. for(i = 0; i < m; ++i){
  371. int cls = -1;
  372. char *path = paths[i];
  373. for(j = 0; j < classes; ++j){
  374. if(strstr(path, labels[j])){
  375. cls = j;
  376. break;
  377. }
  378. }
  379. image im = load_image_color(paths[i], 0, 0);
  380. image resized = resize_min(im, size);
  381. resize_network(&net, resized.w, resized.h);
  382. //show_image(im, "orig");
  383. //show_image(crop, "cropped");
  384. //cvWaitKey(0);
  385. float *pred = network_predict(net, resized.data);
  386. if(net.hierarchy) hierarchy_predictions(pred, net.outputs, net.hierarchy, 1, 1);
  387. free_image(im);
  388. free_image(resized);
  389. top_k(pred, classes, topk, indexes);
  390. if(indexes[0] == cls) avg_acc += 1;
  391. for(j = 0; j < topk; ++j){
  392. if(indexes[j] == cls) avg_topk += 1;
  393. }
  394. printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
  395. }
  396. }
  397. void validate_classifier_single(char *datacfg, char *filename, char *weightfile)
  398. {
  399. int i, j;
  400. network net = parse_network_cfg(filename);
  401. if(weightfile){
  402. load_weights(&net, weightfile);
  403. }
  404. set_batch_network(&net, 1);
  405. srand((unsigned int)time(0));
  406. list *options = read_data_cfg(datacfg);
  407. char *label_list = option_find_str(options, "labels", "data/labels.list");
  408. char *leaf_list = option_find_str(options, "leaves", 0);
  409. if(leaf_list) change_leaves(net.hierarchy, leaf_list);
  410. char *valid_list = option_find_str(options, "valid", "data/train.list");
  411. int classes = option_find_int(options, "classes", 2);
  412. int topk = option_find_int(options, "top", 1);
  413. char **labels = get_labels(label_list);
  414. list *plist = get_paths(valid_list);
  415. char **paths = (char **)list_to_array(plist);
  416. int m = plist->size;
  417. free_list(plist);
  418. float avg_acc = 0;
  419. float avg_topk = 0;
  420. int *indexes = (int*)calloc(topk, sizeof(int));
  421. for(i = 0; i < m; ++i){
  422. int cls = -1;
  423. char *path = paths[i];
  424. for(j = 0; j < classes; ++j){
  425. if(strstr(path, labels[j])){
  426. cls = j;
  427. break;
  428. }
  429. }
  430. image im = load_image_color(paths[i], 0, 0);
  431. image resized = resize_min(im, net.w);
  432. image crop = crop_image(resized, (resized.w - net.w)/2, (resized.h - net.h)/2, net.w, net.h);
  433. //show_image(im, "orig");
  434. //show_image(crop, "cropped");
  435. //cvWaitKey(0);
  436. float *pred = network_predict(net, crop.data);
  437. if(net.hierarchy) hierarchy_predictions(pred, net.outputs, net.hierarchy, 1, 1);
  438. if(resized.data != im.data) free_image(resized);
  439. free_image(im);
  440. free_image(crop);
  441. top_k(pred, classes, topk, indexes);
  442. if(indexes[0] == cls) avg_acc += 1;
  443. for(j = 0; j < topk; ++j){
  444. if(indexes[j] == cls) avg_topk += 1;
  445. }
  446. printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
  447. }
  448. }
  449. void validate_classifier_multi(char *datacfg, char *filename, char *weightfile)
  450. {
  451. int i, j;
  452. network net = parse_network_cfg(filename);
  453. set_batch_network(&net, 1);
  454. if(weightfile){
  455. load_weights(&net, weightfile);
  456. }
  457. srand((unsigned int)time(0));
  458. list *options = read_data_cfg(datacfg);
  459. char *label_list = option_find_str(options, "labels", "data/labels.list");
  460. char *valid_list = option_find_str(options, "valid", "data/train.list");
  461. int classes = option_find_int(options, "classes", 2);
  462. int topk = option_find_int(options, "top", 1);
  463. char **labels = get_labels(label_list);
  464. list *plist = get_paths(valid_list);
  465. int scales[] = {224, 288, 320, 352, 384};
  466. int nscales = sizeof(scales)/sizeof(scales[0]);
  467. char **paths = (char **)list_to_array(plist);
  468. int m = plist->size;
  469. free_list(plist);
  470. float avg_acc = 0;
  471. float avg_topk = 0;
  472. int *indexes = (int*)calloc(topk, sizeof(int));
  473. for(i = 0; i < m; ++i){
  474. int cls = -1;
  475. char *path = paths[i];
  476. for(j = 0; j < classes; ++j){
  477. if(strstr(path, labels[j])){
  478. cls = j;
  479. break;
  480. }
  481. }
  482. float *pred = (float*)calloc(classes, sizeof(float));
  483. image im = load_image_color(paths[i], 0, 0);
  484. for(j = 0; j < nscales; ++j){
  485. image r = resize_min(im, scales[j]);
  486. resize_network(&net, r.w, r.h);
  487. float *p = network_predict(net, r.data);
  488. if(net.hierarchy) hierarchy_predictions(p, net.outputs, net.hierarchy, 1 , 1);
  489. axpy_cpu(classes, 1, p, 1, pred, 1);
  490. flip_image(r);
  491. p = network_predict(net, r.data);
  492. axpy_cpu(classes, 1, p, 1, pred, 1);
  493. if(r.data != im.data) free_image(r);
  494. }
  495. free_image(im);
  496. top_k(pred, classes, topk, indexes);
  497. free(pred);
  498. if(indexes[0] == cls) avg_acc += 1;
  499. for(j = 0; j < topk; ++j){
  500. if(indexes[j] == cls) avg_topk += 1;
  501. }
  502. printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1));
  503. }
  504. }
  505. void try_classifier(char *datacfg, char *cfgfile, char *weightfile, char *filename, int layer_num)
  506. {
  507. network net = parse_network_cfg(cfgfile);
  508. if(weightfile){
  509. load_weights(&net, weightfile);
  510. }
  511. set_batch_network(&net, 1);
  512. srand(2222222);
  513. list *options = read_data_cfg(datacfg);
  514. char *name_list = option_find_str(options, "names", 0);
  515. if(!name_list) name_list = option_find_str(options, "labels", "data/labels.list");
  516. int top = option_find_int(options, "top", 1);
  517. int i = 0;
  518. char **names = get_labels(name_list);
  519. clock_t time;
  520. int *indexes = (int*)calloc(top, sizeof(int));
  521. char buff[256];
  522. char *input = buff;
  523. while(1){
  524. if(filename){
  525. strncpy(input, filename, 256);
  526. }else{
  527. printf("Enter Image Path: ");
  528. fflush(stdout);
  529. input = fgets(input, 256, stdin);
  530. if(!input) return;
  531. strtok(input, "\n");
  532. }
  533. image orig = load_image_color(input, 0, 0);
  534. image r = resize_min(orig, 256);
  535. image im = crop_image(r, (r.w - 224 - 1)/2 + 1, (r.h - 224 - 1)/2 + 1, 224, 224);
  536. float mean[] = {0.48263312050943f, 0.45230225481413f, 0.40099074308742f};
  537. float std[] = {0.22590347483426f, 0.22120921437787f, 0.22103996251583f};
  538. float var[3];
  539. var[0] = std[0]*std[0];
  540. var[1] = std[1]*std[1];
  541. var[2] = std[2]*std[2];
  542. normalize_cpu(im.data, mean, var, 1, 3, im.w*im.h);
  543. float *X = im.data;
  544. time=clock();
  545. float *predictions = network_predict(net, X);
  546. layer l = net.layers[layer_num];
  547. for(i = 0; i < l.c; ++i){
  548. if(l.rolling_mean) printf("%f %f %f\n", l.rolling_mean[i], l.rolling_variance[i], l.scales[i]);
  549. }
  550. #ifdef GPU
  551. cuda_pull_array(l.output_gpu, l.output, l.outputs);
  552. #endif
  553. for(i = 0; i < l.outputs; ++i){
  554. printf("%f\n", l.output[i]);
  555. }
  556. /*
  557. printf("\n\nWeights\n");
  558. for(i = 0; i < l.n*l.size*l.size*l.c; ++i){
  559. printf("%f\n", l.filters[i]);
  560. }
  561. printf("\n\nBiases\n");
  562. for(i = 0; i < l.n; ++i){
  563. printf("%f\n", l.biases[i]);
  564. }
  565. */
  566. top_predictions(net, top, indexes);
  567. printf("%s: Predicted in %f seconds.\n", input, sec(clock()-time));
  568. for(i = 0; i < top; ++i){
  569. int index = indexes[i];
  570. printf("%s: %f\n", names[index], predictions[index]);
  571. }
  572. free_image(im);
  573. if (filename) break;
  574. }
  575. }
  576. void predict_classifier(char *datacfg, char *cfgfile, char *weightfile, char *filename, int top)
  577. {
  578. network net = parse_network_cfg(cfgfile);
  579. if(weightfile){
  580. load_weights(&net, weightfile);
  581. }
  582. set_batch_network(&net, 1);
  583. srand(2222222);
  584. list *options = read_data_cfg(datacfg);
  585. char *name_list = option_find_str(options, "names", 0);
  586. if(!name_list) name_list = option_find_str(options, "labels", "data/labels.list");
  587. if(top == 0) top = option_find_int(options, "top", 1);
  588. int i = 0;
  589. char **names = get_labels(name_list);
  590. clock_t time;
  591. int *indexes = (int*)calloc(top, sizeof(int));
  592. char buff[256];
  593. char *input = buff;
  594. while(1){
  595. if(filename){
  596. strncpy(input, filename, 256);
  597. }else{
  598. printf("Enter Image Path: ");
  599. fflush(stdout);
  600. input = fgets(input, 256, stdin);
  601. if(!input) return;
  602. strtok(input, "\n");
  603. }
  604. image im = load_image_color(input, 0, 0);
  605. image r = letterbox_image(im, net.w, net.h);
  606. //resize_network(&net, r.w, r.h);
  607. //printf("%d %d\n", r.w, r.h);
  608. float *X = r.data;
  609. time=clock();
  610. float *predictions = network_predict(net, X);
  611. if(net.hierarchy) hierarchy_predictions(predictions, net.outputs, net.hierarchy, 1, 1);
  612. top_k(predictions, net.outputs, top, indexes);
  613. fprintf(stderr, "%s: Predicted in %f seconds.\n", input, sec(clock()-time));
  614. for(i = 0; i < top; ++i){
  615. int index = indexes[i];
  616. //if(net.hierarchy) printf("%d, %s: %f, parent: %s \n",index, names[index], predictions[index], (net.hierarchy->parent[index] >= 0) ? names[net.hierarchy->parent[index]] : "Root");
  617. //else printf("%s: %f\n",names[index], predictions[index]);
  618. printf("%5.2f%%: %s\n", predictions[index]*100, names[index]);
  619. }
  620. if(r.data != im.data) free_image(r);
  621. free_image(im);
  622. if (filename) break;
  623. }
  624. }
  625. void label_classifier(char *datacfg, char *filename, char *weightfile)
  626. {
  627. int i;
  628. network net = parse_network_cfg(filename);
  629. set_batch_network(&net, 1);
  630. if(weightfile){
  631. load_weights(&net, weightfile);
  632. }
  633. srand((unsigned int)time(0));
  634. list *options = read_data_cfg(datacfg);
  635. char *label_list = option_find_str(options, "names", "data/labels.list");
  636. char *test_list = option_find_str(options, "test", "data/train.list");
  637. int classes = option_find_int(options, "classes", 2);
  638. char **labels = get_labels(label_list);
  639. list *plist = get_paths(test_list);
  640. char **paths = (char **)list_to_array(plist);
  641. int m = plist->size;
  642. free_list(plist);
  643. for(i = 0; i < m; ++i){
  644. image im = load_image_color(paths[i], 0, 0);
  645. image resized = resize_min(im, net.w);
  646. image crop = crop_image(resized, (resized.w - net.w)/2, (resized.h - net.h)/2, net.w, net.h);
  647. float *pred = network_predict(net, crop.data);
  648. if(resized.data != im.data) free_image(resized);
  649. free_image(im);
  650. free_image(crop);
  651. int ind = max_index(pred, classes);
  652. printf("%s\n", labels[ind]);
  653. }
  654. }
  655. void test_classifier(char *datacfg, char *cfgfile, char *weightfile, int target_layer)
  656. {
  657. int curr = 0;
  658. network net = parse_network_cfg(cfgfile);
  659. if(weightfile){
  660. load_weights(&net, weightfile);
  661. }
  662. srand((unsigned int)time(0));
  663. list *options = read_data_cfg(datacfg);
  664. char *test_list = option_find_str(options, "test", "data/test.list");
  665. int classes = option_find_int(options, "classes", 2);
  666. list *plist = get_paths(test_list);
  667. char **paths = (char **)list_to_array(plist);
  668. int m = plist->size;
  669. free_list(plist);
  670. clock_t time;
  671. data val, buffer;
  672. load_args args = {0};
  673. args.w = net.w;
  674. args.h = net.h;
  675. args.paths = paths;
  676. args.classes = classes;
  677. args.n = net.batch;
  678. args.m = 0;
  679. args.labels = 0;
  680. args.d = &buffer;
  681. args.type = OLD_CLASSIFICATION_DATA;
  682. #ifdef __linux__
  683. pthread_t load_thread = load_data_in_thread(args);
  684. #else
  685. HANDLE load_thread = load_data_in_thread(args);
  686. #endif
  687. for(curr = net.batch; curr < m; curr += net.batch){
  688. time=clock();
  689. #ifdef __linux__
  690. pthread_join(load_thread, 0);
  691. #else
  692. WaitForSingleObject(load_thread, INFINITE);
  693. CloseHandle(load_thread);
  694. #endif
  695. val = buffer;
  696. if(curr < m){
  697. args.paths = paths + curr;
  698. if (curr + net.batch > m) args.n = m - curr;
  699. load_thread = load_data_in_thread(args);
  700. }
  701. fprintf(stderr, "Loaded: %d images in %lf seconds\n", val.X.rows, sec(clock()-time));
  702. time=clock();
  703. matrix pred = network_predict_data(net, val);
  704. int i, j;
  705. if (target_layer >= 0){
  706. //layer l = net.layers[target_layer];
  707. }
  708. for(i = 0; i < pred.rows; ++i){
  709. printf("%s", paths[curr-net.batch+i]);
  710. for(j = 0; j < pred.cols; ++j){
  711. printf("\t%g", pred.vals[i][j]);
  712. }
  713. printf("\n");
  714. }
  715. free_matrix(pred);
  716. fprintf(stderr, "%lf seconds, %d images, %d total\n", sec(clock()-time), val.X.rows, curr);
  717. free_data(val);
  718. }
  719. }
  720. void threat_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename)
  721. {
  722. #ifdef OPENCV
  723. float threat = 0;
  724. float roll = .2;
  725. printf("Classifier Demo\n");
  726. network net = parse_network_cfg(cfgfile);
  727. if(weightfile){
  728. load_weights(&net, weightfile);
  729. }
  730. set_batch_network(&net, 1);
  731. list *options = read_data_cfg(datacfg);
  732. srand(2222222);
  733. CvCapture * cap;
  734. if(filename){
  735. cap = cvCaptureFromFile(filename);
  736. }else{
  737. cap = cvCaptureFromCAM(cam_index);
  738. }
  739. int top = option_find_int(options, "top", 1);
  740. char *name_list = option_find_str(options, "names", 0);
  741. char **names = get_labels(name_list);
  742. int *indexes = (int*)calloc(top, sizeof(int));
  743. if(!cap) error("Couldn't connect to webcam.\n");
  744. //cvNamedWindow("Threat", CV_WINDOW_NORMAL);
  745. //cvResizeWindow("Threat", 512, 512);
  746. float fps = 0;
  747. int i;
  748. int count = 0;
  749. while(1){
  750. ++count;
  751. struct timeval tval_before, tval_after, tval_result;
  752. gettimeofday(&tval_before, NULL);
  753. image in = get_image_from_stream(cap);
  754. if(!in.data) break;
  755. image in_s = resize_image(in, net.w, net.h);
  756. image out = in;
  757. int x1 = out.w / 20;
  758. int y1 = out.h / 20;
  759. int x2 = 2*x1;
  760. int y2 = out.h - out.h/20;
  761. int border = .01*out.h;
  762. int h = y2 - y1 - 2*border;
  763. int w = x2 - x1 - 2*border;
  764. float *predictions = network_predict(net, in_s.data);
  765. float curr_threat = 0;
  766. if(1){
  767. curr_threat = predictions[0] * 0 +
  768. predictions[1] * .6 +
  769. predictions[2];
  770. } else {
  771. curr_threat = predictions[218] +
  772. predictions[539] +
  773. predictions[540] +
  774. predictions[368] +
  775. predictions[369] +
  776. predictions[370];
  777. }
  778. threat = roll * curr_threat + (1-roll) * threat;
  779. draw_box_width(out, x2 + border, y1 + .02*h, x2 + .5 * w, y1 + .02*h + border, border, 0,0,0);
  780. if(threat > .97) {
  781. draw_box_width(out, x2 + .5 * w + border,
  782. y1 + .02*h - 2*border,
  783. x2 + .5 * w + 6*border,
  784. y1 + .02*h + 3*border, 3*border, 1,0,0);
  785. }
  786. draw_box_width(out, x2 + .5 * w + border,
  787. y1 + .02*h - 2*border,
  788. x2 + .5 * w + 6*border,
  789. y1 + .02*h + 3*border, .5*border, 0,0,0);
  790. draw_box_width(out, x2 + border, y1 + .42*h, x2 + .5 * w, y1 + .42*h + border, border, 0,0,0);
  791. if(threat > .57) {
  792. draw_box_width(out, x2 + .5 * w + border,
  793. y1 + .42*h - 2*border,
  794. x2 + .5 * w + 6*border,
  795. y1 + .42*h + 3*border, 3*border, 1,1,0);
  796. }
  797. draw_box_width(out, x2 + .5 * w + border,
  798. y1 + .42*h - 2*border,
  799. x2 + .5 * w + 6*border,
  800. y1 + .42*h + 3*border, .5*border, 0,0,0);
  801. draw_box_width(out, x1, y1, x2, y2, border, 0,0,0);
  802. for(i = 0; i < threat * h ; ++i){
  803. float ratio = (float) i / h;
  804. float r = (ratio < .5) ? (2*(ratio)) : 1;
  805. float g = (ratio < .5) ? 1 : 1 - 2*(ratio - .5);
  806. draw_box_width(out, x1 + border, y2 - border - i, x2 - border, y2 - border - i, 1, r, g, 0);
  807. }
  808. top_predictions(net, top, indexes);
  809. char buff[256];
  810. sprintf(buff, "/home/pjreddie/tmp/threat_%06d", count);
  811. //save_image(out, buff);
  812. printf("\033[2J");
  813. printf("\033[1;1H");
  814. printf("\nFPS:%.0f\n",fps);
  815. for(i = 0; i < top; ++i){
  816. int index = indexes[i];
  817. printf("%.1f%%: %s\n", predictions[index]*100, names[index]);
  818. }
  819. if(1){
  820. show_image(out, "Threat");
  821. cvWaitKey(10);
  822. }
  823. free_image(in_s);
  824. free_image(in);
  825. gettimeofday(&tval_after, NULL);
  826. timersub(&tval_after, &tval_before, &tval_result);
  827. float curr = 1000000.f/((long int)tval_result.tv_usec);
  828. fps = .9*fps + .1*curr;
  829. }
  830. #endif
  831. }
  832. void gun_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename)
  833. {
  834. #ifdef OPENCV
  835. int bad_cats[] = {218, 539, 540, 1213, 1501, 1742, 1911, 2415, 4348, 19223, 368, 369, 370, 1133, 1200, 1306, 2122, 2301, 2537, 2823, 3179, 3596, 3639, 4489, 5107, 5140, 5289, 6240, 6631, 6762, 7048, 7171, 7969, 7984, 7989, 8824, 8927, 9915, 10270, 10448, 13401, 15205, 18358, 18894, 18895, 19249, 19697};
  836. printf("Classifier Demo\n");
  837. network net = parse_network_cfg(cfgfile);
  838. if(weightfile){
  839. load_weights(&net, weightfile);
  840. }
  841. set_batch_network(&net, 1);
  842. list *options = read_data_cfg(datacfg);
  843. srand(2222222);
  844. CvCapture * cap;
  845. if(filename){
  846. cap = cvCaptureFromFile(filename);
  847. }else{
  848. cap = cvCaptureFromCAM(cam_index);
  849. }
  850. int top = option_find_int(options, "top", 1);
  851. char *name_list = option_find_str(options, "names", 0);
  852. char **names = get_labels(name_list);
  853. int *indexes = (int*)calloc(top, sizeof(int));
  854. if(!cap) error("Couldn't connect to webcam.\n");
  855. cvNamedWindow("Threat Detection", CV_WINDOW_NORMAL);
  856. cvResizeWindow("Threat Detection", 512, 512);
  857. float fps = 0;
  858. int i;
  859. while(1){
  860. struct timeval tval_before, tval_after, tval_result;
  861. gettimeofday(&tval_before, NULL);
  862. image in = get_image_from_stream(cap);
  863. image in_s = resize_image(in, net.w, net.h);
  864. show_image(in, "Threat Detection");
  865. float *predictions = network_predict(net, in_s.data);
  866. top_predictions(net, top, indexes);
  867. printf("\033[2J");
  868. printf("\033[1;1H");
  869. int threat = 0;
  870. for(i = 0; i < sizeof(bad_cats)/sizeof(bad_cats[0]); ++i){
  871. int index = bad_cats[i];
  872. if(predictions[index] > .01){
  873. printf("Threat Detected!\n");
  874. threat = 1;
  875. break;
  876. }
  877. }
  878. if(!threat) printf("Scanning...\n");
  879. for(i = 0; i < sizeof(bad_cats)/sizeof(bad_cats[0]); ++i){
  880. int index = bad_cats[i];
  881. if(predictions[index] > .01){
  882. printf("%s\n", names[index]);
  883. }
  884. }
  885. free_image(in_s);
  886. free_image(in);
  887. cvWaitKey(10);
  888. gettimeofday(&tval_after, NULL);
  889. timersub(&tval_after, &tval_before, &tval_result);
  890. float curr = 1000000.f/((long int)tval_result.tv_usec);
  891. fps = .9*fps + .1*curr;
  892. }
  893. #endif
  894. }
  895. void demo_classifier(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename)
  896. {
  897. #ifdef OPENCV
  898. printf("Classifier Demo\n");
  899. network net = parse_network_cfg(cfgfile);
  900. if(weightfile){
  901. load_weights(&net, weightfile);
  902. }
  903. set_batch_network(&net, 1);
  904. list *options = read_data_cfg(datacfg);
  905. srand(2222222);
  906. CvCapture * cap;
  907. if(filename){
  908. cap = cvCaptureFromFile(filename);
  909. }else{
  910. cap = cvCaptureFromCAM(cam_index);
  911. }
  912. int top = option_find_int(options, "top", 1);
  913. char *name_list = option_find_str(options, "names", 0);
  914. char **names = get_labels(name_list);
  915. int *indexes = (int*)calloc(top, sizeof(int));
  916. if(!cap) error("Couldn't connect to webcam.\n");
  917. cvNamedWindow("Classifier", CV_WINDOW_NORMAL);
  918. cvResizeWindow("Classifier", 512, 512);
  919. float fps = 0;
  920. int i;
  921. while(1){
  922. struct timeval tval_before, tval_after, tval_result;
  923. gettimeofday(&tval_before, NULL);
  924. image in = get_image_from_stream(cap);
  925. image in_s = resize_image(in, net.w, net.h);
  926. show_image(in, "Classifier");
  927. float *predictions = network_predict(net, in_s.data);
  928. if(net.hierarchy) hierarchy_predictions(predictions, net.outputs, net.hierarchy, 1, 1);
  929. top_predictions(net, top, indexes);
  930. printf("\033[2J");
  931. printf("\033[1;1H");
  932. printf("\nFPS:%.0f\n",fps);
  933. for(i = 0; i < top; ++i){
  934. int index = indexes[i];
  935. printf("%.1f%%: %s\n", predictions[index]*100, names[index]);
  936. }
  937. free_image(in_s);
  938. free_image(in);
  939. cvWaitKey(10);
  940. gettimeofday(&tval_after, NULL);
  941. timersub(&tval_after, &tval_before, &tval_result);
  942. float curr = 1000000.f/((long int)tval_result.tv_usec);
  943. fps = .9*fps + .1*curr;
  944. }
  945. #endif
  946. }
  947. void run_classifier(int argc, char **argv)
  948. {
  949. if(argc < 4){
  950. fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]);
  951. return;
  952. }
  953. char *gpu_list = find_char_arg(argc, argv, "-gpus", 0);
  954. int ngpus;
  955. int *gpus = read_intlist(gpu_list, &ngpus, gpu_index);
  956. int cam_index = find_int_arg(argc, argv, "-c", 0);
  957. int top = find_int_arg(argc, argv, "-t", 0);
  958. int clear = find_arg(argc, argv, "-clear");
  959. char *data = argv[3];
  960. char *cfg = argv[4];
  961. char *weights = (argc > 5) ? argv[5] : 0;
  962. char *filename = (argc > 6) ? argv[6]: 0;
  963. char *layer_s = (argc > 7) ? argv[7]: 0;
  964. int layer = layer_s ? atoi(layer_s) : -1;
  965. if(0==strcmp(argv[2], "predict")) predict_classifier(data, cfg, weights, filename, top);
  966. else if(0==strcmp(argv[2], "try")) try_classifier(data, cfg, weights, filename, atoi(layer_s));
  967. else if(0==strcmp(argv[2], "train")) train_classifier(data, cfg, weights, gpus, ngpus, clear);
  968. else if(0==strcmp(argv[2], "demo")) demo_classifier(data, cfg, weights, cam_index, filename);
  969. else if(0==strcmp(argv[2], "gun")) gun_classifier(data, cfg, weights, cam_index, filename);
  970. else if(0==strcmp(argv[2], "threat")) threat_classifier(data, cfg, weights, cam_index, filename);
  971. else if(0==strcmp(argv[2], "test")) test_classifier(data, cfg, weights, layer);
  972. else if(0==strcmp(argv[2], "label")) label_classifier(data, cfg, weights);
  973. else if(0==strcmp(argv[2], "valid")) validate_classifier_single(data, cfg, weights);
  974. else if(0==strcmp(argv[2], "validmulti")) validate_classifier_multi(data, cfg, weights);
  975. else if(0==strcmp(argv[2], "valid10")) validate_classifier_10(data, cfg, weights);
  976. else if(0==strcmp(argv[2], "validcrop")) validate_classifier_crop(data, cfg, weights);
  977. else if(0==strcmp(argv[2], "validfull")) validate_classifier_full(data, cfg, weights);
  978. }
  979. };