类型错误:无法将 ufunc 'true_divide' 输出(类型代码 'd')强制转换为提供的输出参数(类型代码 'q')

Beg*_*Beg 12 python cluster-analysis spyder scikit-learn

我正在尝试将 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)
Run Code Online (Sandbox Code Playgroud)

执行此操作后,我收到以下错误:

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''
Run Code Online (Sandbox Code Playgroud)

我不明白它如何在仅具有较少特征(列)的同一数据集上给出此错误。有谁能认出原因吗?

Dan*_*Oak 11

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

a = np.array(..., dtype=float)
np.divide(a, b, out=np.zeros_like(a), where=(b!=0))
Run Code Online (Sandbox Code Playgroud)

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

如果dtypeofa是整数但为b浮点型,则得到的错误是:ufunc 'true_divide' 输出(类型代码 'd') 无法根据转换规则 ''same_kind'' 强制转换为提供的输出参数(类型代码 'l')


小智 5

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

cluster_data = cluster_data.astype(str)
cluster_data.dtypes.head()
Run Code Online (Sandbox Code Playgroud)

这似乎修复了错误。