【问题标题】:ValueError: Found input variables with inconsistent numbers of samples: [143, 426]ValueError:发现样本数量不一致的输入变量:[143, 426]
【发布时间】:2021-08-06 00:02:02
【问题描述】:

如何解决它引发的这个错误? ValueError: 发现样本数量不一致的输入变量:[143, 426]

#split the data set into independent (X) and dependent (Y) data sets
X = df.iloc[:,2:31].values
Y = df.iloc[:,1].values

#split the data qet into 75% training and 25% testing
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)

#scale the data (feature scaling)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_train = sc.fit_transform(X_test)

#Using Logistic Regression Algorithm to the Training Set

classifier = LogisticRegression(random_state = 0)
classifier.fit(X_train, Y_train)

以及X_train、Y_train的形状:

X_train.shape
(143, 29)
Y_train.shape
(426,)

错误信息: ValueError Traceback(最近一次调用最后一次) 在 () 2 3 分类器 = LogisticRegression(random_state = 0) ----> 4 分类器.fit(X_train, Y_train) 5 #Using KNeighborsClassifier 邻居类的方法使用Nearest Neighbor算法 6

2 帧 /usr/local/lib/python3.7/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays) 210 如果 len(uniques) > 1: 211 raise ValueError("发现输入变量的数量不一致" --> 212 " 样本: %r" % [int(l) for l in lengths]) 213 214

ValueError: 发现样本数量不一致的输入变量:[143, 426]

【问题讨论】:

    标签: python machine-learning neural-network data-science


    【解决方案1】:

    您在第 11 行有一个错误,您将分配给 X_train 而不是 X_test。看看下面更正后的代码。

    #split the data set into independent (X) and dependent (Y) data sets
    X = df.iloc[:,2:31].values
    Y = df.iloc[:,1].values
    
    #split the data qet into 75% training and 25% testing
    X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
    
    #scale the data (feature scaling)
    sc = StandardScaler()
    X_train = sc.fit_transform(X_train)
    X_test = sc.transform(X_test)
    
    #Using Logistic Regression Algorithm to the Training Set
    
    classifier = LogisticRegression(random_state = 0)
    classifier.fit(X_train, Y_train)
    

    也不要在 X_test 上使用 fit_transform。您希望使用与 X_train 中计算的相同的均值和标准差。

    【讨论】:

    • 感谢纠正 X_train 中的问题,Y_train 在行 [143, 426] 中不相等我认为我对此很陌生,我知道如何纠正它
    • 如果这回答了您的问题,请检查答案左侧的勾号:)
    • @AcilFarhat X_train 和 Y_train 中的样本数必须相等。也就是说,X_train.shape[0] == Y_train.shape[0]。确保 X_train 和 Y_train 中的数据点数量完全相同。
    猜你喜欢
    • 2021-06-20
    • 2018-06-25
    • 2018-12-04
    • 2021-05-31
    • 2020-08-19
    • 2021-09-12
    • 2020-06-07
    • 2022-01-16
    • 2022-01-11
    相关资源
    最近更新 更多