8 ответов
+ 2
yes, here's how i did it at last
import math
import numpy as np
n = int(input())
ce1=[0,0]
ce2=[2,2]
cl1=np.empty((0,2), float)
cl2=np.empty((0,2), float)
for i in range(n):
x=[float(j) for j in input().split()]
d21=(np.array(ce1)-np.array(x))**2
d1=math.sqrt(d21.sum())
d2=math.sqrt(((np.array(ce2)-np.array(x))**2).sum())
if d1<=d2:
cl1=np.append(cl1,np.array([x]),axis=0)
else:
cl2=np.append(cl2,np.array([x]),axis=0)
if len(cl1) != 0:
nce1=np.mean(cl1,axis=0).round(2)
print(nce1)
else:
print (None)
if len(cl2) != 0:
nce2=np.mean(cl2,axis=0).round(2)
print(nce2)
else:
print(None)
+ 1
Finding the next centroid
Unsupervised learning algorithm clustering involves updating the centroid of each cluster. Here we find the next centroids for given data points and initial centroids.
Task
Assume that there are two clusters among the given two-dimensional data points and two random points (0, 0), and (2, 2) are the initial cluster centroids. Calculate the euclidean distance between each data point and each of the centroid, assign each data point to its nearest centroid, then calculate the new centroid. If there's a tie, assign the data point to the cluster with centroid (0, 0). If none of the data points were assigned to the given centroid, return None.
Input Format
First line: an integer to indicate the number of data points (n)
Next n lines: two numeric values per each line to represent a data point in two dimensional space.
Output Format
Two lists for two centroids. Numbers are rounded to the second decimal place.
Sample Input
3
1 0
0 .5
4 0
Sample Output
[0.5 0.25]
[4. 0.]
0
above is the full question
below is my code
i only fail case 3
please help
import math
import numpy as np
n = int(input())
ce1=[0,0]
ce2=[2,2]
cl1=np.empty((0,2), float)
cl2=np.empty((0,2), float)
for i in range(n):
x=[float(j) for j in input().split()]
d21=(np.array(ce1)-np.array(x))**2
d1=math.sqrt(d21.sum())
d2=math.sqrt(((np.array(ce2)-np.array(x))**2).sum())
if d1<=d2:
cl1=np.append(cl1,np.array([x]),axis=0)
else:
cl2=np.append(cl2,np.array([x]),axis=0)
nce1=np.mean(cl1,axis=0).round(2)
nce2=np.mean(cl2,axis=0).round(2)
print(nce1)
print(nce2)
0
Have you completed Arash? How is the test case 3? Do you mind to share it?
0
Thanks Arash! :)
0
I have also write my code like this and run well
import math
import numpy as np
n = int(input())
ce1=[0,0]
ce2=[2,2]
cl1=np.empty([0,2], float)
cl2=np.empty([0,2], float)
for i in range(n):
x = [float(j) for j in input().split()]
d21 = (np.array(ce1)-np.array(x))**2
d1=math.sqrt(d21.sum())
d2 = math.sqrt(((np.array(ce2)-np.array(x))**2).sum())
if d1<=d2:
cl1 = np.append(cl1, np.array([x]), axis=0)
else:
cl2 = np.append(cl2, np.array([x]), axis=0)
if cl1.shape[0]!=0:
print(np.mean(cl1,axis=0).round(2))
else:
print(None)
if cl2.shape[0]!=0:
print(np.mean(cl2,axis=0).round(2))
else:
print(None)
0
Arash, i was there!
What I did was add the None option if one of the cluster is empty :D