# -*- coding: utf-8 -*- """ Created on Wed Nov 22 08:17:53 2017 @author: Miguel Almeida """ from sklearn.datasets import load_iris from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans from mpl_toolkits.mplot3d import axes3d from skimage.io import imsave,imread def plot_iris(X,y,file_name): plt.figure(figsize=(7,7)) plt.plot(X[y==0,0], X[y==0,1],'o', markersize=7, color='blue', alpha=0.5) plt.plot(X[y==1,0], X[y==1,1],'o', markersize=7, color='red', alpha=0.5) plt.plot(X[y==2,0], X[y==2,1],'o', markersize=7, color='green', alpha=0.5) plt.gca().set_aspect('equal', adjustable='box') plt.savefig(file_name,dpi=200,bbox_inches='tight') iris = load_iris() X = iris.data y = iris.target f, prob= f_classif(X,y) # Create an SelectKBest object to select features with two best ANOVA F-Values fvalue_selector = SelectKBest(f_classif, k=2) # Apply the SelectKBest object to the features and target #Selecionado as que tem menos probabilidade e maior F1-score (probabilidade de independencia dos dados ser maior) X_kbest = fvalue_selector.fit_transform(X, y) pca = PCA(n_components=2) pca.fit(X) print(pca.components_) t_data = pca.transform(X) ####Terceiro Ex. img = imread("vegetables.png") w,h,d = img.shape cols = np.reshape(img/255.0, (w * h, d)) nColors = 16 kmeans = KMeans(n_clusters= nColors, random_state=0) kmeans.fit(cols) labels = kmeans.predict(cols) centroids = kmeans.cluster_centers_ c_cols = np.zeros(cols.shape) for ix in range(cols.shape[0]): c_cols[ix,:] = centroids[labels[ix]] final_img = np.reshape(c_cols,(w,h,3)) imsave('image.png',final_img) #Gerar figura 3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(cols[:,0], cols[:,1], cols[:,2], c=cols,s=10) ax.set_xlabel('Red') ax.set_ylabel('Green') ax.set_zlabel('Blue') ax.set_xlim3d(0,1) ax.set_ylim3d(0,1) ax.set_zlim3d(0,1) plt.savefig('T7-veg_rgb.png',dpi=200,bbox_inches='tight') plot_iris(X_kbest,y,"terceiro.png")