Numpy 类型错误:ufunc';减去';未包含具有签名匹配类型dtype(';<;U1';)dtype(';<;U1';)dtype(';<;U1';)的循环

Numpy 类型错误:ufunc';减去';未包含具有签名匹配类型dtype(';<;U1';)dtype(';<;U1';)dtype(';<;U1';)的循环,numpy,matplotlib,python-unicode,Numpy,Matplotlib,Python Unicode,试图获取一个小玩具数据集的直方图时,numpy通过matplotlib出现了一个奇怪的错误。我只是不知道如何解释这个错误,这使得我很难看到下一步该怎么做 没有发现太多的相关,虽然和表面上相似 我希望底部的调试信息比驱动程序代码更有用,但是如果我遗漏了什么,请询问。作为现有测试套件的一部分,这是可复制的 if n > 1: return diff(a[slice1]-a[slice2], n-1, axis=axis) else: &g

试图获取一个小玩具数据集的直方图时,numpy通过matplotlib出现了一个奇怪的错误。我只是不知道如何解释这个错误,这使得我很难看到下一步该怎么做

没有发现太多的相关,虽然和表面上相似

我希望底部的调试信息比驱动程序代码更有用,但是如果我遗漏了什么,请询问。作为现有测试套件的一部分,这是可复制的

        if n > 1:
            return diff(a[slice1]-a[slice2], n-1, axis=axis)
        else:
>           return a[slice1]-a[slice2]
E           TypeError: ufunc 'subtract' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')

../py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py:1567: TypeError
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> entering PDB >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(1567)diff()
-> return a[slice1]-a[slice2]
(Pdb) bt
[...]
py2.7.11-venv/lib/python2.7/site-packages/matplotlib/axes/_axes.py(5678)hist()
-> m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
  py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(606)histogram()
-> if (np.diff(bins) < 0).any():
> py2.7.11-venv/lib/python2.7/site-packages/numpy/lib/function_base.py(1567)diff()
-> return a[slice1]-a[slice2]
(Pdb) p numpy.__version__
'1.11.0'
(Pdb) p matplotlib.__version__
'1.4.3'
(Pdb) a
a = [u'A' u'B' u'C' u'D' u'E']
n = 1
axis = -1
(Pdb) p slice1
(slice(1, None, None),)
(Pdb) p slice2
(slice(None, -1, None),)
(Pdb)
如果n>1:
返回差异(a[slice1]-a[slice2],n-1,轴=轴)
其他:
>返回[slice1]-a[slice2]

E TypeError:ufunc“subtract”不包含签名类型与dtype匹配的循环(“为什么要将
diff
应用于字符串数组

我在同一点上得到了一个错误,尽管消息不同

In [23]: a=np.array([u'A' u'B' u'C' u'D' u'E'])

In [24]: np.diff(a)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-9d5a62fc3ff0> in <module>()
----> 1 np.diff(a)

C:\Users\paul\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\lib\function_base.pyc in diff(a, n, axis)
   1112         return diff(a[slice1]-a[slice2], n-1, axis=axis)
   1113     else:
-> 1114         return a[slice1]-a[slice2]
   1115 
   1116 

TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'numpy.ndarray' 
[23]中的
a=np.array([u'a'u'B'u'C'u'D'u'E'))
In[24]:np.diff(a)
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在()
---->1 np.差异(a)
C:\Users\paul\AppData\Local\enthught\Canopy\User\lib\site packages\numpy\lib\function\u base.pyc,以不同的(a、n、axis)表示
1112返回差异(a[slice1]-a[slice2],n-1,轴=轴)
1113其他:
->1114返回一个[slice1]-一个[slice2]
1115
1116
TypeError:-:'numpy.ndarray'和'numpy.ndarray'的操作数类型不受支持

这是
a
数组的
bins
参数吗?文档中说
bins
应该是什么?

我自己对这一点很陌生,但我也有一个类似的错误,发现这是由于类型转换问题。我试图连接而不是接受差异,但我认为这里的原则是相同的。我提供了一个另一个类似的答案,所以我希望这是好的

本质上,您需要使用不同的数据类型转换,在我的情况下,我需要str not float,我怀疑您的是相同的,所以我建议的解决方案是。很抱歉,我无法在建议之前对其进行测试,但从您的示例中,我不清楚您在做什么

return diff(str(a[slice1])-str(a[slice2]), n-1, axis=axis)
请参阅下面的示例代码,了解对代码的修复,更改发生在第三行到最后一行。代码将生成一个基本的随机林模型

import scipy
import math
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn import preprocessing, metrics, cross_validation

Data = pd.read_csv("Free_Energy_exp.csv", sep=",")
Data = Data.fillna(Data.mean()) # replace the NA values with the mean of the descriptor
header = Data.columns.values # Ues the column headers as the descriptor labels
Data.head()
test_name = "Test.csv"

npArray = np.array(Data)
print header.shape
npheader = np.array(header[1:-1])
print("Array shape X = %d, Y = %d " % (npArray.shape))
datax, datay =  npArray.shape

names = npArray[:,0]
X = npArray[:,1:-1].astype(float)
y = npArray[:,-1] .astype(float)
X = preprocessing.scale(X)

XTrain, XTest, yTrain, yTest = cross_validation.train_test_split(X,y, random_state=0)

# Predictions results initialised 
RFpredictions = []
RF = RandomForestRegressor(n_estimators = 10, max_features = 5, max_depth = 5, random_state=0)
RF.fit(XTrain, yTrain)       # Train the model
print("Training R2 = %5.2f" % RF.score(XTrain,yTrain))
RFpreds = RF.predict(XTest)

with open(test_name,'a') as fpred :
    lenpredictions = len(RFpreds)
    lentrue = yTest.shape[0]
    if lenpredictions == lentrue :
            fpred.write("Names/Label,, Prediction Random Forest,, True Value,\n")
            for i in range(0,lenpredictions) :
                    fpred.write(RFpreds[i]+",,"+yTest[i]+",\n")
    else :
            print "ERROR - names, prediction and true value array size mismatch."
这会导致错误的

Traceback (most recent call last):
  File "min_example.py", line 40, in <module>
    fpred.write(RFpreds[i]+",,"+yTest[i]+",\n")
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')

这些示例来自更大的代码,因此我希望示例足够清晰。

我遇到了一个类似的问题,我迭代的数据帧中的一行整数的类型为
numpy.int64
。我得到了


TypeError:ufunc'subtract'不包含签名匹配类型为dtype的循环(“我得到了相同的错误,但在我的例子中,我从dict.value中减去dict.key。我已通过从其他dict.value中减去相应key的dict.value来修复此问题

cosine_sim = cosine_similarity(e_b-e_a, w-e_c)
这里我得到了一个错误,因为e_b,e_a和e_c分别是单词a,b,c的嵌入向量。我不知道“w”是字符串,当我找到w是字符串时,我通过以下行修复了这个问题:

cosine_sim = cosine_similarity(e_b-e_a, word_to_vec_map[w]-e_c)

现在我没有减去dict.key,而是减去了key的相应值,我认为@James是对的。我在处理Polyval()时遇到了相同的错误。是的,解决方法是使用相同类型的变量。您可以使用typecast将所有变量转换为同一类型

下面是一个示例代码

import numpy
P = numpy.array(input().split(), float)
x = float(input())
print(numpy.polyval(P,x))

这里我使用float作为输出类型,所以即使用户输入INT值(整数)。最终答案将被打印为浮动。

啊,很有趣!我试图创建一个带有分类箱的直方图,这意味着我想要的根本不是直方图,而是条形图。谢谢!你有没有可能在答案中显示一些代码?答案下面是一个编辑按钮。这些信息属于答案,而不是cAndrew Ng的Coursera DL课程中的omment.同学就在这里:)ThanksI遇到了类似的错误,因为我也从0.00中减去了0.0。
pd。对于数值(数据帧)
它解决了我的问题。我在脚本中遇到了同样的问题,因为
numpy
模块没有导入。会是这种情况吗?
import numpy
P = numpy.array(input().split(), float)
x = float(input())
print(numpy.polyval(P,x))