【问题标题】:SVM a dataframe based on the last columnSVM 基于最后一列的数据框
【发布时间】:2017-08-13 22:02:33
【问题描述】:

我一直在尝试根据最后一个类名来支持数据帧。

我有这个数据框

#FIll the data frame
df = read.table("https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data",
               sep=",",
               col.names=c("buying", "maint", "doors", "persons", "lug_boot", "safety", ""),
               fill=TRUE,
               strip.white=TRUE)

lastColName <- colnames(df)[ncol(df)]

...

model <- svm(lastColName~.,
             data = df,
             kernel="polynomial",
             degree = degree,
             type = "C-classification",
             cost = cost)

我收到的是 NULLError in model.frame.default(formula = str(lastColName) ~ ., data = df1, : invalid type (NULL) for variable 'str(lastColName)'。我知道NULL 在列没有名称时到达。我不明白另一个错误,因为它是最后一列名称..

有什么想法吗?

【问题讨论】:

    标签: r dataframe svm


    【解决方案1】:

    当您尝试在公式中使用动态变量时,您必须使用as.formula。详情见?as.formula

    以下代码可以正常工作:

    library(e1071)
    df_1 = read.table("https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data",
                    sep=",",
                    col.names=c("buying", "maint", "doors", "persons", "lug_boot", "safety", ""),
                    fill=TRUE,
                    strip.white=TRUE)
    
    lastColName <- colnames(df_1)[ncol(df_1)]
    
    model <- svm(as.formula(paste(lastColName, "~ .", sep = " ")),
                 data = df_1,
                 kernel="polynomial",
                 degree = 3,
                 type = "C-classification",
                 cost = 1)
    # to predict on the data remove the last column 
    prediction <- predict(model, df_1[,-ncol(df_1)])
    
    # The output
    table(prediction)
    
    # The output is:
    
    prediction
    acc  good unacc  vgood 
    0     0    1728     0 
    
    # Since this is a highly unbalanced classification the model is not doing a very good job
    

    【讨论】:

    • 哇,谢谢!但是,预测失败了,因为参数的长度不同。我使用了你的方法 => table(predict(model), as.formula(paste(lastColName, "~ .", sep = " ")), dnn=c("Prediction", "Actual"))
    • 更新了从模型中预测的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多