gpt4 book ai didi

machine-learning - 如何在 Pyspark 中获得直线线性回归结果?

转载 作者:行者123 更新时间:2023-11-30 09:05:26 25 4
gpt4 key购买 nike

我正在使用 Pyspark 在一个非常小的数据集上运行简单的线性回归,但无法让它返回直线结果,就像在 scikit-learn、keras 和 tensorflow 中一样。我已经使用超参数搜索尝试了数百个参数和设置。 (我的代码如下)。我也尝试过使用 LinearRegressionWithSGD 并得到相同的结果。我所需要的只是一个单一的直线结果。我如何在 Pyspark 中得到这个?

def plotData(xs, ys, predictions, labels, the_title):
y_preds = list( (predictions.collect()) )
x_labels = list( (labels.collect()) )
print('xs = ', xs)
print('ys = ', ys)
print('y_predictions = ' , y_preds)

# Plot outputs
plt.figure(figsize=(8,5))
plt.axis([min(xs)-1, max(xs)+1, min(ys)-1, max(ys)+1])
plt.title(the_title)
plt.scatter(x_labels, ys, color='blue')
plt.plot(x_labels, y_preds, 'rx')
plt.plot(x_labels, y_preds, color='black', linewidth=3)
plt.xlabel('x values', fontsize=14)
plt.ylabel('y values', fontsize=14)
plt.show()

# Small contrived dataset
dataset = [(1, 1), (2, 3), (4, 3), (3, 2), (5, 5)]

dataset2 = []
xs = []
ys = []
for d in dataset:
xs.append(d[0])
ys.append(d[1])
dataset2.append((d[0], Vectors.dense([d[1]])))

spark = SparkSession.builder.appName("LinearRegTest").getOrCreate()
df = spark.createDataFrame(dataset2, ["label", "features"])

i=100
r=0.3
e=0.8
s='auto'
f=True

# Create linear regression model
lir = LinearRegression(maxIter=i, regParam=r, elasticNetParam=e, solver=s, fitIntercept=f)

# Train the model using our training data
model = lir.fit(df)

# Generate some predictions using our model
fullPredictions = model.transform(df).cache()

# Extract the predictions and the "known" correct labels.
predictions = fullPredictions.select("prediction").rdd.map(lambda x: x[0])
labels = fullPredictions.select("label").rdd.map(lambda x: x[0])

print("Coefficients: " + str(model.coefficients))
print("Intercept: " + str(model.intercept))
print("Total iterations: " + str(model.summary.totalIterations))
paramStr = "maxIter="+str(i)+", regParam="+str(r)+", elasticNetParam="+str(e) +", solver="+str(s)+", fitIntercept="+str(f)

plotData(xs, ys, predictions, labels, "Contrived Dataset: LinearRegression CHART " + "\n" + paramStr)

这给了我这个结果。

Pyspark output

然而,在相同的数据上使用 scikit-learn、keras 和 tensorflow,都给出了直线结果。 LinearRegression 在 Pyspark 中的工作方式是否不同,或者我做错了什么?很感谢任何形式的帮助。

最佳答案

看起来这些点的输出顺序不太正确。解决方案可以像排序一样简单吗?

from pyspark.sql.functions import col
fullPredictions.sort(col("features")).show()

关于machine-learning - 如何在 Pyspark 中获得直线线性回归结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53012062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com