[英]weird svm behavior in R (e1071)
我在 R(第一個示例)和 Python(第二個示例)中使用 SVM 為二進制分類任務運行了以下代碼。
給定隨機生成的數據(X)
和響應(Y)
,此代碼執行 1000 次離開組交叉驗證。 因此, Y
每個條目都是跨 CV 迭代的預測平均值。
曲線下的計算面積應為 ~0.5,因為X
和Y
是完全隨機的。 然而,這並不是我們所看到的。 曲線下面積經常顯着高於 0.5。 X
的行數非常少,這顯然會導致問題。
知道這里會發生什么嗎? 我知道我可以增加X
的行數或減少列數來解決問題,但我正在尋找其他問題。
Y=as.factor(rep(c(1,2), times=14))
X=matrix(runif(length(Y)*100), nrow=length(Y))
library(e1071)
library(pROC)
colnames(X)=1:ncol(X)
iter=1000
ansMat=matrix(NA,length(Y),iter)
for(i in seq(iter)){
#get train
train=sample(seq(length(Y)),0.5*length(Y))
if(min(table(Y[train]))==0)
next
#test from train
test=seq(length(Y))[-train]
#train model
XX=X[train,]
YY=Y[train]
mod=svm(XX,YY,probability=FALSE)
XXX=X[test,]
predVec=predict(mod,XXX)
RFans=attr(predVec,'decision.values')
ansMat[test,i]=as.numeric(predVec)
}
ans=rowMeans(ansMat,na.rm=TRUE)
r=roc(Y,ans)$auc
print(r)
同樣,當我在 Python 中實現同樣的事情時,我得到了類似的結果。
Y = np.array([1, 2]*14)
X = np.random.uniform(size=[len(Y), 100])
n_iter = 1000
ansMat = np.full((len(Y), n_iter), np.nan)
for i in range(n_iter):
# Get train/test index
train = np.random.choice(range(len(Y)), size=int(0.5*len(Y)), replace=False, p=None)
if len(np.unique(Y)) == 1:
continue
test = np.array([i for i in range(len(Y)) if i not in train])
# train model
mod = SVC(probability=False)
mod.fit(X=X[train, :], y=Y[train])
# predict and collect answer
ansMat[test, i] = mod.predict(X[test, :])
ans = np.nanmean(ansMat, axis=1)
fpr, tpr, thresholds = roc_curve(Y, ans, pos_label=1)
print(auc(fpr, tpr))`
您應該將交叉驗證的每次迭代視為一個獨立的實驗,您使用訓練集進行訓練,使用測試集進行測試,然后計算模型技能分數(在本例中為 AUC)。
所以你實際上應該做的是計算每次 CV 迭代的 AUC。 然后取 AUC 的平均值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.