如何在Python的NumPy中对数组进行标准化
在这篇文章中,我们将讨论如何在Python中使用NumPy对一维和二维数组进行归一化。归一化是指将一个数组的值缩放到所需的范围。
一维阵列的规范化
假设我们有一个数组=[1,2,3],在[0,1]范围内进行归一化,意味着将数组[1,2,3]转换为[0, 0.5, 1],因为1,2和3是等距的。
Array [1,2,4] -> [0, 0.3, 1]
这也可以在一个范围内进行,即用[0,1]来代替[3,7]。
现在,
Array [1,2,3] -> [3,5,7]
和
Array [1,2,4] -> [3,4.3,7]
让我们看看有代码的例子
示例 1:
# import module
import numpy as np
# explicit function to normalize array
def normalize(arr, t_min, t_max):
norm_arr = []
diff = t_max - t_min
diff_arr = max(arr) - min(arr)
for i in arr:
temp = (((i - min(arr))*diff)/diff_arr) + t_min
norm_arr.append(temp)
return norm_arr
# gives range staring from 1 and ending at 3
array_1d = np.arange(1,4)
range_to_normalize = (0,1)
normalized_array_1d = normalize(array_1d,
range_to_normalize[0],
range_to_normalize[1])
# display original and normalized array
print("Original Array = ",array_1d)
print("Normalized Array = ",normalized_array_1d)
输出:
示例 2:
现在,Lets的输入数组是[1,2,4,8,10,15],范围也是[0,1] 。
# import module
import numpy as np
# explicit function to normalize array
def normalize(arr, t_min, t_max):
norm_arr = []
diff = t_max - t_min
diff_arr = max(arr) - min(arr)
for i in arr:
temp = (((i - min(arr))*diff)/diff_arr) + t_min
norm_arr.append(temp)
return norm_arr
# assign array and range
array_1d = [1, 2, 4, 8, 10, 15]
range_to_normalize = (0, 1)
normalized_array_1d = normalize(
array_1d, range_to_normalize[0],
range_to_normalize[1])
# display original and normalized array
print("Original Array = ", array_1d)
print("Normalized Array = ", normalized_array_1d)
输出:
二维阵列的归一化
为了使二维数组或矩阵正常化,我们需要NumPy库。对于矩阵来说,一般的归一化是使用欧氏规范或弗罗比纽斯规范。
简单归一化的公式是
这里,v是矩阵,|v|是行列式,也叫欧几里得准则。v-cap是归一化矩阵。
以下是实施上述内容的一些例子。
示例 1:
# import module
import numpy as np
# explicit function to normalize array
def normalize_2d(matrix):
norm = np.linalg.norm(matrix)
matrix = matrix/norm # normalized matrix
return matrix
# gives and array staring from -2
# and ending at 13
array = np.arange(16) - 2
# converts 1d array to a matrix
matrix = array.reshape(4, 4)
print("Simple Matrix \n", matrix)
normalized_matrix = normalize_2d(matrix)
print("\nSimple Matrix \n", normalized_matrix)
输出:
示例 2:
我们也可以使用其他规范,如1-norm或2-norm
# import module
import numpy as np
def normalize_2d(matrix):
# Only this is changed to use 2-norm put 2 instead of 1
norm = np.linalg.norm(matrix, 1)
# normalized matrix
matrix = matrix/norm
return matrix
# gives and array staring from -2 and ending at 13
array = np.arange(16) - 2
# converts 1d array to a matrix
matrix = array.reshape(4, 4)
print("Simple Matrix \n", matrix)
normalized_matrix = normalize_2d(matrix)
print("\nSimple Matrix \n", normalized_matrix)
输出:
通过这种方式,我们可以在python中用NumPy进行归一化处理。