python(5):TypeError: xxx() got an unexpected keyword argument ‘xxx‘

定义了一个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))

改后程序代码跑通:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值