Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- scatter plot
- from mpl_toolkits.mplot3d import Axes3D
- import matplotlib.pyplot as plt
- fig=plt.figure()
- ax=fig.add_subplot(111, projection='3d')
- x=[0.5,2.2,3.9,2.1,0.5,0.8,2.7,2.5,2.8,0.1]
- y=[4.5,1.5,3.5,1.9,3.2,4.3,1.1,3.5,3.9,4.1]
- z=[2.5,0.1,1.1,4.9,1.2,2.6,3.1,2.8,1.5,2.9]
- import sklearn.preprocessing as p
- import numpy as np
- np.random.seed(0)
- import matplotlib.pyplot as plt
- from mpl_toolkits.mplot3d import Axes3D
- import scipy.spatial.distance as d
- def initialize_clusters(points, k):
- """Initializes clusters as k randomly selected points from points."""
- return points[np.random.randint(points.shape[0], size=k)]
- # Function for calculating the distance between centroids
- def get_distances(centroid, points):
- """Returns the distance the centroid is from each data point in points."""
- return d.cityblock(points , centroid)
- k = 3
- maxiter = 50
- X=np.array( [[0.5, 4.5, 2.5],
- [2.2, 1.5, 0.1],
- [3.9, 3.5, 1.1],
- [2.1, 1.9, 4.9],
- [0.5, 3.2, 1.2],
- [0.8, 4.3, 2.6],
- [2.7, 1.1, 3.1],
- [2.5, 3.5, 2.8],
- [2.8, 3.9, 1.5],
- [0.1, 4.1, 2.9]])
- # scaler = p.MinMaxScaler()
- # X = scaler.fit_transform(X)
- # Initialize our centroids by picking random data points
- centroids = initialize_clusters(X, k)
- # Initialize the vectors in which we will store the
- # assigned classes of each data point and the
- # calculated distances from each centroid
- classes = np.zeros(X.shape[0], dtype=np.float64)
- distances = np.zeros([X.shape[0], k], dtype=np.float64)
- # Loop for the maximum number of iterations
- for i in range(maxiter):
- # Assign all points to the nearest centroid
- for i, c in enumerate(centroids):
- distances[:, i] = get_distances(c, X)
- # Determine class membership of each point
- # by picking the closest centroid
- classes = np.argmin(distances, axis=1)
- # Update centroid location using the newly
- # assigned data point classes
- for c in range(k):
- centroids[c] = np.mean(X[classes == c], 0)
- group_colors = ['skyblue', 'coral', 'lightgreen']
- colors = [group_colors[j] for j in classes]
- fig= plt.figure()
- ax=fig.add_subplot(111, projection='3d')
- ax.scatter(X[:,0],X[:,1],X[:,2], alpha=0.5)
- ax.scatter(centroids[:,0], centroids[:,1], color=['blue', 'darkred', 'green'], marker='o', lw=2)
- print(centroids)
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement