""" plt.close('all') # Load an image of a bird A = mpimg.imread('bird_small.png') A = A / 255 # Divide by 255 so that all values are in the range 0 - 1 # Size of the image m, n, z = A.shape X = A.reshape(m * n, 3) K = 16 max_iters = 10 initial_centroids = kmeans_init_centroids(X, K) # Run K-Means centroids, idx = run_kmeans(X, initial_centroids, max_iters) # Sample 1000 random indexes (since working with all the data is # too expensive. If you have a fast computer, you may increase this. sel = np.random.choice(X.shape[0], 1000) fig = plt.figure() from mpl_toolkits.mplot3d import Axes3D ax = fig.add_subplot(111, projection='3d') # Visualize the data and centroid memberships in 3D ax.scatter(X[sel, 0], X[sel, 1], X[sel, 2], c=idx[sel]) plt.title('Pixel dataset plotted in 3D. Color shows centroid memberships')
print('Image shape {}'.format(img_shape)) # Reshape the image into an Nx3 matrix where N = number of pixels. # Each row will contain the Red, Green and Blue pixel values # This gives us our dataset matrix X that we will use K-Means on. X = image.reshape(img_shape[0] * img_shape[1], 3) # Run your K-Means algorithm on this data # You should try different values of K and max_iters here K = 16 max_iters = 10 # When using K-Means, it is important the initialize the centroids # randomly. # You should complete the code in kMeansInitCentroids.py before proceeding initial_centroids = kmic.kmeans_init_centroids(X, K) # Run K-Means centroids, idx = km.run_kmeans(X, initial_centroids, max_iters, False) # plt.show() print('K-Means Done.') input('Program paused. Press ENTER to continue') # ===================== Part 5: Image Compression ===================== # In this part of the exercise, you will use the clusters of K-Means to # compress an image. To do this, we first find the closest clusters for # each example. print('Applying K-Means to compress an image.') # Find closest cluster members
#压缩到100维 再压缩重放后的数据 disp.display_data(X_rec[0:100]) plt.title('Recovered faces') plt.axis('equal') input('Program paused. Press ENTER to continue') '''第8部分 利用PCA可视化高维数据''' image = io.imread('bird_small.png') #读取图片 image = img_as_float(image) img_shape = image.shape X = image.reshape((img_shape[0] * img_shape[1], 3)) #将图片格式转换为包含3列(3个颜色通道)的矩阵 K = 16 #聚类中心数量 max_iters = 10 #外循环迭代次数 initial_centroids = kmic.kmeans_init_centroids(X, K) #初始化K个聚类中心 centroids, idx = km.run_kmeans(X, initial_centroids, max_iters, False) #执行k-means,得到最终的聚类中心和每个样本点所属的聚类中心序号 selected = np.random.randint(X.shape[0], size=1000) #随机选择1000(可以更改)个样本点 每个样本点3维 #可视化3维数据 不同颜色表示每个样本点的所属的簇 cm = plt.cm.get_cmap('RdYlBu') fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(X[selected, 0], X[selected, 1], X[selected, 2], c=idx[selected], cmap=cm,