2013-12-03 04:41:40 +04:00
|
|
|
#include "softmax_layer.h"
|
|
|
|
#include <math.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
softmax_layer *make_softmax_layer(int inputs)
|
|
|
|
{
|
2013-12-06 01:17:16 +04:00
|
|
|
fprintf(stderr, "Softmax Layer: %d inputs\n", inputs);
|
2013-12-03 04:41:40 +04:00
|
|
|
softmax_layer *layer = calloc(1, sizeof(softmax_layer));
|
|
|
|
layer->inputs = inputs;
|
2014-01-29 04:28:42 +04:00
|
|
|
layer->output = calloc(inputs, sizeof(float));
|
|
|
|
layer->delta = calloc(inputs, sizeof(float));
|
2013-12-03 04:41:40 +04:00
|
|
|
return layer;
|
|
|
|
}
|
|
|
|
|
2014-01-29 04:28:42 +04:00
|
|
|
/* UNSTABLE!
|
|
|
|
void forward_softmax_layer(const softmax_layer layer, float *input)
|
2013-12-03 04:41:40 +04:00
|
|
|
{
|
|
|
|
int i;
|
2014-01-29 04:28:42 +04:00
|
|
|
float sum = 0;
|
2013-12-03 04:41:40 +04:00
|
|
|
for(i = 0; i < layer.inputs; ++i){
|
|
|
|
sum += exp(input[i]);
|
|
|
|
}
|
|
|
|
for(i = 0; i < layer.inputs; ++i){
|
|
|
|
layer.output[i] = exp(input[i])/sum;
|
|
|
|
}
|
|
|
|
}
|
2014-01-29 04:28:42 +04:00
|
|
|
*/
|
|
|
|
void forward_softmax_layer(const softmax_layer layer, float *input)
|
|
|
|
{
|
|
|
|
int i;
|
|
|
|
float sum = 0;
|
|
|
|
float largest = 0;
|
|
|
|
for(i = 0; i < layer.inputs; ++i){
|
|
|
|
if(input[i] > largest) largest = input[i];
|
|
|
|
}
|
|
|
|
for(i = 0; i < layer.inputs; ++i){
|
|
|
|
sum += exp(input[i]-largest);
|
2014-02-14 22:26:31 +04:00
|
|
|
printf("%f, ", input[i]);
|
2014-01-29 04:28:42 +04:00
|
|
|
}
|
2014-02-14 22:26:31 +04:00
|
|
|
printf("\n");
|
|
|
|
if(sum) sum = largest+log(sum);
|
|
|
|
else sum = largest-100;
|
2014-01-29 04:28:42 +04:00
|
|
|
for(i = 0; i < layer.inputs; ++i){
|
|
|
|
layer.output[i] = exp(input[i]-sum);
|
|
|
|
}
|
|
|
|
}
|
2013-12-03 04:41:40 +04:00
|
|
|
|
2014-01-29 04:28:42 +04:00
|
|
|
void backward_softmax_layer(const softmax_layer layer, float *input, float *delta)
|
2013-12-03 04:41:40 +04:00
|
|
|
{
|
|
|
|
int i;
|
|
|
|
for(i = 0; i < layer.inputs; ++i){
|
|
|
|
delta[i] = layer.delta[i];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|