在For循环中重新分配列表(JavaScript)
如果以前有人问过我,我很抱歉——我在搜索后找不到我想要的东西,但我是个初学者,所以我可能错过了一些东西 我试图用JavaScript实现Lloyd的算法(非常粗糙),以获得一些实践在For循环中重新分配列表(JavaScript),javascript,arrays,for-loop,k-means,Javascript,Arrays,For Loop,K Means,如果以前有人问过我,我很抱歉——我在搜索后找不到我想要的东西,但我是个初学者,所以我可能错过了一些东西 我试图用JavaScript实现Lloyd的算法(非常粗糙),以获得一些实践 var k_means = function (array,number_clusters,max_loops) { var initial_centers = underscore.sample(shelter_lat_lon,number_clusters); var current_centers =
var k_means = function (array,number_clusters,max_loops) {
var initial_centers = underscore.sample(shelter_lat_lon,number_clusters);
var current_centers = initial_centers;
var current_associations = {};
for (p = 0; p < current_centers.length; p++) {
current_associations[current_centers[p]] = []
}
for (loops = 0; loops < max_loops; loops++) {
for (i = 0; i < array.length; i++) {
var current_loc = array[i]
temp_array = new Array();
for (j = 0; j < current_centers.length; j++) {
var distance_from_center = distance(current_centers[j],current_loc)
temp_array.push(distance_from_center)
}
var closest_center_lat_lon = current_centers[smallest_index(temp_array)]
current_associations[closest_center_lat_lon].push(current_loc)
}
new_clusters_temp = []
for (var key in current_associations) {
lat = []
lon = []
for (i = 0; i < current_associations[key].length; i++){
lat.push(current_associations[key][i][0])
lon.push(current_associations[key][i][1])
}
mean_lat = math_module.mean(lat)
mean_lon = math_module.mean(lon)
new_clusters_temp.push([mean_lat,mean_lon])
}
current_centers = new_clusters_temp;
}
}
节点返回错误“无法读取未定义的属性‘push’”。调试一段时间后,它本质上认为数组“current_centers”为空。在Python中,这就是我在for循环之外重新分配列表的方式。这在JavaScript中不同吗
干杯!
Alex您需要做的第一件事是修复for循环。对于(u=0;u
current_centers = new_clusters_temp;