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

命令执行过程图,如下。

命令执行结果

命令执行效果


从上图中可以看出,转换格式后,数据很容易阅读。

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读取效果

相关文章
|
4月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
6月前
|
机器学习/深度学习 数据采集 数据挖掘
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
222 2
|
4月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
7月前
|
JSON API 数据格式
Python采集京东商品评论API接口示例,json数据返回
下面是一个使用Python采集京东商品评论的完整示例,包括API请求、JSON数据解析
|
7月前
|
存储 JSON API
Python与JSON:结构化数据的存储艺术
Python字典与JSON格式结合,为数据持久化提供了便捷方式。通过json模块,可轻松实现数据序列化与反序列化,支持跨平台数据交换。适用于配置管理、API通信等场景,兼具可读性与高效性,是Python开发中不可或缺的数据处理工具。
304 0
|
4月前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
481 4
|
4月前
|
JSON API 数据处理
Swagger动态参数注解:使用@DynamicParameters实现JSON参数的灵活定义
总结起来,通过使用SpringFox提供给我们工具箱里面非常有力量但又不太显眼工具———即使面对复杂多变、非标准化数据格式也能轻松驾驭它们———从而大大增强我们系统与外界沟通交流能力同时也保证系统内部数据处理逻辑清晰明确易于维护升级.
312 10
|
5月前
|
JSON API 数据安全/隐私保护
Python采集淘宝评论API接口及JSON数据返回全流程指南
Python采集淘宝评论API接口及JSON数据返回全流程指南
|
5月前
|
机器学习/深度学习 数据采集 并行计算
多步预测系列 | LSTM、CNN、Transformer、TCN、串行、并行模型集合研究(Python代码实现)
多步预测系列 | LSTM、CNN、Transformer、TCN、串行、并行模型集合研究(Python代码实现)
536 2
|
5月前
|
JSON 缓存 开发者
淘宝商品详情接口(item_get)企业级全解析:参数配置、签名机制与 Python 代码实战
本文详解淘宝开放平台taobao.item_get接口对接全流程,涵盖参数配置、MD5签名生成、Python企业级代码实现及高频问题排查,提供可落地的实战方案,助你高效稳定获取商品数据。

推荐镜像

更多