可以使用round()函数。
round(a,2)即表示a保留两位小数
深度学习中经常遇到变量和常量转换的问题,可以使用item()函数,
关于x.item()用法:
文档中给了例子,说是一个元素张量可以用item得到元素值,请注意这里的print(x)和print(x.item())值是不一样的,一个是打印张量,一个是打印元素:
- x = torch.randn(1)
- print(x)
- print(x.item())
-
- #结果是
- tensor([-0.4464]) # 为张量
- -0.44643348455429077 # 为常量
- #
-
- # -*- encoding: utf-8 -*-
- from flask import Flask, render_template
- app = Flask(__name__)
-
- @app.route('/')
- def index():
- Res['num'] = 1
- Res['bboxes'] = bboxes_n # 参数自己设置,我是用bbox坐标的
- Res['predtime'] = round(r_time, 2)
- # 使用render_template模块来渲染模板文件,通过第二个参数传递数据变量
- # return render_template('day3.html', my_shijei=my_str, myint=my_int, mydict=my_dict, mylist=my_list)
- # 通过**引用来将嵌套dict直接传递给模板
- return render_template('template.html', **Res)
-
- if __name__ == "__main__":
- app.run(host='0.0.0.0', port=5000, debug=True, processes=True)
-
- <!DOCTYPE html>
- <title>File Browser</title>
- <h1>File Browser</h1>
-
- <p>URL: {{ file_url }}</p>
- <p>num: {{ num }}</p>
- {% for i in bboxes %}
- <p>bbox : {{i}}</p>
- {% endfor %}
- <p>predtime: {{ predtime }}s</p>
-
json中包含numpy类型等参数时,dumps转换时会报错,需要自己定义一个转换函数。
TypeError: Object of type ‘int64’ is not JSON serializable (或者float32)
- # 首先,继承json.JSONEncoder,自定义序列化方法。
- class NpEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, np.integer):
- return int(obj)
- elif isinstance(obj, np.floating):
- return float(obj)
- elif isinstance(obj, np.ndarray):
- return obj.tolist()
- else:
- return super(NpEncoder, self).default(obj)
- # 使用dumps方法(我们可以直接把dict直接序列化为json对象)加上 cls=NpEncoder,data就可以正常序列化了
- json_res = json.dumps(Res, ensure_ascii=False, cls=NpEncoder)
-
- # dict转json
- import json
- names = ['joker','joe','nacy','timi']
- filename='names.json'
- with open(filename,'w') as file_obj:
- json.dump(names,file_obj)
-
- # json文件转dict
- filename='names.json'
- with open(filename) as file_obj:
- names = json.load(file_obj)
- print(names)
-