【问题标题】:AttributeError: 'numpy.ndarray' object has no attribute 'iloc'AttributeError:“numpy.ndarray”对象没有属性“iloc”
【发布时间】:2019-04-10 12:38:36
【问题描述】:

我正在尝试结合使用堆叠的两种机器学习算法来获得更好的结果,但在某些方面失败了。 这是我的代码:

类合奏(threading.Thread): “堆叠三个分类模型以提高预测的准确性” def init(self, X, Y, XT, YT, accLabel=None): threading.Thread.init(self) 自我.X = X 自我.Y = Y 自我.XT=XT 自我.YT=YT self.accLabel=accLabel

def Stacking(self,model,n_fold,train,test,y):

    folds=StratifiedKFold(n_splits=n_fold,random_state=1)
    test_pred=np.empty((test.shape[0],1),float)
    train_pred=np.empty((0,1),float)
    for train_indices,val_indices in folds.split(train,y):
        x_train,x_val=train.iloc[train_indices],train.iloc[val_indices]
        y_train,y_val=y.iloc[train_indices],y.iloc[val_indices]

        model.fit(X=x_train,y=y_train)
        train_pred=np.append(train_pred,model.predict(x_val))
        test_pred=np.append(test_pred,model.predict(test))
    return test_pred.reshape(-1,1),train_pred   

def run(self):
    X = np.zeros(self.X.shape)
    Y = np.zeros(self.Y.shape)
    XT = np.zeros(self.XT.shape)
    YT = np.zeros(self.YT.shape)
    np.copyto(X, self.X)
    np.copyto(Y, self.Y)
    np.copyto(XT, self.XT)
    np.copyto(YT, self.YT)

    model1 = tree.DecisionTreeClassifier(random_state=1)
    n_fold=4
    test_pred1 ,train_pred1=self.Stacking(model1, n_fold, X, XT, Y)
    train_pred1=pd.DataFrame(train_pred1)
    test_pred1=pd.DataFrame(test_pred1)

    model2 = KNeighborsClassifier()
    test_pred2 ,train_pred2=self.Stacking(model2, n_fold, X, XT, Y)
    train_pred2=pd.DataFrame(train_pred2)
    test_pred2=pd.DataFrame(test_pred2)

    df = pd.concat([train_pred1, train_pred2], axis=1)
    df_test = pd.concat([test_pred1, test_pred2], axis=1)
    model = LogisticRegression(random_state=1)
    model.fit(df,Y)
    sd = model.score(df_test, YT)
    acc = (sum(sd == YT) / len(YT) * 100)
    print("Accuracy of Ensemble Learning Model is : %.2f" % acc+' %')
    print('=' * 100)
    if self.accLabel: self.accLabel.set("Accuracy of Ensembelance Learning: %.2f" % (acc)+' %')

错误出现在 Stacking 方法中的 'iloc' 中。

我一直收到 np.ndarray has no attribute 'iloc' 的错误。我尝试搜索但找不到任何特定链接,尽管我认为这与属于 np.ndarray 的 iloc 有关。 如果有人可以帮我解决这个问题!

【问题讨论】:

  • .iloc 是 Pandas 数据框方法。当您将 XY 传递给 Stacking() 时,它们都只是 numpy 数组,因此您不能在它们上调用 iloc
  • ilocpandas 数据框属性。在numpy 中没有任何意义。当您收到AttributeError 时,不要只是继续尝试。检查对象的type,并检查其文档。那个时候的对象很可能不是你想要的。

标签: pandas numpy


【解决方案1】:

正如 cmets 所建议的,.iloc 是 Pandas 数据框方法。

要过滤一个 numpy 数组,您只需要:array[indices]

在你的情况下:

x_train,x_val=train[train_indices],train[val_indices]
y_train,y_val=y[train_indices],y[val_indices]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2020-12-03
    • 2020-11-29
    • 2020-10-06
    • 2018-01-25
    • 2016-06-29
    • 2020-03-25
    相关资源
    最近更新 更多