Python导出隐马尔科夫模型参数到JSON文件C语言读取

Python导出隐马尔科模型参数到JSON文件C语言读取


本文主要演示Python导出JSON文件,将模型参数保存到JSON文件,然后由C语言调用从JSON读取模型参数,读取具体参数,最后打印输出。

Python 导出隐马尔科夫模型参数

在Python中训练好模型后,将模型参数保存到Python字典中,然后调用json模块的dump函数,将字典整体以JSON格式保存到文件中。

参数导出

Python导出的数据有矩阵,数组,整数与字符串。下面是Python代码。

import numpy as np
import os
import json
import joblib

def model_export_test():

    para = dict()
    para['n'] = 2
    para['ft'] = 2
    para['m'] = [
        [
            0.65985107421875,
            4.225499739584418,
        ],
        [
            0.366943359375,
            12.658813626901697,

        ],
    ]
    para['c'] = [
        [
            0.011996133774518967,
            3.7065230565392455,
        ],
        [
            0.018222754001617433,
            4.0523744826252015,

        ],
    ],
    para['s'] = [
        0.15384615384615385,
        0.07692307692307693,
    ],
    para['t'] = [
        [
            0.6666666666666666,
            0.0,
        ],
        [
            0.0,
            0.5,
        ],
    ],
    para['ftType'] = 'ft30'
    para['sTNum'] = 1
    para['sTList'] = [1]
    return para


if '__main__' == __name__:
    para = dict()
    para['model_num'] = 2
    para['model1'] = model_export_test()
    para['model2'] = model_export_test()

    f = open(r'E:\\model.ini', 'wt')
    json.dump(para, f)
    f.close()

格式转换

由于json.dump导出的参数无换行,即所有数据都在同一行,阅读困难,因此需要根据数据添加换行符。在Python命令行中调用josn.tool完成格式转换。

python -m json.tool model.ini model_re.ini

命令执行过程图,如下。
Python导出隐马尔科夫模型参数到JSON文件C语言读取
命令执行结果
Python导出隐马尔科夫模型参数到JSON文件C语言读取
命令执行效果
Python导出隐马尔科夫模型参数到JSON文件C语言读取
从上图中可以看出,转换格式后,数据很容易阅读。

C语言读取模型参数

调用从cJSON读取JSON文件

调用从JSON中的cJSON_Parse函数读取JSON文件中的参数,cJSON_Parse返回的参数是结构的循环链表。文件读取代码如下。

	FILE *f;long len;char *data;
    int ret = -1;
	
	f=fopen(filename,"rb");fseek(f,0,SEEK_END);len=ftell(f);fseek(f,0,SEEK_SET);
	data=(char*)malloc(len+1);fread(data,1,len,f);fclose(f);
    /* doit(data); */
	char *out;cJSON *json;
	
	json=cJSON_Parse(data);
    printf("json file name:%s \n", filename);
    printf("type: %d \n", json->type);

参数再提取

cJSON读取的数据不方便直接使用,因此需要做进一步整理,本文是将模型参数提取到模型结构体数组中。

int readHmodelParaFromfile1(char *filename, modelPara1_t *modelPara, int model_num)
{
	FILE *f;long len;char *data;
    int ret = -1;
	
	f=fopen(filename,"rb");fseek(f,0,SEEK_END);len=ftell(f);fseek(f,0,SEEK_SET);
	data=(char*)malloc(len+1);fread(data,1,len,f);fclose(f);
    /* doit(data); */
	char *out;cJSON *json;
	
	json=cJSON_Parse(data);
    printf("json file name:%s \n", filename);
    printf("type: %d \n", json->type);

    int numentries=0;
    cJSON *child, *child_bf;
    child = json->child;

    while (child) numentries++,child=child->next;
    printf("numentries:%d \n", numentries);
    if(!json || numentries != json->child->valueint && 0 != strcmp(json->child->string, MODEL_NUM) || model_num < numentries)
    {
        printf("model file error !!!!!!!!!\n");
        return ret;
    }
    child_bf = json->child;

    int numentries_idx = 1;

	while(numentries_idx < numentries)
	{
	    /*
		out=cJSON_Print(json);
		cJSON_Delete(json);
		printf("%s\n",out);
		free(out);
		*/
		child_bf = child_bf->next;
		child = child_bf->child;
		getintValueUsingName(child, &modelPara->fNumber, "n");
        getintValueUsingName(child, &modelPara->nNumber, "ft");
        printf("n:%d f:%d\n\n", modelPara->nNumber, modelPara->fNumber);

        modelPara->m = malloc(sizeof(double) * modelPara->nNumber * modelPara->fNumber);
        ret = getMatUsingName(child, modelPara->m, (char *)MODEL_M_NAME, modelPara->nNumber, modelPara->fNumber);
        printf("%s ret:%d value:%lf\n\n", MODEL_M_NAME, ret, modelPara->m[modelPara->nNumber * modelPara->fNumber - 1]);

        modelPara->c = malloc(sizeof(double) * modelPara->nNumber * modelPara->fNumber);
        ret = getMatUsingName(child, modelPara->c, (char *)MODEL_C_NAME, modelPara->nNumber, modelPara->fNumber);
        printf("%s ret:%d value:%lf\n\n", MODEL_C_NAME, ret, modelPara->c[modelPara->nNumber * modelPara->fNumber - 1]);
        mat_check_maximum(modelPara->c, modelPara->nNumber, modelPara->fNumber);

        modelPara->s = malloc(sizeof(double) * modelPara->nNumber);
        ret = getMatUsingName(child, modelPara->s, (char *)MODEL_S_NAME, 1, modelPara->nNumber);
        printf("%s ret:%d value:%lf\n\n", MODEL_S_NAME, ret, modelPara->s[modelPara->nNumber - 1]);

        modelPara->t = malloc(sizeof(double) * modelPara->nNumber * modelPara->nNumber);
        ret = getMatUsingName(child, modelPara->t, (char *)MODEL_T_NAME, modelPara->nNumber, modelPara->nNumber);
        printf("%s ret:%d value:%lf\n\n", MODEL_T_NAME, ret, modelPara->t[modelPara->nNumber * modelPara->nNumber - 1]);

        ret = getintValueUsingName(child, &modelPara->sTNum, "sTNum");
        printf("%s ret:%d value:%d\n\n", "sTNum", ret, modelPara->sTNum);
        modelPara->sTList = malloc(sizeof(double) * modelPara->sTNum);
        ret = getArrayUsingName(child, modelPara->sTList, "sTList", modelPara->sTNum);
        printf("%s ret:%d value:%lf\n\n", "sTList", ret, modelPara->sTList[modelPara->sTNum - 1]);

        ret = getstringUsingName(child, modelPara->type, 127, "ftType");
        printf("%s ret:%d value:%s\n\n", "ftType", ret, modelPara->type);

        modelPara++;

        numentries_idx++;

	}

    cJSON_Delete(json);
    free(data);

	return ret;
}

参数打印函数

void print_model_matpara(modelPara_t *modelPara)
{
    int i,j;
    if(modelPara->m)
    {
        printf("m[%d][%d]:\n", modelPara->nNumber, modelPara->fNumber);
        for(i=0; i<modelPara->nNumber; i++)
        {
            for(j=0; j<modelPara->fNumber; j++)
            {
                printf("%lf ", modelPara->m[i*modelPara->fNumber + j]);
            }
            printf("\n");
        }
    }
    if(modelPara->c)
    {
        printf("c[%d][%d]:\n", modelPara->nNumber, modelPara->fNumber);
        for(i=0; i<modelPara->nNumber; i++)
        {
            for(j=0; j<modelPara->fNumber; j++)
            {
                printf("%lf ", modelPara->c[i*modelPara->fNumber + j]);
            }
            printf("\n");
        }
    }
    if(modelPara->s)
    {
        printf("s[%d]:\n", modelPara->nNumber);
        for(i=0; i<1; i++)
        {
            for(j=0; j<modelPara->nNumber; j++)
            {
                printf("%lf ", modelPara->s[i*modelPara->nNumber + j]);
            }
            printf("\n");
        }
    }
    if(modelPara->t)
    {
        printf("t[%d][%d]:\n", modelPara->nNumber, modelPara->nNumber);
        for(i=0; i<modelPara->nNumber; i++)
        {
            for(j=0; j<modelPara->nNumber; j++)
            {
                printf("%lf ", modelPara->t[i*modelPara->nNumber + j]);
            }
            printf("\n");
        }
    }
    if(0 < modelPara->score_th_num)
    {
        printf("\n score_th_list[%d]:\n", modelPara->score_th_num);
        for(i=0; i<modelPara->score_th_num; i++)
        {
            printf("%lf ", modelPara->score_th_list[i]);
        }
        printf("\n");
    }

    printf("\n height_th: %lf\n", modelPara->height_th);
    printf("\n height_max_th: %lf\n", modelPara->height_max_th);

    if(0 < modelPara->decay_factor_num)
    {
        printf("\ndecay_factor_num[%d]:\n", modelPara->decay_factor_num);
        for(i=0; i<modelPara->decay_factor_num; i++)
        {
            printf("%lf ", modelPara->decay_factor_list[i]);
        }
        printf("\n");
    }

    if(0 < modelPara->sub_times_num)
    {
        printf("\nsub_times_num[%d]:\n", modelPara->sub_times_num);
        for(i=0; i<modelPara->sub_times_num; i++)
        {
            printf("%lf ", modelPara->sub_times_list[i]);
        }
        printf("\n");
    }
    printf("\n up_th: %lf\n", modelPara->up_th);

    printf("\n up_num_th: %d\n", modelPara->up_num_th);
    printf("\n down_num_th: %d\n", modelPara->down_num_th);

    printf("\n peak_max_th: %lf\n", modelPara->peak_max_th);

    if(0 < modelPara->dumpling_num)
    {
        printf("\n dumpling_num: %d\n", modelPara->dumpling_num);
    }

    printf("\n fl: %d\n", modelPara->fl);
    printf("\n fs: %d\n", modelPara->fs);

    printf("\n pre_times: %lf\n", modelPara->pre_times);
    printf("\n late_time: %lf\n", modelPara->late_time);

    printf("\n ft_type: %s\n", modelPara->ft_type);
    printf("\n band_num: %d\n", modelPara->band_num);

    printf("\n frq_start: %lf\n", modelPara->frq_start);
    printf("\n frq_end: %lf\n", modelPara->frq_end);


    
}

主函数

int main (int argc, const char * argv[]) {

    modelPara1_t modelPara[10];

	/* dofile("./json.ini"); */
    readHmodelParaFromfile1("./model_re.ini", modelPara, 10);
    printf("\n\n model 1\n\n");
    print_model_matpara1(modelPara);
    printf("\n\n model 2\n\n");
    print_model_matpara1(&modelPara[1]);
	return 0;
}

C读取效果

Python导出隐马尔科夫模型参数到JSON文件C语言读取

上一篇:FastAPI(45)- 返回响应数据的五种常见方式


下一篇:336. 回文对