“ 我们先来编写一个算法,或者功能,无论你怎么称呼这个操作。我们要实现的是,把一组数据,压缩到0到1之间,但不改变这组数据之间的相对关系。(小白可能会问:这样做的意义是什么?OK,这个疑问先埋藏在心里,我们后面再解释)
”
例如:有一组数据,是学生的体重,我们将这组数据放在一个列表(list类型)里,列表中的元素,即体重,都是int类型的数值。
body_weight = [120, 89, 112, 135, 141, 83, 95, 90]
实现代码,你可以这样写:
import numpy as npbody_weight = [120, 89, 112, 135, 141, 83, 95, 90]max_weight = np.max(body_weight)min_weight = np.min(body_weight)body_weight_standard = []for item in body_weight: tmp = (item - min_weight) / (max_weight - min_weight) body_weight_standard.append(tmp)print('压缩后的体重表:\n', body_weight_standard)
输出:
压缩后的体重表:
[0.6379310344827587, 0.10344827586206896, 0.5, 0.896551724137931, 1.0, 0.0, 0.20689655172413793, 0.1206896551724138]
你还可以这样写:
import numpy as npbody_weight = [120, 89, 112, 135, 141, 83, 95, 90]def myStandard(input_x): max_weight = np.max(input_x) min_weight = np.min(input_x) output_y = [] for item in input_x: tmp = (item - min_weight) / (max_weight - min_weight) output_y.append(tmp) return output_ybody_weight_standard = myStandard(body_weight)print('压缩后的体重表:\n', body_weight_standard)
输出和上面是一样的。
当然,你还可以这样写:
import numpy as npclass myClass: def myStandard(self, input_x): max_weight = np.max(input_x) min_weight = np.min(input_x) output_y = [] for item in input_x: tmp = (item - min_weight) / (max_weight - min_weight) output_y