个人笔记--python代码--储存数据

1. 存储Error(txt文件)

python 复制代码
import numpy as np

 # Error
 error_u = np.linalg.norm(exact_u_current - predict_np_u, 2) / np.linalg.norm(exact_u_current, 2)
 error_v = np.linalg.norm(exact_v_current - predict_np_v, 2) / np.linalg.norm(exact_v_current, 2)
 error_p = np.linalg.norm(exact_p_current - predict_np_p, 2) / np.linalg.norm(exact_p_current, 2)

 print('Error u: %e' % error_u)
 print('Error v: %e' % error_v)
 print('Error p: %e' % error_p)

 # 打开一个文件以追加写入模式
 with open('errors.txt', 'a') as file:
     file.write('\n')
     file.write('From t = %f to t = %f\n' % (t_current[0], t_current[-1]))
     file.write('Error u: %e\n' % error_u)
     file.write('Error v: %e\n' % error_v)
     file.write('Error p: %e\n' % error_p)
     file.write('\n')

这里的with open('errors.txt', 'a') as file:的'a'指的是追加模式 (append mode)。如果文件不存在,会创建一个新文件。如果文件存在,新的内容会被追加到文件的末尾,而不会覆盖原有内容。

而with open('errors.txt', 'w') as file:的'w'表示写入模式 (write mode)。如果文件不存在,会创建一个新文件。如果文件存在,原有内容会被清空,新的内容会覆盖原有内容。

2. 存储数值 (matlab文件)

python 复制代码
import os
import scipy.io

file_name = "./current_figures_matlab_data/"

if not os.path.exists(file_name):
    os.mkdir(file_name)

scipy.io.savemat(file_name + "Sol_" + params_name + "_" + str(pic_num) + ".mat",
                {'x': unique_x, 'y': unique_y, 't': t_current,
                 'exact_u_current': exact_u_current, 'predict_np_u': predict_np_u,
                 'exact_v_current': exact_v_current, 'predict_np_v': predict_np_v,
                 'exact_p_current': exact_p_current, 'predict_np_p': predict_np_p,
                 'exact_u_current_plot_final': exact_u_current, 'u_pred_plot_final': u_pred_plot_final,
                 'exact_v_current_plot_final': exact_v_current, 'v_pred_plot_final': v_pred_plot_final,
                 'exact_p_current_plot_final': exact_p_current, 'p_pred_plot_final': p_pred_plot_final})

储存为.mat文件,这样后期就可以直接在MATLAB画图或者做其他分析。

3. 储存loss数值 (csv文件)

python 复制代码
import numpy as np

def print_boundary_value_count(AM_count, current_t_num):
    np.savetxt("boundary_value/boundary_value_top" + params_name + "_" + str(current_t_num) + "_" + str(AM_count) + ".csv", model.boundary_value_top_collect, delimiter=',',
               header='x,y,pred,given')
    np.savetxt("boundary_value/boundary_value_bottom" + params_name + "_" + str(current_t_num) + "_" + str(AM_count) + ".csv", model.boundary_value_bottom_collect, delimiter=',',
               header='x,y,pred,given')
    np.savetxt("boundary_value/boundary_value_left" + params_name + "_" + str(current_t_num) + "_" + str(AM_count) + ".csv", model.boundary_value_left_collect, delimiter=',',
               header='x,y,pred,given')
    np.savetxt("boundary_value/boundary_value_right" + params_name + "_" + str(current_t_num) + "_" + str(AM_count) + ".csv", model.boundary_value_right_collect, delimiter=',',
               header='x,y,pred,given')

这里虽然是.csv文件,但是可以用excel打开,只需要在excel里全选把格式改一下就能看见数据。

或者用以下方式存储为.csv文件

python 复制代码
import pandas as pd

# 创建一个DataFrame来存储实际值和预测值
results = pd.DataFrame({
    'Actual': u_test,
    'Predicted': u_pred
})

# 将DataFrame保存为CSV文件
results.to_csv('predictions.csv', index=False)

4. 储存预测值 (excel文件)

python 复制代码
import pandas as pd

# 创建一个DataFrame来存储实际值和预测值
results = pd.DataFrame({
    'Actual': u_test,
    'Predicted': u_pred
})

# 将DataFrame保存为Excel文件
results.to_excel('predictions.xlsx', index=False)

5. 储存训练模型 (pt文件)

python 复制代码
 if model.save:
     torch.save(model.net.state_dict(), './models/' + params_name + "-" + str(i) + "-" + '.pt')

Note:

以上所有代码都是不完整的,部分是从我自己代码抽取出来整理的。只是提供一个思路。

作用只是为了我自己后期需要用到这个功能然后看一眼知道大概怎么处理而已。

代码出现很多的params_name是一个我自己创建的参数名称,用了argparse.ArgumentParser()。

python 复制代码
    params_name = ("_2D_" + str(args.PDE_type) + "_" + str(version_num) + "_ADAM=" + str(args.adam_iter) + "_LBFGS=" + str(args.lbfgs_iter)
                   + "_Nx=" + str(args.num_x) + "_Ny=" + str(args.num_y) + "_N=" + str(args.N) + "_M=" + str(args.M) + "_Mb=" + str(args.M_b)
                   + "_h=" + str(args.hid_layers) + "_n=" + str(args.hid_neurons) + "_ADAMlr=" + str(args.lbfgs_lr)
                   + "_modelType=" + str(args.model_type) + "_AMType=" + str(args.AM_type) + "_AMk=" + str(args.AM_K)
                   + "_AMCount=" + str(args.AM_count) + "_AWlr=" + str(args.AW_lr) + "_q=" + str(args.q)
                   + "_move_type=" + str(args.move_type) + "_init=" + str(args.init_cond)
                   + "_bound=" + str(args.boundary_cond) + "_ep=" + str(args.epsilon)
                   + "_Ld=" + str(args.L_d) + "_")
相关推荐
冷雨夜中漫步1 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴2 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再2 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
喵手4 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934734 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
Gain_chance4 小时前
34-学习笔记尚硅谷数仓搭建-DWS层最近一日汇总表建表语句汇总
数据仓库·hive·笔记·学习·datagrip
helloworldandy4 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
Gain_chance5 小时前
36-学习笔记尚硅谷数仓搭建-DWS层数据装载脚本
大数据·数据仓库·笔记·学习
肖永威5 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ5 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto