# 在 Python 中對數字列表進行歸一化

Fariba Laiq 2022年5月17日 Python Python List

## 歸一化公式

$$X_{norm} = {x-x_{min}\over x_{max}-x_{min}}$$

## 使用 Python sklearn 中的 MinMaxScaler 函式歸一化數字列表

sklearn 包的 preprocessing 模組中提供了一個名為 MinMaxScaler() 的內建方法。我們將建立一個一維 NumPy 陣列並將其傳遞給函式。我們必須安裝 NumPysklearn 軟體包才能使用此功能。

# python 3.x
import numpy as np
from sklearn import preprocessing
list = np.array([6,1,0,2,7,3,8,1,5]).reshape(-1,1)
print('Original List:',list)
scaler = preprocessing.MinMaxScaler()
normalizedlist=scaler.fit_transform(list)
print('Normalized List:',normalizedlist)


Original List: [[6]
[1]
[0]
[2]
[7]
[3]
[8]
[1]
[5]]
Normalized List: [[0.75 ]
[0.125]
[0.   ]
[0.25 ]
[0.875]
[0.375]
[1.   ]
[0.125]
[0.625]]


# python 3.x
import numpy as np
from sklearn import preprocessing
list = np.array([6,1,0,2,7,3,8,1,5]).reshape(-1,1)
print('Original List:',list)
scaler = preprocessing.MinMaxScaler(feature_range=(0, 3))
normalizedlist=scaler.fit_transform(list)
print('Normalized List:',normalizedlist)


Original List: [[6]
[1]
[0]
[2]
[7]
[3]
[8]
[1]
[5]]
Normalized List: [[2.25 ]
[0.375]
[0.   ]
[0.75 ]
[2.625]
[1.125]
[3.   ]
[0.375]
[1.875]]


## 在 Python 中手動歸一化數字列表

list = [6,1,0,2,7,3,8,1,5]
print('Original List:',list)
xmin = min(list)
xmax=max(list)
for i, x in enumerate(list):
list[i] = (x-xmin) / (xmax-xmin)
print('Normalized List:',list)


Original List: [6, 1, 0, 2, 7, 3, 8, 1, 5]
Normalized List: [0.75, 0.125, 0.0, 0.25, 0.875, 0.375, 1.0, 0.125, 0.625]

Author: Fariba Laiq

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.