定义了一个python函数,调用时出现报错如下:

Traceback (most recent call last):
  File "gaussian_kernel.py", line 18, in <module>
    print(gaussian_kernel_vectorization(x, x, l=500, sigma=10))
TypeError: gaussian_kernel_vectorization() got an unexpected keyword argument 'sigma'

原因是:函数参数传递出错,gaussian_kernel_vectorization()函数定义的参数名sigma_f和调用gaussian_kernel_vectorization()函数传递的参数名sigma不一致。(注:c++里面传递函数参数时不需要考虑参数名称,但需要保持参数类型一致或者参数类型可以传递)

代码如下:

# -*- coding:utf-8 -*-
import numpy as np

def gaussian_kernel(x1, x2, l=1.0, sigma_f=1.0):
    """Easy to understand but inefficient."""
    m, n = x1.shape[0], x2.shape[0]
    dist_matrix = np.zeros((m, n), dtype=float)
    for i in range(m):
        for j in range(n):
            dist_matrix[i][j] = np.sum((x1[i] - x2[j]) ** 2)
    return sigma_f ** 2 * np.exp(- 0.5 / l ** 2 * dist_matrix)

def gaussian_kernel_vectorization(x1, x2, l=1.0, sigma_f=1.0):
    """More efficient approach."""
    dist_matrix = np.sum(x1**2, 1).reshape(-1, 1) + np.sum(x2**2, 1) - 2 * np.dot(x1, x2.T)
    return sigma_f ** 2 * np.exp(-0.5 / l ** 2 * dist_matrix)

x = np.array([700, 800, 1029]).reshape(-1, 1)
print(x)
# print(gaussian_kernel_vectorization(x, x, l=500, sigma=10))#改前
print(gaussian_kernel_vectorization(x, x, l=500, sigma_f=10))

改后程序代码跑通:

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐