【问题标题】:fit and transform error on Cross validation and test data交叉验证和测试数据的拟合和转换错误
【发布时间】:2023-03-27 03:12:02
【问题描述】:

我需要有关此处代码的帮助。我正在尝试拟合和转换训练数据,然后转换交叉验证和测试数据。但是当我这样做时,我得到的错误是 - ValueError: X has 24155 features, but Normalizer 期望 49041 features 作为输入。

谁能帮我解决这个问题。

我的代码 sn-p-

from sklearn.preprocessing import Normalizer
normalizer = Normalizer()

X_train_price_norm = normalizer.fit_transform(X_train['price'].values.reshape(1,-1))
X_cv_price_norm = normalizer.transform(X_cv['price'].values.reshape(1,-1))
X_test_price_norm = normalizer.transform(X_test['price'].values.reshape(1,-1))


print("After vectorizations")
print(X_train_price_norm.shape, y_train.shape)
print(X_cv_price_norm.shape, y_cv.shape)
print(X_test_price_norm.shape, y_test.shape)
print("="*100)

【问题讨论】:

  • 转换函数需要一个二维数组作为(样本、特征)。该错误表明X_train['price']x_cv['price']x_test['price'] 的第二个维度不相同。请在您拆分它们的地方添加代码。
  • 您知道reshape(1, -1) 会将您的所有数据转换为一个样本吗?我相信这不是你想要的。删除此方法应该会给您想要的结果。
  • @afsharov - 感谢反馈,但是不使用下面的 reshape(-1,1) 是我得到的错误 - ValueError: Expected 2D array, got 1D array instead: array=[399.99 215.92 510.88 ... 861.25 74.99 529.61]。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)。
  • @kaveh - 感谢您愿意提供帮助!这是代码 sn-p,其中数据从 sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, stratify=y) X_train, X_cv, y_train, y_cv = train_test_split (X_train, y_train, test_size=0.33, stratify=y_train)
  • 所以,我认为您应该将 reshape 更改为 (-1,1) 而不是 (1,-1)。由于您有 1 个功能(价格)和许多示例。

标签: python scikit-learn data-preprocessing


【解决方案1】:

transform 函数需要一个二维数组 (samples, features)

错误提示X_train['price']x_cv['price']x_test['price']的第二个维度不相同。

正如代码所反映的,您有 1 个功能(价格),以及许多示例。所以,正如上面的解释(样本,特征),你的输入形状应该像(n_samples,1),因为你有一个特征。现在,考虑将 reshape 更改为 (-1,1) 而不是 (1,-1)

X_train_price_norm = normalizer.fit_transform(X_train['price'].values.reshape(-1,1))
X_cv_price_norm = normalizer.transform(X_cv['price'].values.reshape(-1,1))
X_test_price_norm = normalizer.transform(X_test['price'].values.reshape(-1,1))

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 2022-11-23
    • 2023-03-27
    • 2012-08-21
    • 2017-05-08
    • 1970-01-01
    • 2021-08-05
    • 2018-07-01
    • 2016-01-29
    相关资源
    最近更新 更多