Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

python - TypeError: cannot perform reduce with flexible type

I have been using the scikit-learn library. I'm trying to use the Gaussian Naive Bayes Module under the scikit-learn library but I'm running into the following error. TypeError: cannot perform reduce with flexible type

Below is the code snippet.

training = GaussianNB()
training = training.fit(trainData, target)
prediction = training.predict(testData)

This is target

['ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'ALL', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML', 'AML']

This is trainData

[['-214' '-153' '-58' ..., '36' '191' '-37']
['-139' '-73' '-1' ..., '11' '76' '-14']
['-76' '-49' '-307' ..., '41' '228' '-41']
..., 
['-32' '-49' '49' ..., '-26' '133' '-32']
['-124' '-79' '-37' ..., '39' '298' '-3']
['-135' '-186' '-70' ..., '-12' '790' '-10']]

Below is the stack trace

Traceback (most recent call last):
File "prediction.py", line 90, in <module>
  gaussianNaiveBayes()
File "prediction.py", line 76, in gaussianNaiveBayes
  training = training.fit(trainData, target)
File "/Library/Python/2.7/site-packages/sklearn/naive_bayes.py", line 163, in fit
  self.theta_[i, :] = np.mean(Xi, axis=0)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/ core/fromnumeric.py", line 2716, in mean
  out=out, keepdims=keepdims)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/_methods.py", line 62, in _mean
  ret = um.add.reduce(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
TypeError: cannot perform reduce with flexible type
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...