Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. scatter plot
  2. from mpl_toolkits.mplot3d import Axes3D
  3. import matplotlib.pyplot as plt
  4. fig=plt.figure()
  5. ax=fig.add_subplot(111, projection='3d')
  6. x=[0.5,2.2,3.9,2.1,0.5,0.8,2.7,2.5,2.8,0.1]
  7. y=[4.5,1.5,3.5,1.9,3.2,4.3,1.1,3.5,3.9,4.1]
  8. z=[2.5,0.1,1.1,4.9,1.2,2.6,3.1,2.8,1.5,2.9]
  9.  
  10. import sklearn.preprocessing as p
  11. import numpy as np
  12. np.random.seed(0)
  13. import matplotlib.pyplot as plt
  14. from mpl_toolkits.mplot3d import Axes3D
  15. import scipy.spatial.distance as d
  16.  
  17. def initialize_clusters(points, k):
  18. """Initializes clusters as k randomly selected points from points."""
  19. return points[np.random.randint(points.shape[0], size=k)]
  20.  
  21. # Function for calculating the distance between centroids
  22. def get_distances(centroid, points):
  23. """Returns the distance the centroid is from each data point in points."""
  24. return d.cityblock(points , centroid)
  25.  
  26. k = 3
  27. maxiter = 50
  28.  
  29. X=np.array( [[0.5, 4.5, 2.5],
  30. [2.2, 1.5, 0.1],
  31. [3.9, 3.5, 1.1],
  32. [2.1, 1.9, 4.9],
  33. [0.5, 3.2, 1.2],
  34. [0.8, 4.3, 2.6],
  35. [2.7, 1.1, 3.1],
  36. [2.5, 3.5, 2.8],
  37. [2.8, 3.9, 1.5],
  38. [0.1, 4.1, 2.9]])
  39. # scaler = p.MinMaxScaler()
  40. # X = scaler.fit_transform(X)
  41.  
  42. # Initialize our centroids by picking random data points
  43. centroids = initialize_clusters(X, k)
  44.  
  45. # Initialize the vectors in which we will store the
  46. # assigned classes of each data point and the
  47. # calculated distances from each centroid
  48. classes = np.zeros(X.shape[0], dtype=np.float64)
  49. distances = np.zeros([X.shape[0], k], dtype=np.float64)
  50.  
  51. # Loop for the maximum number of iterations
  52. for i in range(maxiter):
  53. # Assign all points to the nearest centroid
  54. for i, c in enumerate(centroids):
  55. distances[:, i] = get_distances(c, X)
  56. # Determine class membership of each point
  57. # by picking the closest centroid
  58. classes = np.argmin(distances, axis=1)
  59. # Update centroid location using the newly
  60. # assigned data point classes
  61. for c in range(k):
  62. centroids[c] = np.mean(X[classes == c], 0)
  63. group_colors = ['skyblue', 'coral', 'lightgreen']
  64. colors = [group_colors[j] for j in classes]
  65.  
  66. fig= plt.figure()
  67. ax=fig.add_subplot(111, projection='3d')
  68. ax.scatter(X[:,0],X[:,1],X[:,2], alpha=0.5)
  69. ax.scatter(centroids[:,0], centroids[:,1], color=['blue', 'darkred', 'green'], marker='o', lw=2)
  70. print(centroids)
  71. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement