sklearn normalize example

Example 1: Scaling features to a range

# Scaling features to a range using MinMaxScaler

X_train = np.array([[ 1., -1.,  2.],
                    [ 2.,  0.,  0.],
                    [ 0.,  1., -1.]])

min_max_scaler = preprocessing.MinMaxScaler()
X_train_minmax = min_max_scaler.fit_transform(X_train)
X_train_minmax
# array([[0.5		, 0.		, 1.	    ],
#        [1.		, 0.5		, 0.33333333],
#        [0.		, 1.		, 0.		]])

X_test = np.array([[-3., -1.,  4.]])
X_test_minmax = min_max_scaler.transform(X_test)
X_test_minmax
# array([[-1.5		,	0.		, 	1.66666667]])

min_max_scaler.scale_
# array([0.5       , 0.5       , 0.33...])

min_max_scaler.min_
# array([0.       , 0.5       , 0.33...])

Example 2: Scaling features to a range

# Scaling features to a range using MaxAbsScaler

X_train = np.array([[ 1., -1.,  2.],
                    [ 2.,  0.,  0.],
                    [ 0.,  1., -1.]])

max_abs_scaler = preprocessing.MaxAbsScaler()
X_train_maxabs = max_abs_scaler.fit_transform(X_train)
X_train_maxabs
# array([[ 0.5, -1.,  1. ],
#        [ 1. ,  0. ,  0. ],
#        [ 0. ,  1. , -0.5]])
X_test = np.array([[ -3., -1.,  4.]])
X_test_maxabs = max_abs_scaler.transform(X_test)
X_test_maxabs
# array([[-1.5, -1. ,  2. ]])
max_abs_scaler.scale_
# array([2.,  1.,  2.])

Tags:

Misc Example