Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Hello! Help me with python ML , please! For numerical features, impelement a class that normalizes each feature values by subtracting the mean and dividing
Hello! Help me with python ML please!
For numerical features, impelement a class that normalizes each feature values by subtracting the mean and dividing by the standard deviation.
Implement a fit method that takes as input feature matrix X and computes and saves mean and std values of each feature assuming that all the features are numerical The feature matrix can be either pdDataFrame, or npndarray.
Implement a transform method that takes as input feature matrix X and normalizes each column using precomputed mean and std values for this feature.
from sklearn.base import TransformerMixin, BaseEstimator
class ScalerBaseEstimator TransformerMixin:
def fitself X yNone:
Compute and save mean and standard deviation values
of each feature in the feature matrix.
Parameters
X : pdDataFrame or numpy.ndarray of shape nsamples, nfeatures
Feature matrix.
y : pdSeries or numpy.ndarray of shape nsamples,default : None
Target values. Optional.
Returns
self : returns an instance of self.
self.columnmean
self.columnstd
for i in rangeXshape:
# extract column values
if typeX is not npndarray:
Xi Xvalues: i
else:
Xi X: i
# compute mean and std
# YOUR CODE HERE
raise NotImplementedError
return self
def transformself X:
Normalizes values of each feature
by subtructing the corresponding precomputed feature mean
and dividing by the corresponding standard deviation.
Parameters
X : pdDataFrame or numpy.ndarray of shape nsamples, nfeatures
Feature matrix.
Returns
Xtransformed : arraylike of shape nsamples, nfeatures
Transformed feature matrix.
Xtransformed
for i in rangelenselfcolumnmean:
# extract column values
if typeX is not npndarray:
Xi Xvalues: i
else:
Xi X: i
# YOUR CODE HERE
raise NotImplementedError
Xtransformed npcolumnstackXtransformed
return Xtransformed
# TEST Scaler class
A nparangereshape
scaler Scaler
scaler.fitA
assert npallclosescalercolumnmean, "Computed mean values are incorrect."
assert npallclosescalercolumnstd "Computed std values are incorrect."
scaler.fitpdDataFrameA
Atransformed scaler.transformpdDataFrameA
assert npallcloseAtransformed,
"Scaled values are incorrect."
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started