【问题标题】:What does inconsistent number of samples mean?样本数不一致是什么意思?
【发布时间】:2019-06-21 10:20:45
【问题描述】:

我正在使用 scikit 的逻辑回归,但我不断收到消息:

Found input variables with inconsistent numbers of samples: [90000, 5625]

在下面的代码中,我删除了包含文本的列,然后将日期拆分为训练和测试集。

import numpy as np
import pandas as pd
import matplotlib 
import matplotlib.pyplot as plt
from scipy import stats
from sklearn import datasets, linear_model
from sklearn.model_selection import train_test_split

dataset = pd.read_csv("/Users/An/Desktop/data/telco.csv", na_values = ' ') 
dataset = dataset.dropna(axis = 0)

dataset = dataset.replace({'Yes':1, 'Fiber optic': 1, 'DSL':1, 'No':0, 'No phone service':0, 'No internet service':0})
dataset = dataset.drop('Contract', axis  =1)
dataset = dataset.drop('PaymentMethod',axis  =1)
dataset = dataset.drop('customerID',axis  =1)
dataset = dataset.drop('gender',axis  =1)

for i in list(['tenure', 'MonthlyCharges', 'TotalCharges']):
    sd = np.std(dataset[i])
    mean = np.mean(dataset[i])
    dataset[i] = (dataset[i] - mean) / sd

total = pd.DataFrame(dataset)  
data_train, data_test = train_test_split(total, test_size=0.2)
data_train = data_train.values
data_test = data_test.values

from sklearn.linear_model import LogisticRegression

clf = LogisticRegression(C=1e9)
clf = clf.fit(data_train[:,0:16], data_train[:,16])
print clf.intercept_, clf.coef_

有人可以解释错误消息的含义并帮助我弄清楚为什么会收到它吗?

【问题讨论】:

  • 可以发data_train的形状吗?
  • @markuscosinus 我把它放在克里斯的回答下

标签: python machine-learning scikit-learn logistic-regression


【解决方案1】:

在倒数第二行,data_train.reshape(-1, 1) 导致了您的问题。删除 reshape 对您有帮助。

原因

LogisticRegression.fit 期望 xy 具有相同的 shape[0],但您正在将 x(n, m) 重塑为 (n*m, 1)

这是复制的形状:

import numpy as np

df = np.ndarray((2000,10))
x, y  = df[:, 2:9], df[:, 9]
x.shape, y.shape # << what you should give to `clf.fit`
# ((2000, 7), (2000, ))

x.reshape(-1, 1).shape, y.shape # << what you ARE giving to `clf.fit`,
# ((14000, 1), (2000,))         # << which is causing the problem

【讨论】:

  • 我去掉了reshape,现在两个数组的形状分别是(5625, 16)和(5625,),没问题。但我现在收到此错误:ValueError: Unknown label type: 'unknown'。
  • @Anya 那是y 没有统一的dtype。我无法确定原因,因为我没有数据集,但我的猜测是当您执行dataset.replace 时,有些项目没有转换为int。您可以通过dataset.iloc[-1].value_counts()查看。
  • 尽管我将 x 值指定为第 2 到 18 列中的数据,但我的代码似乎仍在读取包含文本的第 0 列和第 1 列。删除前两列后,我的代码运行良好。你知道为什么会这样吗?
  • @Anya 您能否更新您的问题以反映您当前的代码?
  • 我已经更新了 - 我的数据集现在只有 16 列
猜你喜欢
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 2012-04-19
  • 2015-11-16
  • 1970-01-01
相关资源
最近更新 更多