def visualize_2d(save_path, embedding, label, domain, class_num):

    fig = plt.figure()
    ax = fig.add_subplot(111)
    colors = cm.rainbow(np.linspace(0.0, 1.0, class_num))

    xx = embedding[:, 0]
    yy = embedding[:, 1]

    for i in range(class_num):
        ax.scatter(xx[label == i], yy[label == i], color=colors[i], s=10)
    '''
    for i in range(embedding.shape[0]):
        plt.text(xx[i], yy[i], str(label[i]), fontdict={"size": 10})
    '''

    ax.xaxis.set_major_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(NullFormatter())
    plt.axis('tight')
    plt.legend(loc='best', scatterpoints=1, fontsize=5)
    plt.savefig(os.path.join(save_path, "TSNE_Label_2D.pdf"),
                format='pdf',
                dpi=600)
    plt.show()
    plt.close()

    fig = plt.figure()
    ax = fig.add_subplot(111)
    colors = cm.rainbow(np.linspace(0.0, 1.0, class_num))

    for i in range(2):
        ax.scatter(xx[domain == i],
                   yy[domain == i],
                   color=cm.bwr(i / 1.),
                   s=10)
    '''
    for i in range(embedding.shape[0]):
        plt.text(xx[i], yy[i], str(int(domain[i])), fontdict={
                 "size": 10}, color=cm.bwr(domain[i]/1.))
    '''
    ax.xaxis.set_major_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(NullFormatter())
    plt.axis('tight')
    plt.legend(loc='best', scatterpoints=1, fontsize=5)
    plt.savefig(os.path.join(save_path, "TSNE_Domain_2D.pdf"),
                format='pdf',
                dpi=600)
    plt.show()
    plt.close()
def visualize_3d(save_path, embedding, label, domain, class_num):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection="3d")
    colors = cm.rainbow(np.linspace(0.0, 1.0, class_num))

    xx = embedding[:, 0]
    yy = embedding[:, 1]
    zz = embedding[:, 2]

    for i in range(class_num):
        ax.scatter(xx[label == i],
                   yy[label == i],
                   zz[label == i],
                   color=colors[i],
                   s=10)

    ax.xaxis.set_major_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(NullFormatter())
    ax.zaxis.set_major_formatter(NullFormatter())
    plt.axis('tight')
    plt.legend(loc='best', scatterpoints=1, fontsize=5)
    plt.savefig(os.path.join(save_path, "TSNE_Label_3D.pdf"),
                format='pdf',
                dpi=600)
    plt.show()
    plt.close()

    fig = plt.figure()
    ax = fig.add_subplot(111, projection="3d")

    for i in range(2):
        ax.scatter(xx[domain == i],
                   yy[domain == i],
                   zz[domain == i],
                   color=cm.bwr(i / 1.),
                   s=10)

    ax.xaxis.set_major_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(NullFormatter())
    ax.zaxis.set_major_formatter(NullFormatter())
    plt.axis('tight')
    plt.legend(loc='best', scatterpoints=1, fontsize=5)
    plt.savefig(os.path.join(save_path, "TSNE_Domain_3D.pdf"),
                format='pdf',
                dpi=600)
    plt.show()
    plt.close()
示例#3
0
 def graph_combi(self,par,dico,lar,lon):
     """ This method produces a plot as a cumulative plot where the results
     of the Maximum Likehood Method are directly shown in order to allow the
     user to checked graphically (GSA) if the number of populations is adapted.
     If not he can adapt the number of populations """
     fig2 = plt.figure(2)
     fig2.canvas.manager.window.resizable(int(lar/2), int(lon/2))
     fig2.canvas.manager.window.wm_geometry("+"+str(int(lon/2))+"+0") 
     ax = fig2.add_subplot(111)
     lis=list(self.df[self.parameter].dropna())
     (quantiles, values), (slope, intercept, r) = stats.probplot(lis, dist='norm')
     index = 0
     lo = len(lis)
     plt.plot(quantiles, values,'ok') # To plot the cumulative plot
     color=cm.bwr(np.linspace(0,1,len(dico.keys()))) # Color for each population
     for key,c in zip(dico.keys(),color):
         ax.plot(quantiles[index:int(index+len(dico[key]))], values[index:int(index+len(dico[key]))],marker='o',c=c,linewidth=0) # Print the population and mixing categories
         if len(dico[key])>1:
             nb = len(values[index:int(index+len(dico[key]))])
             perc = round(100*float(nb)/float(lo),1)
             av = round(np.mean(values[index:int(index+len(dico[key])-1)]),1)
             st = round(np.std(values[index:int(index+len(dico[key])-1)]),1)
         else: # If there is one value for the key to avoid numpy Warning on the mean, deviation ...
             nb = 1
             perc = round(100*float(nb)/float(lo),1)
             av = round(values[index],1)
             st = 0
         ax.annotate(str(key)+' ('+str(perc)+'%): Mean='+str(av)+'+/-'+str(st), xy=(quantiles[int(index+len(dico[key])/2)], values[int(index+len(dico[key])/2)]), xytext=(quantiles[int(index+len(dico[key])/2)]+0.5, values[int(index+len(dico[key])/2)]),color=c,fontsize=12) # Plot the name of the key and the mean+stdev directly on the plot
         index = int(index+len(dico[key]))
     ticks_perc=[1, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 99] #define ticks
     ticks_quan=[stats.norm.ppf(i/100.) for i in ticks_perc] #transfrom them from precentile to cumulative density
     plt.xticks(ticks_quan,ticks_perc,fontsize=15) #assign new ticks
     plt.xlabel('Cumulative (%)',fontsize=15)
     plt.yticks(fontsize=15)
     plt.ylabel('Parameter (values)',fontsize=15)
     plt.title(str(par),fontsize=20)
     plt.grid() #show plot
     fig2.show()   
示例#4
0
    def visualize(self, dim):
        self.src_extractor.cpu()
        self.tar_extractor.cpu()

        self.src_extractor.eval()
        self.tar_extractor.eval()

        src_data = torch.FloatTensor()
        src_label = torch.LongTensor()

        for index, src in enumerate(self.src_loader):
            data, label = src
            src_data = torch.cat((src_data, data))
            src_label = torch.cat((src_label, label))

        tar_data = torch.FloatTensor()
        tar_label = torch.IntTensor()

        for index, tar in enumerate(self.tar_loader):
            data, label = tar
            tar_data = torch.cat((tar_data, data))
            tar_label = torch.cat((tar_label, label))

        if src_data.shape[1] != 3:
            src_data = src_data.expand(
                src_data.shape[0], 3, self.img_size, self.img_size)

        src_data, src_label = src_data[0:1000], src_label[0:1000]
        tar_data, tar_label = tar_data[0:1000], tar_label[0:1000]

        src_z = self.src_extractor(src_data)
        tar_z = self.src_extractor(tar_data)

        data = np.concatenate(
            (src_z.detach().numpy(), tar_z.detach().numpy()))
        label = np.concatenate(
            (src_label.numpy(), tar_label.numpy()))

        tsne = TSNE(n_components=dim, verbose=1,
                    init="pca", perplexity=40, n_iter=3000)

        embedding = tsne.fit_transform(data)

        embedding_max, embedding_min = np.max(
            embedding, 0), np.min(embedding, 0)
        embedding = (embedding-embedding_min)/(embedding_max-embedding_min)

        if dim == 2:
            fig = plt.figure()
            ax = fig.add_subplot(111)
            colors = cm.rainbow(np.linspace(0.0, 1.0, self.num_classes))

            xx = embedding[:, 0]
            yy = embedding[:, 1]

            for i in range(self.num_classes):
                ax.scatter(xx[label == i], yy[label == i],
                           color=colors[i], s=10)

            ax.xaxis.set_major_formatter(NullFormatter())
            ax.yaxis.set_major_formatter(NullFormatter())
            plt.axis('tight')
            plt.legend(loc='best', scatterpoints=1, fontsize=5)
            plt.savefig("TSNE_Label_2D.pdf", format='pdf', dpi=600)
            plt.show()
            plt.close("all")

            src_tag = torch.zeros(src_z.size(0))
            tar_tag = torch.ones(tar_z.size(0))
            tag = np.concatenate((src_tag.numpy(), tar_tag.numpy()))

            fig = plt.figure()
            ax = fig.add_subplot(111)
            colors = cm.rainbow(np.linspace(0.0, 1.0, self.num_classes))

            xx = embedding[:, 0]
            yy = embedding[:, 1]

            for i in range(2):
                ax.scatter(xx[tag == i], yy[tag == i],
                           color=cm.bwr(i/1.), s=10)

            ax.xaxis.set_major_formatter(NullFormatter())
            ax.yaxis.set_major_formatter(NullFormatter())
            plt.axis('tight')
            plt.legend(loc='best', scatterpoints=1, fontsize=5)
            plt.savefig("TSNE_Domain_2D.pdf", format='pdf', dpi=600)
            plt.show()
            plt.close("all")

        elif dim == 3:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection="3d")
            colors = cm.rainbow(np.linspace(0.0, 1.0, self.num_classes))

            xx = embedding[:, 0]
            yy = embedding[:, 1]
            zz = embedding[:, 2]

            for i in range(self.num_classes):
                ax.scatter(xx[label == i], yy[label == i],
                           zz[label == i], color=colors[i], s=10)

            ax.xaxis.set_major_formatter(NullFormatter())
            ax.yaxis.set_major_formatter(NullFormatter())
            ax.zaxis.set_major_formatter(NullFormatter())
            plt.axis('tight')
            plt.legend(loc='best', scatterpoints=1, fontsize=5)
            plt.savefig("TSNE_Label_3D.pdf", format='pdf', dpi=600)
            plt.show()
            plt.close("all")

            src_tag = torch.zeros(src_z.size(0))
            tar_tag = torch.ones(tar_z.size(0))
            tag = np.concatenate((src_tag.numpy(), tar_tag.numpy()))

            fig = plt.figure()
            ax = fig.add_subplot(111, projection="3d")

            xx = embedding[:, 0]
            yy = embedding[:, 1]
            zz = embedding[:, 2]

            for i in range(2):
                ax.scatter(xx[tag == i], yy[tag == i],
                           zz[tag == i], color=cm.bwr(i/1.), s=10)

            ax.xaxis.set_major_formatter(NullFormatter())
            ax.yaxis.set_major_formatter(NullFormatter())
            ax.zaxis.set_major_formatter(NullFormatter())
            plt.axis('tight')
            plt.legend(loc='best', scatterpoints=1, fontsize=5)
            plt.savefig("TSNE_Domain_3D.pdf", format='pdf', dpi=600)
            plt.show()
            plt.close("all")
示例#5
0
 def plot_campaign_pop(self, par, dictiopopu, coordonnee, lar, lon):
     """ This method creates a map of the data serie architectured with
     populations and mixing groups as defined above """
     fig4 = plt.figure()
     fig4.canvas.manager.window.resizable(int(lar / 2), int(lon / 2))
     fig4.canvas.manager.window.wm_geometry("+" + str(int(lon / 2)) + "+" +
                                            str(int(lar / 2)))
     ax = fig4.add_subplot(111)
     try:
         dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
         f = os.path.join(dirname, "Map.tif")
         datafile = cbook.get_sample_data(f)
         img = imread(datafile)
     except:
         pass
     dicofinal = OrderedDict()
     for key in dictiopopu.keys():
         try:
             minimum = np.min(dictiopopu[key])
             maximum = np.max(dictiopopu[key])
             dicofinal.setdefault(key, [[], []])
             for i in range(0, len(self.df.values)):
                 if minimum <= float(
                         self.df[self.parameter].iloc[i]) <= maximum:
                     dicofinal[key][0].append(
                         float(self.df['LONGITUDE'].iloc[i]))
                     dicofinal[key][1].append(
                         float(self.df['LATITUDE'].iloc[i]))
                 else:
                     None
         except ValueError:
             pass
     colors = cm.bwr(np.linspace(0, 1, len(dicofinal.keys())))
     for keyf, c in zip(dicofinal.keys(), colors):
         ax.scatter(dicofinal[keyf][0],
                    dicofinal[keyf][1],
                    edgecolors='black',
                    linewidth=1,
                    color=c,
                    marker='o',
                    s=50,
                    label=str(keyf) + ': from ' +
                    str(round(np.min(dictiopopu[keyf]), 2)) + ' to ' +
                    str(round(np.max(dictiopopu[keyf]), 2)))
     handles, labels = ax.get_legend_handles_labels()
     ax.legend(reversed(handles),
               reversed(labels),
               loc='lower left',
               scatterpoints=1,
               fontsize=12)
     ax.ticklabel_format(useOffset=False)
     plt.xticks(rotation=70)
     try:
         plt.imshow(img, zorder=0, extent=coordonnee)
     except:
         pass
     plt.xlim(float(coordonnee[0]), float(coordonnee[1]))
     plt.ylim(float(coordonnee[2]), float(coordonnee[3]))
     plt.xlabel('Longitude', fontsize=15)
     plt.ylabel('Latitude', fontsize=15)
     plt.xticks(fontsize=15)
     plt.yticks(fontsize=15)
     props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
     plt.text(0.05,
              0.95,
              'X1: ' + str(round(coordonnee[0], 5)) + '\n' + 'X2: ' +
              str(round(coordonnee[1], 5)) + '\n' + 'Y1: ' +
              str(round(coordonnee[2], 5)) + '\n' + 'Y2: ' +
              str(round(coordonnee[3], 5)),
              transform=ax.transAxes,
              fontsize=12,
              verticalalignment='top',
              bbox=props)
     plt.title(str(par), fontsize=20)
     fig4.show()