修正下列代码def rule_evaluation(self, x): rule_out = np.zeros((x.shape[0], self.n_mf ** self.n_input)) for i in range(x.shape[0]): rule = np.zeros((self.n_mf, self.n_input)) for j in range(self.n_input): rule[:, j] = self.membership_function(x[i, j], self.mf_params[j, :]) rule = np.meshgrid(*rule) rule = np.stack(rule, axis=-1) rule = rule.reshape((-1, self.n_input)) rule_out[i, :] = np.min(rule, axis=1) return rule_out
时间: 2024-02-16 13:04:51 浏览: 88
代码中的问题是:self.membership_function()是类的一个方法,不能直接在numba中使用,需要将其转换为一个独立的函数。
修正后的代码如下:
```
import numba as nb
@nb.njit
def membership_function(x, mf_params):
n_mf = mf_params.shape[0]
mf = np.zeros((n_mf,))
for i in range(n_mf):
if mf_params[i, 0] == 0:
if x == mf_params[i, 1]:
mf[i] = 1
else:
mf[i] = 0
elif mf_params[i, 0] == 1:
mf[i] = np.exp(-0.5 * ((x - mf_params[i, 1]) / mf_params[i, 2]) ** 2)
elif mf_params[i, 0] == 2:
if x <= mf_params[i, 1]:
mf[i] = 1
elif x >= mf_params[i, 2]:
mf[i] = 0
else:
mf[i] = (mf_params[i, 2] - x) / (mf_params[i, 2] - mf_params[i, 1])
return mf
@nb.njit(parallel=True)
def rule_evaluation(x, n_mf, n_input, mf_params):
rule_out = np.zeros((x.shape[0], n_mf ** n_input))
for i in nb.prange(x.shape[0]):
rule = np.zeros((n_mf, n_input))
for j in range(n_input):
rule[:, j] = membership_function(x[i, j], mf_params[j, :])
rule = np.meshgrid(*rule)
rule = np.stack(rule, axis=-1)
rule = rule.reshape((-1, n_input))
rule_out[i, :] = np.min(rule, axis=1)
return rule_out
```
这里将self.membership_function()转换为了一个独立的函数membership_function(),并在numba中进行了修饰,同时使用了并行计算,可以大大加速代码运行。
阅读全文