TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'q')

TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'q')

我正在尝试将 Gower 距离实现应用于我的数据框。虽然它可以顺利地处理具有更多特征的相同数据集,但这次当我调用 Gower 距离函数时它会出错。我从同一目录中的另一个 .py 代码导入 Gower 函数。这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

import gower_function as gf

# Importing the dataset with pandas
dataset = pd.read_excel('input_partial.xlsx')
X = dataset.iloc[:, 1:].values
df = pd.DataFrame(X)
#obtaining gower distances of instances
Gower = gf.gower_distances(X)

执行此操作后,出现以下错误:

File "<ipython-input-10-6a4c39600b0e>", line 1, in <module>
Gower = gf.gower_distances(X)

File "C:\Users\...\Clustering\Section 24 - K-Means 
Clustering\gower_function.py", line 184, in gower_distances
X_num = np.divide(X_num ,max_of_numeric,out=np.zeros_like(X_num), 
where=max_of_numeric!=0)

TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to 
provided output parameter (typecode 'q') according to the casting rule 
''same_kind''

我不明白它如何在具有更少特征(列)的同一数据集上给出此错误。有大神知道原因吗?

您需要指定左操作数的dtype为非整数,一些浮点类型,例如

a = np.array ( ... , dtype = float )
np.divide ( a , b , out = np.zeros_like ( a ) , where = b != 0)

如果 abdtype 都是整数,那么您得到的错误是:没有找到匹配指定签名和转换的循环ufunc true_divide.

如果 adtype 是整数,但 b - 浮点数,那么你得到的错误是: ufunc 'true_divide' output (typecode 'd') 无法根据转换规则“'same_kind'”.

强制提供输出参数(类型代码 'l')

我遇到了同样的问题。似乎如果您的所有变量都是整数,则会产生此错误。所以我将每个整数列更改为字符串值。

cluster_data = cluster_data.astype(str)
cluster_data.dtypes.head()

这似乎修复了错误。