Question: Hello! Help with python, please! For numerical features, impelement a class that fills missing values in each feature with its mean value. Implement a fit
Hello! Help with python, please!
For numerical features, impelement a class that fills missing values in each feature with its mean value.
Implement a fit method that takes as input feature matrix X and computes and saves mean value 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 replaces NaN values in each feature with a corresponding mean value and returns a transformed feature matrix.
from sklearn.base import TransformerMixin, BaseEstimator
class MeanImputerBaseEstimator TransformerMixin:
def fitself X yNone:
Compute and save mean value 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
for i in rangeXshape:
if typeX is not npndarray:
Xi Xvalues: i
else:
Xi X: i
# calculate mean for each column and add to the list selfcolumnmean
# YOUR CODE HERE
raise NotImplementedError
return self
def transformself X:
Fills missing values in each feature with a corresponding mean value.
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:
if typeX is not npndarray:
Xi Xvalues: i
else:
Xi X: i
# Fill missing values using mean values
# YOUR CODE HERE
raise NotImplementedError
Xtransformed npcolumnstackXtransformed
return Xtransformed
# TEST MeanImputer class
A nparray
npnan,
npnan,
npnan, npnan
meanimp MeanImputer
meanimp.fitA
printmeanimp.columnmean
assert meanimp.columnmean "Computed mean values are incorrect."
meanimp.fitpdDataFrameA
Atransformed meanimp.transformpdDataFrameA
assert ~npisnanAtransformedany "Transformed feature matrix still contains NaNs."
assert npallcloseAtransformed,
"Filled values are incorrect."
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
