我有以下python代码:
import numpy as np
import sklearn as sk
import pandas as pd
import scipy as sp
import matplotlib.pyplot as plt
import sys
from sklearn.decomposition import PCA
from sklearn.svm import OneClassSVM
np.random.seed(0)
x1 = np.random.normal((1,1), 0.1, (200, 2))
x2 = np.random.normal((1,0), .1, (200, 2))
x3 = np.random.normal((0,1), .1, (200, 2))
x4 = np.array([[0.5, 0.5],
[0.5, 1],
[1, 0.5]])
X = np.vstack([x1, x2, x3])#, x4])
X = sk.preprocessing.scale(X)
X_new = np.vstack([x1, x2, x3, x4])
X_new = sk.preprocessing.scale(X_new)
n, p = X_new.shape
anomaly_index = np.array(range(n-3, n))
normal_index = np.array(range(n-3))
#plt.scatter(X_new[normal_index,0], X_new[normal_index,1])
#plt.scatter(X_new[anomaly_index,0], X_new[anomaly_index,1], marker='*', c='r')
#plt.show()
gammas = [0.5]#, 0.7, 0.9]
nus = [0.01]#, 0.3, 0.8]
nrow = len(gammas)
ncol = len(nus)
j = 0
for gamma in gammas:
for nu in nus:
j += 1
svm = OneClassSVM(kernel='rbf', degree=2,
gamma=gamma, coef0=0.0,
tol=0.001,
nu=nu, shrinking=True,
cache_size=200,
verbose=False,
max_iter=-1, random_state=None)
svm.fit(X)
anomaly_score = - svm.decision_function(X_new)
vmin = anomaly_score.min()
vmax = anomaly_score.max()
xx1, yy1 = np.meshgrid(np.linspace(X_new[:,0].min()-0.3,
X_new[:,0].max()+0.3, 1000),
np.linspace(X_new[:,1].min()-0.3,
X_new[:,1].max()+0.3, 1000))
Z1 = svm.decision_function(np.c_[xx1.ravel(), yy1.ravel()])
Z1 = Z1.reshape(xx1.shape)
plt.subplot(nrow, ncol, j)
plt.title(r'$\gamma=$' + str(gamma) + r' $\nu=$' + str(nu) + '')
plt.scatter(X_new[normal_index, 0], X_new[normal_index, 1],
c=anomaly_score[normal_index], alpha=2, s=50,
vmin=vmin, vmax=vmax)
plt.scatter(X_new[anomaly_index, 0],
X_new[anomaly_index, 1], marker='*',
c=anomaly_score[anomaly_index], alpha=2, s=90,
vmin=vmin, vmax=vmax)
plt.colorbar()
#cb = plt.colorbar()
#tick_locator = ticker.MaxNLocator(nbins=5)
#cb.locator = tick_locator
#cb.update_ticks()
plt.contourf( xx1, yy1, Z1, cmap=plt.cm.Blues,
levels=np.linspace(Z1.min(), 0.3, 7), alpha=0.1)
plt.xlim(X_new[:,0].min()-0.3, X_new[:, 0].max()+0.3)
plt.ylim(X_new[:,1].min()-0.3, X_new[:, 1].max()+0.3)
plt.xlabel(r'$x_1$', size=20)
plt.ylabel(r'$x_2$', size=20)
plt.locator_params(nbins=4)
plt.tight_layout()
#plt.savefig('one_class_svm_3_clusters_grid.pdf')
plt.show()
这很好但是如果我取消注释plt.savefig我收到以下错误:
Process Python[/home/donbeo/Documents/pythoncode/fault_detection/one_class_svm/oc_svm_3_clusters.py] finished
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> >>> >>> >>> >>>
Process Python[/home/donbeo/Documents/pythoncode/fault_detection/one_class_svm/oc_svm_3_clusters.py] finished
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> >>> >>> >>> Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/matplotlib/colors.py", line 355, in to_rgba
'number in rbga sequence outside 0-1 range')
ValueError: number in rbga sequence outside 0-1 range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/donbeo/Documents/pythoncode/fault_detection/one_class_svm/oc_svm_3_clusters.py", line 98, in <module>
plt.savefig(plot_path + 'one_class_svm_3_clusters_grid.pdf')
File "/usr/local/lib/python3.4/dist-packages/matplotlib/pyplot.py", line 577, in savefig
res = fig.savefig(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/figure.py", line 1476, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_qt5agg.py", line 161, in print_figure
FigureCanvasAgg.print_figure(self, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backend_bases.py", line 2211, in print_figure
**kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_pdf.py", line 2485, in print_pdf
self.figure.draw(renderer)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/figure.py", line 1085, in draw
func(*args)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/axes/_base.py", line 2110, in draw
a.draw(renderer)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/collections.py", line 772, in draw
Collection.draw(self, renderer)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/collections.py", line 320, in draw
self._offset_position)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_pdf.py", line 1658, in draw_path_collection
antialiaseds, urls, offset_position):
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backend_bases.py", line 488, in _iter_collection
gc0.set_foreground(fg)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/backend_bases.py", line 1008, in set_foreground
self._rgb = colors.colorConverter.to_rgba(fg)
File "/usr/local/lib/python3.4/dist-packages/matplotlib/colors.py", line 376, in to_rgba
'to_rgba: Invalid rgba arg "%s"\n%s' % (str(arg), exc))
ValueError: to_rgba: Invalid rgba arg "[ 0. 0. 0. 2.]"
number in rbga sequence outside 0-1 range
>>>
答案 0 :(得分:2)
查看错误消息,它会告诉您出了什么问题。回溯的最后一行显示rgba颜色的alpha(第四个值)设置为2,而它应该介于0和1之间。
作为一个小例子,
x1 = np.random.normal((1,1), 0.1, (200, 2))
plt.scatter(x1[:,0], x1[:,1], alpha=2)
plt.show()
会给出相同的错误消息。只需将您的alpha值替换为0到1之间的数字,错误就会消失:
x1 = np.random.normal((1,1), 0.1, (200, 2))
plt.scatter(x1[:,0], x1[:,1], alpha=0.5)
plt.show()
在您的代码中,更改以下行中的Alpha值。在这里,我将其替换为0.5,但只要介于0和1之间,您就可以选择所需的内容。
plt.scatter(X_new[normal_index, 0], X_new[normal_index, 1],
c=anomaly_score[normal_index], alpha=0.5, s=50,
vmin=vmin, vmax=vmax)
plt.scatter(X_new[anomaly_index, 0],
X_new[anomaly_index, 1], marker='*',
c=anomaly_score[anomaly_index], alpha=0.5, s=90,
vmin=vmin, vmax=vmax)