Guest User

Untitled

a guest
Nov 22nd, 2017
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. struct mnist_images
  2. {
  3. unsigned char *data;
  4. float *dataf;
  5. int count;
  6. int w, h;
  7. };
  8.  
  9. struct mnist_labels
  10. {
  11. unsigned char *data;
  12. int count;
  13. };
  14.  
  15. int32_t endian_swap32(int32_t val)
  16. {
  17. val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
  18. return (val << 16) | ((val >> 16) & 0xFFFF);
  19. }
  20.  
  21. void mnist_labels_destroy(struct mnist_labels *dest)
  22. {
  23. free(dest->data);
  24. }
  25.  
  26. void mnist_images_destroy(struct mnist_images *dest)
  27. {
  28. free(dest->data);
  29. free(dest->dataf);
  30. }
  31.  
  32. int mnist_labels_read(struct mnist_labels *dest, const char *filename)
  33. {
  34. FILE *file = fopen(filename, "rb");
  35. int header;
  36.  
  37. if(! file) {
  38. printf("MNIST ERROR: can't read file %s\n", filename);
  39. return 0;
  40. }
  41.  
  42. fread(&header, sizeof(int), 1, file);
  43. fread(&dest->count, sizeof(int), 1, file);
  44.  
  45. dest->count = endian_swap32(dest->count);
  46.  
  47. dest->data = (unsigned char *)malloc(dest->count * sizeof(char));
  48. fread(dest->data, sizeof(char), dest->count, file);
  49.  
  50. fclose(file);
  51. return 1;
  52. }
  53.  
  54. int mnist_images_read(struct mnist_images *dest, const char *filename)
  55. {
  56. FILE *file = fopen(filename, "rb");
  57. int header, size, i;
  58.  
  59. if(! file) {
  60. printf("MNIST ERROR: can't read file %s\n", filename);
  61. return 0;
  62. }
  63.  
  64. fread(&header, sizeof(int), 1, file);
  65. fread(&dest->count, sizeof(int), 1, file);
  66. fread(&dest->w, sizeof(int), 1, file);
  67. fread(&dest->h, sizeof(int), 1, file);
  68.  
  69. dest->count = endian_swap32(dest->count);
  70. dest->w = endian_swap32(dest->w);
  71. dest->h = endian_swap32(dest->h);
  72. size = dest->count * dest->w * dest->h;
  73.  
  74. dest->data = (unsigned char *)malloc(size * sizeof(char));
  75. dest->dataf = (float *)malloc(size * sizeof(float));
  76. fread(dest->data, sizeof(char), size, file);
  77.  
  78. for (i = 0; i < size; i++)
  79. dest->dataf[i] = (dest->data[i] / 255.0) * 2.0 - 1.0;
  80.  
  81. fclose(file);
  82. return 1;
  83. }
Add Comment
Please, Sign In to add comment