Skip to content

Commit d4ea86b

Browse files
committed
Address third round of code review feedback
- Rename test to test_normalize_near_zero_vector_normalizes_correctly - Simplify singular value sqrt to [val, 0.0].max for uniform handling - Preserve sign relationship in content_node divisor fallback
1 parent d429340 commit d4ea86b

File tree

3 files changed

+9
-4
lines changed

3 files changed

+9
-4
lines changed

lib/classifier/extensions/vector.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def SV_decomp(max_sweeps = 20)
102102
q_rotation_matrix.row_size.times do |r|
103103
# Guard against negative values due to floating point errors
104104
val = q_rotation_matrix[r, r].to_f
105-
singular_values << Math.sqrt(val < -Vector::EPSILON ? 0.0 : val.abs)
105+
singular_values << Math.sqrt([val, 0.0].max)
106106
end
107107

108108
# Replace near-zero singular values with EPSILON to prevent division by zero

lib/classifier/lsi/content_node.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,13 @@ def raw_vector_with(word_list)
6161
weighted_total += val unless val.nan?
6262
end
6363

64-
# Guard against division by zero - use small epsilon if weighted_total is zero
65-
divisor = weighted_total.abs < Vector::EPSILON ? -Vector::EPSILON : -weighted_total
64+
# Guard against division by zero - use small epsilon if weighted_total is near zero,
65+
# while preserving the sign relationship with -weighted_total.
66+
divisor = if weighted_total.abs < Vector::EPSILON
67+
weighted_total.negative? ? Vector::EPSILON : -Vector::EPSILON
68+
else
69+
-weighted_total
70+
end
6671
vec = vec.collect { |val| Math.log(val + 1) / divisor }
6772
end
6873

test/extensions/word_hash_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def test_normalize_zero_vector_returns_zero_vector
125125
assert_in_delta 0.0, normalized[2], 0.001
126126
end
127127

128-
def test_normalize_near_zero_vector_returns_unit_vector
128+
def test_normalize_near_zero_vector_normalizes_correctly
129129
# Near-zero vectors should still normalize to unit vectors
130130
# Only actual zero vectors return zero
131131
vec = Vector[1e-15, 1e-15, 1e-15]

0 commit comments

Comments
 (0)