2017-07-30 30 views
-1

使用下面的代码生成错误:类型错误:浮置()参数必须是一个字符串或数字,而不是“强的松”:的Python 3.5想要绘制PCA与sklearn和matplotlib

我竭力要弄清楚是什么导致这个错误被抛出。

self.features是一个由三个浮点数组成的列表ex。 [1.1,1.2,1.3] self.features的示例:

[array([-1.67191985, 0.1  , 9.69981494]), array([-0.68486623, 0.05  , 9.99085024]), array([ -1.36  , 0.1  , 10.44720459]), array([-2.46918915, 0.  , 3.5483372 ]), array([-0.835  , 0.1  , 4.02740479])] 

在这里被抛出的错误的方法。

def pca(self):   
    pca = PCA(n_components=2) 
    x_np = np.asarray(self.features) 
    pca.fit(x_np) 
    X_reduced = pca.transform(x_np) 
    plt.figure(figsize=(10, 8)) 
    plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='RdBu') 
    plt.xlabel('First component') 
    plt.ylabel('Second component') 

完整的追溯是:

Traceback (most recent call last): 
    File "/Users/user/PycharmProjects/Post-Translational-Modification-     
Prediction/pred.py", line 244, in <module> 
y.generate_pca() 
    File "/Users/user/PycharmProjects/Post-Translational-Modification- 
Prediction/pred.py", line 222, in generate_pca 
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='RdBu') 
File "/usr/local/lib/python3.5/site-packages/matplotlib/pyplot.py", 
line 3435, in scatter 
edgecolors=edgecolors, data=data, **kwargs) 
File "/usr/local/lib/python3.5/site-packages/matplotlib/__init__.py", 
line 1892, in inner 
return func(ax, *args, **kwargs) 
File "/usr/local/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 3976, in scatter 
c_array = np.asanyarray(c, dtype=float) 
File "/usr/local/lib/python3.5/site-packages/numpy/core/numeric.py", line 583, in asanyarray 
return array(a, dtype, copy=False, order=order, subok=True) 
TypeError: float() argument must be a string or a number, not 'Pred' 
+0

你能否发布整个错误信息?这是所有的代码还是有更多? – 2Obe

+0

你能不能也发布几行self.features? – Linda

+0

@ 2Obe增加了完整的回溯,有更多的代码,但约200行。但是,我不认为这是造成错误的原因。 谢谢! – vzg100

回答

0

通过@WhoIsJack建议的解决方法是增加np.arange(len(self.features))

对于那些谁遇到类似问题的功能代码:

def generate_pca(self): 
    y= np.arange(len(self.features)) 
    pca = PCA(n_components=2) 
    x_np = np.asarray(self.features) 
    pca.fit(x_np) 
    X_reduced = pca.transform(x_np) 
    plt.figure(figsize=(10, 8)) 
    plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='RdBu') 
    plt.xlabel('First component') 
    plt.ylabel('Second component') 
    plt.show()