加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
tensor_normalize.py 3.20 KB
一键复制 编辑 原始数据 按行查看 历史
"""
This is the module main file
"""
from __future__ import print_function
import numpy as np
def mean_std(p_array):
"""
result = (p_array - np.mean(p_array)) / np.std(p_array) \n
:rtype: numpy.array:
:param numpy.array p_array: the array needed to be normalized
"""
check_params(p_array)
mean = np.mean(p_array)
std = np.std(p_array)
result = (p_array - mean) / std
return result
def mean_std_back(p_array, y_predict):
"""
数组归一化的反向求解\n
y_predict = (p_array - np.mean(p_array)) / np.std(p_array) \n
p_array = (y_predict * np.std(p_array)) + np.mean(p_array)
:rtype: numpy.array:
:param numpy.array|float y_predict: one of the data that has been normalized
:param numpy.array p_array: original entire array
"""
check_params(p_array)
mean = np.mean(p_array)
std = np.std(p_array)
result = (y_predict * std) + mean
return result
def max_interval_divided(p_array):
"""
把数组中元素按照数组的最大间隔范围映射为 0 - 1 区间的 float \n
:rtype: numpy.array
:param numpy.array p_array: the array needed to be normalized
公式:\n
result = (p_array - arr_min) / (arr_max - arr_min)
"""
check_params(p_array)
arr_max = np.max(p_array)
arr_min = np.min(p_array)
result = (p_array - arr_min) / (arr_max - arr_min)
return result
def max_interval_divided_back(p_array, y_predict):
"""
数组归一化的反向求解\n
数组间隔范围映射为 0 - 1,求给定的值的真实值 \n
:rtype: float
:param numpy.array|float y_predict: one of the data that has been normalized
:param numpy.array p_array: original entire array
公式如下: \n
y_predict = (result - arr_min) / (arr_max - arr_min) \n
result = (y_predict * (arr_max - arr_min)) + arr_min \n
"""
check_params(p_array)
arr_max = np.max(p_array)
arr_min = np.min(p_array)
result = y_predict * (arr_max - arr_min) + arr_min
return result
def check_params(params):
"""
Check the type and content of the parameters \n
:param numpy.array params: the given parameter
"""
# check type
if not isinstance(params, np.ndarray):
print("Wrong parameter type, Needed Numpy array")
exit()
# check data type
p_type = params.dtype
isdigit = p_type in ['int32', 'int64', 'float32', 'float64']
if not isdigit:
print("Wrong Type of data,Needed int32,int64,float32,float64")
exit()
# Check whether the Nan is included
if np.isnan(params).sum() > 0:
print("Parameters include NAN, Please Check your data")
exit()
if __name__ == '__main__':
a = [[x, x + 1, x + 2, x + 3, x + 4] for x in range(10)]
a = np.array(a)
print(a)
normalized = mean_std(a)
latest_item = normalized[-1,-1]
print(normalized)
print(latest_item)
restore = mean_std_back(a, latest_item)
print("restore: ", restore)
print("original: ", a[-1, -1])
# normalized = max_interval_divided(p_array)
# test = normalized[:3]
# back = max_interval_divided_back(p_array, test)
# back = max_interval_divided_back(p_array, 0.125)
# print(p_array, normalized, test, back)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化