|
1 | | -# ============================================================================== |
2 | | -# Copyright contributors to the oneDAL project |
3 | | -# |
4 | | -# Licensed under the Apache License, Version 2.0 (the "License"); |
5 | | -# you may not use this file except in compliance with the License. |
6 | | -# You may obtain a copy of the License at |
7 | | -# |
8 | | -# http://www.apache.org/licenses/LICENSE-2.0 |
9 | | -# |
10 | | -# Unless required by applicable law or agreed to in writing, |
11 | | -# distributed under the License is distributed on an "AS IS" BASIS, |
12 | | -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | | -# See the License for the specific language governing permissions and |
14 | | -# limitations under the License. |
15 | | -# ============================================================================== |
16 | | - |
17 | 1 | import numpy as np |
| 2 | +from scipy import sparse |
| 3 | +from sklearn.metrics.pairwise import polynomial_kernel as sklearn_poly_kernel |
18 | 4 |
|
19 | 5 | from sklearnex.svm.poly_kernel import poly_kernel |
20 | 6 |
|
21 | 7 |
|
22 | | -def test_poly_kernel_basic(): |
| 8 | +def test_poly_kernel_dense(): |
| 9 | + """Test poly_kernel on dense input arrays.""" |
23 | 10 | X = np.array([[1, 2], [3, 4]]) |
24 | 11 | Y = np.array([[5, 6], [7, 8]]) |
25 | 12 |
|
26 | | - K = poly_kernel(X, Y, gamma=1.0, coef0=0.0, degree=2) |
| 13 | + result = poly_kernel(X, Y, degree=2, gamma=0.5, coef0=1) |
| 14 | + expected = sklearn_poly_kernel(X, Y, degree=2, gamma=0.5, coef0=1) |
27 | 15 |
|
28 | | - # expected polynomial kernel manually |
29 | | - expected = (np.dot(X, Y.T)) ** 2 |
30 | | - assert np.allclose(K, expected), "Polynomial kernel computation is incorrect" |
| 16 | + np.testing.assert_allclose(result, expected, rtol=1e-5, atol=1e-8) |
31 | 17 |
|
32 | 18 |
|
33 | | -def test_poly_kernel_default_Y(): |
34 | | - X = np.array([[1, 2], [3, 4]]) |
35 | | - K = poly_kernel(X) |
36 | | - expected = (np.dot(X, X.T)) ** 3 # default degree=3 |
37 | | - assert np.allclose(K, expected), "Polynomial kernel with Y=None is incorrect" |
| 19 | +def test_poly_kernel_sparse_fallback(): |
| 20 | + """Test that poly_kernel falls back to sklearn implementation for sparse inputs.""" |
| 21 | + X = sparse.csr_matrix([[1, 0], [0, 1]]) |
| 22 | + Y = sparse.csr_matrix([[0, 1], [1, 0]]) |
| 23 | + |
| 24 | + result = poly_kernel(X, Y, degree=3, gamma=1.0, coef0=1.0) |
| 25 | + expected = sklearn_poly_kernel(X, Y, degree=3, gamma=1.0, coef0=1.0) |
| 26 | + |
| 27 | + np.testing.assert_allclose(result, expected, rtol=1e-5, atol=1e-8) |
0 commit comments