我遇到了以下错误:
AssertionError: 维度不匹配
我使用PySpark的LinearRegressionWithSGD训练了一个线性回归模型。然而,当我尝试在训练集上进行预测时,得到“维度不匹配”的错误。
值得一提的是:
- 数据使用StandardScaler进行了缩放,但预测值没有进行缩放。
- 如代码中所示,用于训练的特征是由PCA生成的。
部分代码如下:
pca_transformed = pca_model.transform(data_std)X = pca_transformed.map(lambda x: (x[0], x[1]))data = train_votes.zip(pca_transformed)labeled_data = data.map(lambda x : LabeledPoint(x[0], x[1:]))linear_regression_model = LinearRegressionWithSGD.train(labeled_data, iterations=10)
预测是错误的来源,我尝试了以下几种方法:
pred = linear_regression_model.predict(pca_transformed.collect())pred = linear_regression_model.predict([pca_transformed.collect()]) pred = linear_regression_model.predict(X.collect())pred = linear_regression_model.predict([X.collect()])
回归权重如下:
DenseVector([1.8509, 81435.7615])
使用的向量如下:
pca_transformed.take(1)[DenseVector([-0.1745, -1.8936])]X.take(1)[(-0.17449817243564397, -1.8935926689554488)]labeled_data.take(1)[LabeledPoint(22221.0, [-0.174498172436,-1.89359266896])]
回答:
这有效:
pred = linear_regression_model.predict(pca_transformed)
pca_transformed的类型是RDD。
该函数对RDD和数组的处理方式不同:
def predict(self, x): """ Predict the value of the dependent variable given a vector or an RDD of vectors containing values for the independent variables. """ if isinstance(x, RDD): return x.map(self.predict) x = _convert_to_vector(x) return self.weights.dot(x) + self.intercept
当使用简单的数组时,可能会出现维度不匹配的问题(如上面的错误)。
可以看出,如果x不是RDD,它会被转换为向量。问题是,除非你使用x[0],否则点积不会工作。
以下是重现错误的代码:
j = _convert_to_vector(pca_transformed.take(1))linear_regression_model.weights.dot(j) + linear_regression_model.intercept
这可以正常工作:
j = _convert_to_vector(pca_transformed.take(1))linear_regression_model.weights.dot(j[0]) + linear_regression_model.intercept