ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-01-17 21:34:08  阅读:127  来源: 互联网

标签:Python nNumber child ret C语言 modelPara JSON num printf


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

命令执行过程图,如下。
在这里插入图片描述
命令执行结果
在这里插入图片描述
命令执行效果
在这里插入图片描述
从上图中可以看出,转换格式后,数据很容易阅读。

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,nNumber,child,ret,C语言,modelPara,JSON,num,printf
来源: https://blog.csdn.net/a72944392/article/details/122548279

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有