summaryrefslogtreecommitdiff
path: root/htk_io/tools/nerv_to_tnet.cpp
blob: 91be7db384b4c83a9f6f280863a56e4be565b68e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>

char token[1024];
typedef struct node
{
	double **mat;
	int nrow;
	int ncol;
	int index;
}node;

int main(int argc, char **argv)
{
	if (argc != 3)
    	{   
        	printf("%s nerv.model.in tnet.model.out\n", argv[0]);
    	}   

    	freopen(argv[1], "r", stdin);
    	freopen(argv[2], "w", stdout);
	node* trans[100], *bp[100];
	int layers = 0;
	int i, j, k;
	char type[128];
	int idx = 0;
	char *flag = "affine";
	while (NULL != gets(token))
    	{   
        	int nrow, ncol;
		if (token[0] == '{')
		{
			char *ss = strstr(token, flag);	
    			if (sscanf(ss, "affine%d_%[a-z]", &idx, type) == 2)
			{
				node *no = new node;
				scanf("%d %d", &nrow, &ncol);	
				no->nrow = nrow;
				no->ncol = ncol;
				no->index = idx;
				no->mat = (double **)malloc(nrow * sizeof(double *));
				for (i = 0; i < nrow; i++)
                		no->mat[i] = (double *)malloc(ncol * sizeof(double));
                		for (i = 0; i < nrow; i++)
            				for (j = 0; j < ncol; j++)
                    			scanf("%lf", no->mat[i] + j);
				
				if (nrow == 1)
					bp[idx] = no;
				else
					trans[idx] = no;		
				layers++;
			}
		}
	}
	if (layers%2)
	{
		perror("number layers of LinearTrans and Bias is not the same.\n");
		return -1;
	}

	layers /= 2;
	for (i = 0; i < layers; i++)
	{
		printf("<biasedlinearity> %d %d\n", trans[i]->ncol, trans[i]->nrow);
		printf("m %d %d\n", trans[i]->ncol, trans[i]->nrow);
		for (j = 0; j < trans[i]->ncol; j++)
		{
			for (k = 0; k < trans[i]->nrow; k++)
				printf("%.10lf ", trans[i]->mat[k][j]);		
			printf("\n");
		}
		printf("v %d", bp[i]->ncol);	
		for (j = 0; j < bp[i]->ncol; j++)
			printf(" %.10lf", bp[i]->mat[0][j]);
		printf("\n");	
		if (i != layers - 1 && trans[i+1]->ncol < trans[i+1]->nrow)
		printf("<sigmoid> %d %d\n", bp[i]->ncol, bp[i]->ncol);
	}
	printf("<softmax> %d %d\n", bp[layers - 1]->ncol, bp[layers - 1]->ncol);
	perror("done!\n");

	return 0;
}