问题描述
我正在尝试在循环函数中应用索引来创建一个新的数据框,以基本上操纵交叉验证结果。我在实际使用这些索引应用于我的循环函数时遇到了问题。
错误发生在 RuntimeError: Given groups=1,weight of size [64,500,5],expected input[1,50,10] to have 500 channels,but got 50 channels instead
,这是我尝试为每个折叠提取索引的地方。 class Simple1DCNN5(torch.nn.Module):
def __init__(self):
super(Simple1DCNN5,self).__init__()
self.sequence = nn.Sequential(
torch.nn.Conv1d(in_channels=500,out_channels=64,kernel_size=1,stride=2),torch.nn.ReLU(),torch.nn.Conv1d(in_channels=64,out_channels=128,kernel_size=1),torch.nn.Conv1d(in_channels=128,out_channels=256,)
self.fc1 = nn.Linear(256,2)
def forward(self,x):
x = x.view(1,-1)
for layer in self.sequence:
x = layer(x)
#print(x.size())
x = x.view(1,-1)
#print(x.size())
x = self.fc1(x)
#print(x.size())
return x
应该代表折叠 1-5 的所有索引,但不是折叠 i。
创建数据框的可重现示例
oppo
在我的循环函数中,我想设置 i = 1:5,并为除 oppo
之外的所有内容获取 #data
attach(PimaIndiansDiabetes)
data=PimaIndiansDiabetes
#create training and testing sets
set.seed(101)
sample <- sample.int(n = nrow(data),size = floor(.7*nrow(data)),replace = F)
train <- data[sample,]
test <- data[-sample,]
#create simple RF
ctrl <- trainControl(method="cv",number=5,classprobs = TRUE,summaryFunction = twoClassSummary,savePredictions = TRUE)
rf_model <- train(diabetes ~.,data=train,metric="ROC",trControl=ctrl)
#reformat the dataframe of interest
cv_dataframe <- rf_model$pred %>% filter(mtry==2)
cv_dataframe$Resample <- sub("Fold","",cv_dataframe$Resample)
。所以对于下面的数据框,
rowIndex
在为 i
提取 head(cv_dataframe)
pred obs neg pos rowIndex mtry Resample
#1 neg neg 0.540 0.460 1 2 1
#2 neg pos 0.544 0.456 11 2 1
..
#3 neg neg 0.926 0.074 5 2 2
#4 pos neg 0.182 0.818 16 2 2
..
#5 neg neg 0.764 0.236 17 2 3
#6 neg neg 0.780 0.220 26 2 3
后,我想将 rowIndex
应用到 Resample==1
并获得 !rowIndex
的数据帧输出,但仅匹配 train
2 到 5 的索引。然后我想只预测 train
的 Resample
其中 train
。这是我尝试过的:
rowIndex
但我认为问题在于 Resample==1
,因为我不能将其用作索引列表。
解决方法
由于 oppo
是删除那些行索引的数字,我们必须使用 -
(!
用于反转逻辑值)。试试:
library(caret)
result <- lapply(unique(cv_dataframe$Resample),function(x) {
oppo <- cv_dataframe$rowIndex[cv_dataframe$Resample!=i]
as.data.frame(predict(rf_model,newdata = train[-oppo,],type = "prob"))
})