我正在尝试解决以下错误,我已经看到过几篇有关此问题的文章,但无法解决。 org.apache.spark.sql.AnalysisException:无法解析*所有列中的列名“功能”
我尝试过的事情:
tempList = []
for col in Df.columns:
new_name = col.strip()
new_name = "".join(new_name.split())
new_name = new_name.replace('.','')
tempList.append(new_name)
Df = Df.toDF(*tempList)
我的Spark数据框中只有6列,并且所有仅都有字符和下划线。 数据框的方案:
StructType(List(StructField(A,ShortType,true),StructField(B,ShortType,true),StructField(C,IntegerType,true),StructField(D,IntegerType,true),StructField(E,StringType,true),StructField(F,DoubleType,true),StructField(G,IntegerType,true)))
我正在尝试从此处实施PCA,https://www.nodalpoint.com/pca-in-spark-1-5/
参考代码:
df = sc.parallelize([[1,2,3], [2,3,4]]).toDF(("a_1", "b", "c"))
def estimateCovariance(df):
m = df.select(df['features']).map(lambda x: x[0]).mean()
dfZeroMean = df.select(df['features']).map(lambda x: x[0]).map(lambda x: x-m) # subtract the mean
return dfZeroMean.map(lambda x: np.outer(x,x)).sum()/df.count()
def pca(df, k=2):
cov = estimateCovariance(df)
col = cov.shape[1]
eigVals, eigVecs = eigh(cov)
inds = np.argsort(eigVals)
eigVecs = eigVecs.T[inds[-1:-(col+1):-1]]
components = eigVecs[0:k]
eigVals = eigVals[inds[-1:-(col+1):-1]] # sort eigenvalues
score = df.select(df['features']).map(lambda x: x[0]).map(lambda x: np.dot(x, components.T) )
scoreDF = sqlContext.createDataFrame(score.map(lambda x: (DenseVector(x),)), ['pca_features'])
# Return the `k` principal components, `k` scores, and all eigenvalues
return components.T, scoreDF, eigVals
comp, score, eigVals = pca(df)
score.collect()
关于可能出什么问题的任何想法吗?
答案 0 :(得分:0)
您似乎没有features
列-如果我正确理解了该问题,则此示例中的所有列均为功能部件,因此您需要选择所有列。
答案 1 :(得分:0)
从您链接到的文章:
我们的
pca
过程的输入包含一个Spark数据框,该数据框包含名为features
的列,其中包含功能为DenseVectors
。
再进一步,您将获得一个有关如何构建样本数据集的示例:
>>> data = [(Vectors.dense([0.0, 1.0, 0.0, 7.0, 0.0]),),
... (Vectors.dense([2.0, 0.0, 3.0, 4.0, 5.0]),),
... (Vectors.dense([4.0, 0.0, 0.0, 6.0, 7.0]),)]
>>> df = sqlContext.createDataFrame(data,["features"])
您的数据集包含许多独立列中的数据。您需要将其截断成单个向量列。 Spark ML为此提供了一个工具,即pyspark.ml.feature.
VectorAssembler
。
在您的情况下,您需要以下内容:
from pyspark.ml.feature import VectorAssembler
vectorAssembler = VectorAssembler(inputCols=["a_1", "b", "c"], outputCol="features")
comp, score, eigVals = pca(vectorAssembler.transform(df))