From 44fec9ee8bc8bcf7973d35e47139990654bda199 Mon Sep 17 00:00:00 2001 From: Atharva Khare Date: Wed, 29 May 2019 19:51:38 +0530 Subject: [PATCH] Fixed ZeroDivideError in PMStandardizationScaler This happened when one of the input features was constant. - Set scale to 1 for the feature which is constant - Added two tests for this case --- .../PMStandardizationScaler.class.st | 6 +++++- .../PMStandardizationScalerTest.class.st | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Math-PrincipalComponentAnalysis/PMStandardizationScaler.class.st b/src/Math-PrincipalComponentAnalysis/PMStandardizationScaler.class.st index 51cfa51f4..78241d614 100644 --- a/src/Math-PrincipalComponentAnalysis/PMStandardizationScaler.class.st +++ b/src/Math-PrincipalComponentAnalysis/PMStandardizationScaler.class.st @@ -22,7 +22,11 @@ PMStandardizationScaler >> mean [ { #category : #accessing } PMStandardizationScaler >> scale [ - ^ self variance sqrt + ^ self variance collect: [ :element | + | root | + root := element sqrt. + (root ~= 0) ifTrue: [ root ] ifFalse: [ 1.0 ] + ] ] { #category : #transforming } diff --git a/src/Math-Tests-PrincipalComponentAnalysis/PMStandardizationScalerTest.class.st b/src/Math-Tests-PrincipalComponentAnalysis/PMStandardizationScalerTest.class.st index 0f7e56d36..03c4a34fa 100644 --- a/src/Math-Tests-PrincipalComponentAnalysis/PMStandardizationScalerTest.class.st +++ b/src/Math-Tests-PrincipalComponentAnalysis/PMStandardizationScalerTest.class.st @@ -40,6 +40,14 @@ PMStandardizationScalerTest >> testTransformAnotherMatrix [ self assert: (t transform: anotherMatrix) equals: (PMMatrix rows: #(#(3 3))) ] +{ #category : #tests } +PMStandardizationScalerTest >> testTransformConstantFeature [ + | aMatrix t | + aMatrix := PMMatrix rows: #(#(8.0 0.0) #(8.0 0.0) #(8.0 1.0) #(8.0 1.0)). + t := PMStandardizationScaler new. + self assert: (t fitAndTransform: aMatrix) equals: (PMMatrix rows: #(#(0.0 -1.0) #(0.0 -1.0) #(0.0 1.0) #(0.0 1.0))) +] + { #category : #tests } PMStandardizationScalerTest >> testVariance [ | aMatrix t | @@ -48,3 +56,15 @@ PMStandardizationScalerTest >> testVariance [ t fit: aMatrix. self assert: t variance asArray closeTo: #(0.25 0.25) ] + +{ #category : #tests } +PMStandardizationScalerTest >> testZeroScale [ + "Tests if PMStandardizationScaler handles case when scale is 0, by changing it to 1. + Happens when one feature is constant eg: 8.0 in this test." + + | aMatrix t | + aMatrix := PMMatrix rows: #((8.0 0.0) #(8.0 0.0) #(8.0 1.0) #(8.0 1.0)). + t := PMStandardizationScaler new. + t fit: aMatrix. + self assert: t scale asArray closeTo: #(1.0 0.5) +]