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

相关文章
|
7天前
|
JSON 监控 API
python语言采集淘宝商品详情数据,json数据示例返回
通过淘宝开放平台的API接口,开发者可以轻松获取商品详情数据,并利用这些数据进行商品分析、价格监控、库存管理等操作。本文提供的示例代码和JSON数据解析方法,可以帮助您快速上手淘宝商品数据的采集与处理。
|
20天前
|
数据采集 JSON 测试技术
如何在Python中高效实现CSV到JSON的数据转换
在实际项目中,数据格式转换是常见问题,尤其从CSV到JSON的转换。本文深入探讨了多种转换方法,涵盖Python基础实现、数据预处理、错误处理、性能优化及调试验证技巧。通过分块处理、并行处理等手段提升大文件转换效率,并介绍如何封装为命令行工具或Web API,实现自动化批量处理。关键点包括基础实现、数据清洗、异常捕获、性能优化和单元测试,确保转换流程稳定高效。
138 83
|
25天前
|
人工智能 JSON 搜索推荐
猫步简历 - 开源免费AI简历生成器 | 一键导出PDF/JSON
猫步简历是一款免费开源的AI简历生成器,帮助用户轻松创建独特、专业的简历。支持导出超高清PDF、图片、JSON等多种格式,并提供AI智能创作、润色和多语种切换等功能。拥有海量模板、高度定制化模块及完善的后台管理系统,助力求职者脱颖而出。官网:https://maobucv.com,GitHub开源地址:https://github.com/Hacker233/resume-design。
174 10
|
1月前
|
机器学习/深度学习 存储 算法
解锁文件共享软件背后基于 Python 的二叉搜索树算法密码
文件共享软件在数字化时代扮演着连接全球用户、促进知识与数据交流的重要角色。二叉搜索树作为一种高效的数据结构,通过有序存储和快速检索文件,极大提升了文件共享平台的性能。它依据文件名或时间戳等关键属性排序,支持高效插入、删除和查找操作,显著优化用户体验。本文还展示了用Python实现的简单二叉搜索树代码,帮助理解其工作原理,并展望了该算法在分布式计算和机器学习领域的未来应用前景。
|
2月前
|
监控 网络安全 开发者
Python中的Paramiko与FTP文件夹及文件检测技巧
通过使用 Paramiko 和 FTP 库,开发者可以方便地检测远程服务器上的文件和文件夹是否存在。Paramiko 提供了通过 SSH 协议进行远程文件管理的能力,而 `ftplib` 则提供了通过 FTP 协议进行文件传输和管理的功能。通过理解和应用这些工具,您可以更加高效地管理和监控远程服务器上的文件系统。
61 20
|
2月前
|
存储 数据采集 数据处理
如何在Python中高效地读写大型文件?
大家好,我是V哥。上一篇介绍了Python文件读写操作,今天聊聊如何高效处理大型文件。主要方法包括:逐行读取、分块读取、内存映射(mmap)、pandas分块处理CSV、numpy处理二进制文件、itertools迭代处理及linecache逐行读取。这些方法能有效节省内存,提升效率。关注威哥爱编程,学习更多Python技巧。
103 8
|
2月前
|
存储 JSON 对象存储
如何使用 Python 进行文件读写操作?
大家好,我是V哥。本文介绍Python中文件读写操作的方法,包括文件读取、写入、追加、二进制模式、JSON、CSV和Pandas模块的使用,以及对象序列化与反序列化。通过这些方法,你可以根据不同的文件类型和需求,灵活选择合适的方式进行操作。希望对正在学习Python的小伙伴们有所帮助。欢迎关注威哥爱编程,全栈路上我们并肩前行。
|
2月前
|
存储 算法 Serverless
剖析文件共享工具背后的Python哈希表算法奥秘
在数字化时代,文件共享工具不可或缺。哈希表算法通过将文件名或哈希值映射到存储位置,实现快速检索与高效管理。Python中的哈希表可用于创建简易文件索引,支持快速插入和查找文件路径。哈希表不仅提升了文件定位速度,还优化了存储管理和多节点数据一致性,确保文件共享工具高效运行,满足多用户并发需求,推动文件共享领域向更高效、便捷的方向发展。
|
3月前
|
分布式计算 MaxCompute 对象存储
|
3月前
|
计算机视觉 Python
如何使用Python将TS文件转换为MP4
本文介绍了如何使用Python和FFmpeg将TS文件转换为MP4文件。首先需要安装Python和FFmpeg,然后通过`subprocess`模块调用FFmpeg命令,实现文件格式的转换。代码示例展示了具体的操作步骤,包括检查文件存在性、构建FFmpeg命令和执行转换过程。
88 7

热门文章

最新文章

推荐镜像

更多