python 数据标准化
时间: 2023-10-26 15:20:20 浏览: 40
数据标准化是将数据转换为具有相同范围的统一尺度的过程,通常用于机器学习和数据挖掘中。在 Python 中,可以使用 scikit-learn 库的 StandardScaler 类来实现数据标准化。具体操作如下:
1. 导入必要的库和数据集:
```python
from sklearn.preprocessing import StandardScaler
import numpy as np
data = np.array([[1, 2], [3, 4], [5, 6]])
```
2. 创建 StandardScaler 对象:
```python
scaler = StandardScaler()
```
3. 使用 fit_transform() 方法对数据进行标准化:
```python
scaled_data = scaler.fit_transform(data)
```
这将返回一个标准化后的数据集 scaled_data,其中每个特征都具有均值为 0 和标准差为 1。
完整代码示例:
```python
from sklearn.preprocessing import StandardScaler
import numpy as np
# 创建数据集
data = np.array([[1, 2], [3, 4], [5, 6]])
# 创建 StandardScaler 对象
scaler = StandardScaler()
# 对数据进行标准化
scaled_data = scaler.fit_transform(data)
print("原始数据集:\n", data)
print("标准化后的数据集:\n", scaled_data)
```
输出结果:
```
原始数据集:
[[1 2]
[3 4]
[5 6]]
标准化后的数据集:
[[-1.22474487 -1.22474487]
[ 0. 0. ]
[ 1.22474487 1.22474487]]
```