[英]Finding the mean of r squared in a dictionary list
我正在為 k=3 的數據集運行 kmeans。 並且還為每個單獨的集群運行線性回歸,並為每個集群找到 r^2。 所以在我找到集群 1,2 和 3 的 r^2 之后,我想找到 r^2 的平均值,但不知道該怎么做。
代碼:
``
np.random.seed(0)
df =
) 正則
plt.show()
如果您試圖找到數組的平均值,那么您可以這樣做:
values = []
START = 1
FINISH = 10
for r in range(START, FINISH+1):
values.append(r**2)
l_sum = 0
for v in values:
l_sum += v
print("The array average is: ", (l_sum/len(values)))
ages = np.random.randint(18, 65, size=1000)
income = np.random.randint(50000, 500000, size=1000)
spending = np.random.randint(1, 100, size=1000)
df = pd.DataFrame({'Age': ages, 'Annual Income (k$)': income, 'Spending Score (1-100)': spending})
df 看起來像
Age Annual Income (k$) Spending Score (1-100)
0 45 271795 40
1 48 185982 9
2 55 312031 29
3 37 463082 95
4 62 337616 94
5 62 142722 47
6 25 53020 63
7 63 115837 71
8 36 173820 42
9 57 496343 58
. . . .
然后我會為集群創建一個列
df['cluster'] = y_kmeans
之后,遍歷唯一的簇編號,並獲取 dataframe 的子集進行操作。
通常,如果您要評估回歸 model,請將基於 X_test 的預測與 y_test 中的實際值進行比較。
cluster_regression_r2s = {}
for cluster in df['cluster'].unique():
df_cluster = df.loc[df['cluster'] == cluster, :]
X = df_cluster.iloc[:, :-1]
y = df_cluster.iloc[:, -1]
X_train, X_test, y_train,y_test = train_test_split(X, y, test_size=0.4, random_state=0)
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
cluster_regression_r2s[cluster] = r2_score(y_test, y_pred)
然后你可以計算 r2 分數的平均值
mean_r2 = np.mean(cluster_regression_r2s.values())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.