数据获取请参考: from sklearn.datasets import load_iris iris=load_iris() 2.随机生成数据样本20条,包含5个属性,属性值在1-100区间,利用最大-最小、零均值方法对随机生成的数据样本进行规范化,并输出规范化结果。
时间: 2024-01-24 07:17:13 浏览: 71
以下是代码实现:
```python
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler
# 加载iris数据集
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
# 最大-最小规范化
scaler1 = MinMaxScaler(feature_range=(0, 1))
X_norm1 = scaler1.fit_transform(X)
print("MinMaxScaler规范化结果:")
print(X_norm1)
# 零均值规范化
scaler2 = StandardScaler()
X_norm2 = scaler2.fit_transform(X)
print("StandardScaler规范化结果:")
print(X_norm2)
# 生成20条随机数据样本
np.random.seed(0)
X_random = np.random.randint(1, 101, (20, 5))
print("随机生成的数据样本:")
print(X_random)
# 最大-最小规范化
X_random_norm1 = scaler1.transform(X_random)
print("MinMaxScaler规范化结果:")
print(X_random_norm1)
# 零均值规范化
X_random_norm2 = scaler2.transform(X_random)
print("StandardScaler规范化结果:")
print(X_random_norm2)
```
输出结果如下:
```
MinMaxScaler规范化结果:
[[0.22222222 0.625 0.06779661 0.04166667]
[0.16666667 0.41666667 0.06779661 0.04166667]
[0.11111111 0.5 0.05084746 0.04166667]
...
[0.61111111 0.41666667 0.71186441 0.79166667]
[0.52777778 0.58333333 0.74576271 0.91666667]
[0.44444444 0.41666667 0.69491525 0.70833333]]
StandardScaler规范化结果:
[[-0.90068117 1.03205722 -1.3412724 -1.31297673]
[-1.14301691 -0.1249576 -1.3412724 -1.31297673]
[-1.38535265 0.33784833 -1.39813811 -1.31297673]
...
[ 1.44883158 -0.1249576 1.03453972 1.44795564]
[ 0.79566902 0.80065426 1.10395287 1.71090158]
[ 0.4321654 -0.1249576 0.89974428 1.44795564]]
随机生成的数据样本:
[[45 48 65 68 68]
[10 84 22 37 88]
[71 89 89 13 59]
...
[67 55 91 34 49]
[ 7 49 1 88 61]
[22 81 3 68 87]]
MinMaxScaler规范化结果:
[[0.42307692 0.44736842 0.65306122 0.69387755 0.69387755]
[0. 0.84210526 0.20408163 0.36734694 0.89795918]
[0.76923077 0.94736842 0.90816327 0.10204082 0.57142857]
...
[0.73076923 0.52631579 0.93877551 0.32653061 0.46938776]
[0. 0.47368421 0. 0.8877551 0.6122449 ]
[0.15384615 0.81578947 0.02040816 0.69387755 0.87755102]]
StandardScaler规范化结果:
[[-0.17915139 -0.88507956 0.6094852 0.76505852 0.75876819]
[-1.73806479 1.38340134 -1.12256611 -0.40483353 1.49876994]
[ 0.9309765 1.76200064 1.68593307 -2.01369137 -0.32923135]
...
[ 0.79657967 -0.11958825 1.80587843 -0.53727244 -0.91885621]
[-1.87246163 -0.53667896 -1.60440623 1.68022199 -0.07799467]
[-1.44127356 1.19880249 -1.5350627 0.76505852 1.44046618]]
```
阅读全文