Exemplo n.º 1
0
def stress_vs_estimate(N=128,dim=2):
    noise2signal = 10**np.arange(-2.5,0.5,0.5); num1=len(noise2signal)
    average_neighbors = [2,8,32,128,512]; num2=len(average_neighbors)
    its = 10

    X = misc.disk(N,dim=dim)
    D = distance_matrix(X,X)
    signal_std = np.std(X)
    noise = np.sqrt(noise2signal)*signal_std
    vis = mds.MDS(D,dim=dim)
    for i in range(num1):
        X_noisy = X+np.random.randn(N,dim)*noise2signal[i]
        true_stress = mds.stress_function(X_noisy,D,estimate=False)
        print(f'exact stress : {true_stress:0.2e}')
        for j in range(num2):
            print(f'  average neighbors : {average_neighbors[j]}')
            stress = 0
            stresses = []
            for k in range(its):
                stresses.append(mds.stress_function(
                    X_noisy,D,estimate=average_neighbors[j]))
            print(f'    average stress : {np.average(stresses):0.2e} '+\
                  f'[{abs(np.average(stresses)-true_stress)/true_stress:0.2e}]')
            print(f'    standard deviation : {np.std(stresses):0.2e} '+\
                  f'[{np.std(stresses)/true_stress:0.2e}]')
            print(f'    minimum stress : {min(stresses):0.2e} '+\
                  f'[{abs(min(stresses)-true_stress)/true_stress:0.2e}]')
            print(f'    maximum stress : {max(stresses):0.2e} '+\
                  f'[{abs(max(stresses)-true_stress)/true_stress:0.2e}]')
Exemplo n.º 2
0
def mds_comparison():
    max_iters = 100
    save_frequency = 10
    
    import misc, distances, mds
    print('\n*** gd.mds_comparison() ***\n')
    
    Y = misc.disk(30,2)
    plt.figure()
    plt.plot(Y[:,0],Y[:,1],'o')
    plt.title('Original data')
    plt.draw()
    plt.pause(0.1)
    
    D = distances.compute(Y)
    
    vis = mds.MDS(D,dim=2,verbose=1)
    vis.initialize_Y()
    vis.optimize(algorithm='gd',max_iters=max_iters,save_cost=True,
                 learning_rate=0.01,from_scratch=True,
                 save_frequency=save_frequency,label='mds, lr=0.01',verbose=2)
    vis.optimize(algorithm='gd',max_iters=max_iters,save_cost=True,
                 learning_rate=0.1,from_scratch=True,
                 save_frequency=save_frequency,label='mds, lr=0.05',verbose=2)
    vis.optimize(algorithm='agd',max_iters=max_iters,save_cost=True,
                 from_scratch=True,save_frequency=save_frequency,verbose=2)

    plt.show()
Exemplo n.º 3
0
    def smart_initialize(self,max_iter=[50,30],lr=[1,0.1],
                         batch_size=10,**kwargs):
        """\
        Computes an mds embedding (dimension embedding_dimension) of the 
        combined distances. Only works when self.Q_is_fixed is False (as this 
        is unnecessary otherwhise).

        Parameters :

        X0 : None or array
        Optional initial embedding (used to compute mds embedding)
        
        Q0 : None or list of arrays
        Optional initial projection parameters.
        """
        assert self.fixed_embedding is False
        assert self.fixed_projections is False
    
        if self.verbose > 0:
            print(self.indent+'  MPSE.smart_initialize():')

        distances = np.sum(self.distances,axis=0)/self.n_perspectives
        if self.weights is not None and self.weights[0] is not None:
            weights = np.product(self.weights,axis=0)
        else:
            weights = None
        vis = mds.MDS(distances,dim=self.embedding_dimension,min_grad=1e-4,
                      indent=self.indent+'    ',
                      initial_embedding=self.embedding,
                      weights = weights,
                      verbose=self.verbose)
        vis.gd(batch_size=batch_size, max_iter=max_iter[0],lr=lr[0],**kwargs)
        self.embedding = vis.X
        H = vis.computation_history[0]
        H['fixed_embedding'] = False
        H['fixed_projections'] = True
        self.computation_history.append(H)

        def Xi():
            indices = np.arange(self.n_samples)
            np.random.shuffle(indices)
            xi = {
                'indices' : indices
            }
            return xi
        F = lambda Q, indices : self.gradient(self.embedding,Q,
                                              batch_size=batch_size,
                                              return_embedding=False)
        Q0 = np.array(self.projections)
        self.projections, H = gd.single(Q0,F,Xi=Xi,p=self.proj.restrict,
                              max_iter=max_iter[1],lr=lr[1],
                              verbose=self.verbose,indent=self.indent+'    ',
                              **kwargs)
        H['fixed_embedding'] = True
        H['fixed_projections'] = False
        self.computation_history.append(H)
        return
Exemplo n.º 4
0
def stress_vs_noise(N=128, dim=2):
    X = misc.disk(N, dim=dim)
    D = distance_matrix(X, X)
    vis = mds.MDS(D, dim=dim)

    noise = 10**np.arange(-2, 3, 0.5)
    its = len(noise)
    stress = np.empty(its)
    for i in range(its):
        X_noisy = X + np.random.randn(N, dim) * noise[i]
        stress[i] = mds.stress_function(X_noisy, D, estimate=False)
        vis.initialize(X0=X_noisy)
        vis.figureX(title=f'noise: {noise[i]:0.2e}, stress: {stress[i]:0.2e}')
    plt.show()
    return
Exemplo n.º 5
0
    def algorithmRequest(self, request):
        if 'parameters' in request.keys():
            params = request['parameters'][0]
            params = json.loads(params)
            print 'parameters:', params, ' type:', params['type']
            if 'type' in params and 'name' in params:
                if params['type'] == 'layout':
                    layoutName = params['name'].encode("utf-8")
                    g = None
                    if layoutName == 'MDS':
                        print "calling mds layout"
                        g = self.getGraphMan(request).substrate
                        descP = g.getStringProperty("descriptors")
                        #res = mds.MDS(g, descP).points()
                        res = mds.MDS(g, descP).sklearn_mds()
                        print res
                    else:
                        g = self.getGraphMan(request).callLayoutAlgorithm(
                            layoutName, params['target'].encode("utf-8"))
                    if g:
                        graphJSON = self.getGraphMan(request).graphToJSON(
                            g,
                            {'nodes': [{
                                'type': 'string',
                                'name': 'label'
                            }]})
                        self.sendJSON(graphJSON)

                if params['type'] == 'float':
                    g = self.getGraphMan(request).callDoubleAlgorithm(
                        params['name'].encode("utf-8"),
                        params['target'].encode("utf-8"))
                    graphJSON = self.getGraphMan(request).graphToJSON(
                        g, {
                            'nodes': [{
                                'type': 'float',
                                'name': 'viewMetric'
                            }, {
                                'type': 'string',
                                'name': 'label'
                            }]
                        })
                    self.sendJSON(graphJSON)

                if params['type'] == 'synchronize layouts':
                    print "calling layout sync"
                    graphJSON = self.getGraphMan(request).synchronizeLayouts()
                    self.sendJSON(graphJSON)
Exemplo n.º 6
0
def compute_mds(num=2):
    if num==2:
        attributes = attributes2
        families = families2
    elif num==3:
        attributes = attributes3
        families = families3
        
    S = setup.connections(attributes_list=attributes,families_list=families)
    D = distances.dmatrices(S,input_type='similarities',
                            connect_components=True,connect_factor=1.5)
    K = len(S); N = len(S[0])
    
    fig, axs = plt.subplots(1,K,sharey=True,sharex=True)
    for i in range(K):
        vis = mds.MDS(D[i],labels=families)
        vis.initialize()
        vis.optimize(algorithm='agd')
        vis.graph(title=attributes[i])
        
        axs[i].title.set_text(attributes[i])
        if i ==0 :
            for n in range(N):
                axs[i].scatter(vis.X[n,0],vis.X[n,1],label=families[n])
        else:
            for n in range(N):
                axs[i].scatter(vis.X[n,0],vis.X[n,1])
        fig.legend(loc=7)
        fig.tight_layout()
        fig.subplots_adjust(right=0.85)   
        plt.show(block=False)
        fig = vis.figure(); plt.show(block=False)
        
    #proj = perspective.Persp()
    #proj.fix_Q(number=K, special='standard')

    #mv = multiview.Multiview(D,persp=proj,labels=families)
    #mv.setup_visualization()
    #mv.initialize_X()
    #mv.optimize_X(rate=0.002,max_iters=200)
    #mv.figureX(); mv.figureY();
    #mv.figure();
    #mv.graphY(k=0); mv.graphY(k=1)
    plt.show()
Exemplo n.º 7
0
def reliability0(N=100, trials=3, repeats=5, **kwargs):
    """\
    Check number of times the mds algorithm is able to reach the optimal
    solution for different random embeddings.
    """
    print('\n***mds.reliability()***')
    cost = np.empty((repeats, trials))
    success = np.zeros(repeats)
    for i in range(repeats):
        X = misc.disk(N, 2)
        D = multigraph.graph_from_coordinates(X, **kwargs)
        for j in range(trials):
            vis = mds.MDS(D, dim=2, **kwargs)
            vis.gd(min_step=1e-3, **kwargs)
            cost[i, j] = vis.cost
            if vis.cost < 1e-3:
                success[i] += 1
    print(cost)
    print(success)
Exemplo n.º 8
0
def reliability(N=[100], edge_probability=[None], trials=10, **kwargs):
    """\
    Check number of times the mds algorithm is able to reach the optimal
    solution for different random embeddings.
    """
    print('\n***mds.reliability()***')
    lenN = len(N)
    lenE = len(edge_probability)
    success_count = np.zeros((lenN, lenE))
    time_ave = np.zeros((lenN, lenE))
    for i in range(lenN):
        n = N[i]
        for j in range(lenE):
            p = edge_probability[j]
            for k in range(trials):
                X = misc.disk(n, 2)
                D = multigraph.graph_from_coordinates(X, **kwargs)
                vis = mds.MDS(D, dim=2, **kwargs)
                vis.gd(min_step=1e-4,
                       edge_probability=p,
                       max_iters=1e6,
                       **kwargs)
                if vis.cost < 1e-2:
                    success_count[i, j] += 1
                    time_ave[i, j] += vis.H['time']
            if success_count[i, j] != 0:
                time_ave[i, j] /= success_count[i, j]
            print('N, prob :', n, p)
            print('  success ratio :', success_count[i, j] / trials)
            print('  average time :', time_ave[i, j])
    success_ratio = success_count / trials

    plt.figure()
    df = pd.DataFrame(success_ratio.T, E, N)
    sn.set(font_scale=1.4)
    sn.heatmap(df, annot=time_ave.T, cbar_kws={'label': 'success ratio'})
    plt.xlabel('number of nodes')
    plt.ylabel('edge probabilities')
    plt.title('computation time')
    plt.show()
Exemplo n.º 9
0
def stress_vs_miss(N=128,dim=2):
    num = 8
    misses = [1,2,4,8,16,32,64,128]
    fig, ax = plt.subplots(2,4,figsize=(12,6))
    axs = ax.flatten()
    fig.suptitle('normalized-stress / number-of-misplaced-nodes')
    fig.tight_layout(pad=2.5)
    fig.subplots_adjust(top=0.88)

    X = misc.disk(N,dim=dim)
    D = distance_matrix(X,X)
    vis = mds.MDS(D,dim=dim)

    stress = np.empty(num)
    for i in range(num):
        X_misplaced = X.copy()
        X_misplaced[-misses[i]::] = misc.disk(misses[i],dim=dim)
        stress[i] = mds.stress_function(X_misplaced,D,estimate=False)
        vis.initialize(X0=X_misplaced)
        vis.figureX(title=f'{stress[i]:0.2e} / {misses[i]}',
                    ax=axs[i])
    plt.show()
Exemplo n.º 10
0
    def initialize_X(self, X0=None, method='mds',max_iters=50,**kwargs):
        """\
        Set initial embedding using misc.initial function.

        Parameters:

        Y0 : numpy array
        Initial embedding (optional)

        number : int > 0
        Number of initial embeddings to be generated and saved. When looking for
        a minimizer of the stress function, the optimization algorithm is run
        using the different initial embeddings and the best solution is 
        retained.
        """
        if self.verbose > 0:
            print('- Multiview.initialize_X():')

        if X0 is not None:
            if self.verbose > 0:
                print('  method : X0 given')
            assert isinstance(X0,np.ndarray)
            assert X0.shape == (self.N,self.persp.dimX)
            self.X = X0
        else:
            if self.verbose > 0:
                print('  method : ',method)
            if method == 'random':
                self.X = misc.initial_embedding(self.N,dim=self.persp.dimX,
                                                radius=self.D_rms,**kwargs)
            elif method == 'mds':
                D = np.average(self.D,axis=0)
                vis = mds.MDS(D,dim=self.persp.dimX)
                vis.initialize()
                vis.optimize(max_iters=max_iters,**kwargs)
                self.X = vis.X
        self.update()
        self.X0 = self.X.copy()
Exemplo n.º 11
0
def agd_mds_standard(N=100,dim=2,trials=3,runs=5):
    """\
    test convergence of adaptive gradient descent for MDS problem, by solving 
    the MDS problems with multiple initial parameters.
    """
    print('*** test.agd_mds_standard() ***')
    print(f'  N : {N}')
    print(f'  dim : {dim}')
    print()

    for i in range(trials):
        print(f'  Trial # {i}')
        print('  Normalized cost :')
        Y = misc.disk(N,dim)
        D = distances.compute(Y)
        vis = mds.MDS(D,dim=dim)
        stress = []
        for run in range(runs):
            vis.initialize_Y()
            vis.optimize(algorithm='agd')
            stress.append(vis.ncost)
            print(f'  {vis.ncost:0.2e}')
        print()
Exemplo n.º 12
0
def all(D,
        persp,
        method='mds',
        separate=True,
        fixed=True,
        varying=True,
        verbose=0,
        title='',
        names=None,
        labels=None,
        edges=None,
        **kwargs):
    """
    Runs all algorithms on specified data and returns all instances.
    """
    K = len(D)
    N = len(D[0])
    # Separate visualization
    if separate is True:
        svis = []
        for k in range(K):
            svis.append(mds.MDS(D[k]))
            svis[k].initialize()
            svis[k].optimize(verbose=verbose, **kwargs)
    if fixed is True:
        fvis = multiview.Multiview(D, persp, verbose=verbose, labels=labels)
        fvis.setup_visualization()
        fvis.initialize_X()
        fvis.optimize_X()
    if varying is True:
        vvis = multiview.Multiview(D, persp, verbose=verbose, labels=labels)
        vvis.setup_visualization()
        vvis.initialize_X()
        vvis.initialize_Q()
        vvis.optimize_all(batch_number=10, max_iters=300)

    return svis, fvis, vvis
Exemplo n.º 13
0
def stress_vs_noise(N=128,dim=2):
    num = 6
    noise2signal = 10**np.arange(-2.5,0.5,0.5)
    fig, ax = plt.subplots(2,3,figsize=(9,6))
    axs = ax.flatten()
    fig.suptitle('noise-to-signal-ratio / normalized-stress')
    fig.tight_layout(pad=2.5)
    fig.subplots_adjust(top=0.88)

    X = misc.disk(N,dim=dim)
    signal_std = np.std(X)
    noise = np.sqrt(noise2signal)*signal_std
    D = distance_matrix(X,X)
    vis = mds.MDS(D,dim=dim)

    stress = np.empty(num)
    for i in range(num):
        X_noisy = X+np.random.randn(N,dim)*noise2signal[i]
        stress[i] = mds.stress_function(X_noisy,D,estimate=False)
        vis.initialize(X0=X_noisy)
        vis.figureX(title=f'{noise2signal[i]:0.2e} / {stress[i]:0.2e}',
                    ax=axs[i])
    plt.show()
    return
Exemplo n.º 14
0
    def __init__(self, data, weights=None, data_args=None,
                 fixed_embedding=None, fixed_projections=None,
                 initial_embedding=None, initial_projections=None,
                 visualization_method='mds', visualization_args={},
                 total_cost_function='rms',
                 embedding_dimension=3, image_dimension=2,
                 projection_family='linear',projection_constraint='orthogonal',
                 hidden_samples=None,
                 sample_labels=None, perspective_labels=None,
                 sample_colors=None, image_colors=None,
                 verbose=0, indent='',
                 **kwargs):
        """\
        Initializes MPSE object.

        Parameters
        ----------

        data : list, length (n_perspectives)
        List containing distance/dissimilarity/feature data for each 
        perspective. Each array can be of the following forms:
        1) A 1D condensed distance array
        2) A square distance matrix
        3) An array containing features
        ***4) A dictionary describing a graph

        weights : None or string or array or list
        If visualization allows for it, weights to be used in computation of
        cost/gradiant of each perspective.
        IF a list is given, then the list must have length equal to the number
        of perspectives. Otherwise, it is assumed that the given weights are the
        same for all perspectives.
        The possible weights are described in setup.setup_weights. These are:
        1) None : no weights are used
        2) string : method to compute weights based on distances
        3) function : function to compute weights based on distances
        4) array : array containing pairwise weights or node weights, depending
        on size (must be of length of distances or of samples).

        data_args : dictionary (optional) or list
        Optional arguments to pass to distances.setup().
        If a list is passed, then the length must be the number of perspectives
        and each element must be a dictionary. Then, each set of distances will
        be set up using a different set of arguments.

        fixed_embedding : array
        If an array is given, this is assumed to be the true embedding and
        by default optimization is done w.r.t. the projections only.

        fixed_projections : list
        If a list is given, this is assumed to be the true projections and by
        default optimization is done w.r.t. the embedding coordinates only.

        initial_embedding : array
        If given, this is the initial embedding used.

        initial_projections : list
        If given, this is the initial projections used.

        visualization_method : str
        Visualization method. Current options are 'mds' and 'tsne'.
        The visualization method can be different for different perspectives, 
        by passing a list of visualization methods instead.

        visualization_args : dict
        Dictionary with arguments to pass to each visualization method.
        Different arguments can be passed to different visualization methods
        by passing a list of dictionaries instead.

        embedding_dimension : int
        Dimension of embedding.

        image_dimension : int
        Dimension of image (after projection). Each perspective can have a
        different image dimension, by specifying a list instead.

        projection_family : str
        Projection family. Options are 'linear'.

        projection_constraint : str
        Constraints on projection family. Options are None, 'orthogonal',
        'similar'.

        embedding_dimension : int > 0
        Dimension of the embedding.
        Alternative name: embedding_dimension

        projection_dimension : int or array
        Dimension of projections. Can be different for each perspective.
 
        persp : Object instance of projections.Persp class or int > 0.
        Describes set of allowed projection functions and stores list of
        projection parameters. See perspective.py. If instead of a Persp object
        a positive integer int is given, then it is assumed that 
        embedding_dimension=image_dimension=int
        and that all projections are the identity.

        sample_labels : list (optional)
        List containing labels of samples (used in plots).

        sample_colors : array (optional)
        Array containing color value of samples (used in plots).

        image_colors : array-like, shape (n_perspectives, n_samples)
        Colors for each image.
        """
        self.verbose, self.indent = verbose, indent
        if verbose > 0:
            print(indent+'mview.MPSE():')

        ##set up sets of distances from data
        self.distances = setup.setup_distances_from_multiple_perspectives(
            data, data_args)
        self.n_perspectives = len(self.distances)
        self.n_samples = scipy.spatial.distance.num_obs_y(self.distances[0])

        ##set up weights from data
        if isinstance(weights,list) or isinstance(weights, np.ndarray):
            assert len(weights) == self.n_perspectives
            self.weights = weights
        else:
            self.weights = [weights]*self.n_perspectives
        for i in range(self.n_perspectives):
            self.weights[i] = setup.setup_weights(self.distances[i], \
                                self.weights[i], min_weight = 0)

        ##set up parameters
        self.embedding_dimension = embedding_dimension
        self.image_dimension = image_dimension
        self.projection_family = projection_family
        self.projection_constraint = projection_constraint
        proj = projections.PROJ(embedding_dimension,image_dimension,
                                projection_family,projection_constraint)
        self.proj = proj

        ##set up hidden samples
        if hidden_samples is not None:
            assert isinstance(hidden_samples, list)
            assert len(hidden_samples) == self.n_perspectives
        self.hidden_samples = hidden_samples

        if verbose > 0:
            print(indent+'  data details:')
            print(indent+f'    number of perspectives : {self.n_perspectives}')
            print(indent+f'    number of samples : {self.n_samples}')
            print(indent+'  visualization details:')
            print(indent+'    embedding dimension :',self.embedding_dimension)
            print(indent+f'    image dimension : {self.image_dimension}')
            print(indent+f'    visualization type : {visualization_method}')

        #setup sample labels:
        if sample_labels is not None:
            assert len(sample_labels) == self.n_samples
        self.sample_labels = sample_labels
        #setup perspective labels:
        if perspective_labels is None:
            perspective_labels = range(1,self.n_perspectives+1)
        else:
            assert len(perspective_labels) == self.n_perspectives
        self.perspective_labels = perspective_labels
        
        #setup colors:
        self.sample_colors = sample_colors
        self.image_colors = image_colors

        #setup visualization instances:
        self.visualization_instances = []
        self.visualization_method = visualization_method
        if isinstance(visualization_method,str):
            visualization_method = [visualization_method]*self.n_perspectives
        if isinstance(visualization_args,dict):
            visualization_args = [visualization_args]*self.n_perspectives
        for i in range(self.n_perspectives):
            assert visualization_method[i] in ['mds','tsne']
            if self.verbose > 0:
                print('  setup visualization instance for perspective',
                      self.perspective_labels[i],':')
            if visualization_method[i] == 'mds':
                vis = mds.MDS(self.distances[i],
                              weights = self.weights[i],
                              embedding_dimension=self.image_dimension,
                              verbose=self.verbose, indent=self.indent+'    ',
                              **visualization_args[i])
            elif visualization_method[i] == 'tsne':
                vis = tsne.TSNE(self.distances[i],
                                embedding_dimension=self.image_dimension,
                                verbose=self.verbose, indent=self.indent+'    ',
                                **visualization_args[i])
            self.visualization_instances.append(vis)
        self.visualization = self.visualization_instances

        #setup objectives:
        if total_cost_function == 'rms':
            self.total_cost_function = lambda individual_costs : \
                np.sqrt(np.sum(individual_costs**2)/self.n_perspectives)
        else:
            assert callable(total_cost_function)
            self.total_cost_function = total_cost_function
        def cost_function(X,Q,Y=None,**kwargs):
            if Y is None:
                Y = self.proj.project(Q,X)
            individual_costs = np.zeros(self.n_perspectives)
            for k in range(self.n_perspectives):
                individual_costs[k] = \
                    self.visualization[k].objective(Y[k],**kwargs)
            cost = self.total_cost_function(individual_costs)
            return cost, individual_costs
        self.cost_function = cost_function

        #setup gradient function:
        if self.projection_family == 'linear':
            def gradient(embedding,projections,batch_size=None,indices=None,
                         return_embedding=True,return_projections=True,
                         return_cost=True, return_individual_costs=False):
                """\
                Returns MPSE gradient(s), along with cost and individual costs 
                (optional).

                Parameters
                ----------

                embedding : numpy array
                Current embedding.

                projections : numpy array
                Current projections (as a single array).

                return_embedding : boolean
                If True, returns MPSE gradient w.r.t. embedding.

                return_projections : boolean
                If True, returns MPSE gradient w.r.t. projections. 

                return_cost : boolean
                If True, returns MPSE cost.

                return_individual_costs : boolean
                If True, returns individual embedding costs.
                """
                if return_embedding:
                    dX = np.zeros(embedding.shape)
                if return_projections:
                    dQ = []
                individual_costs = np.empty(self.n_perspectives)
                Y = self.proj.project(projections,embedding)
                for k in range(self.n_perspectives):
                    dY_k, cost_k = self.visualization[k].gradient(
                        Y[k],batch_size=batch_size,indices=indices)
                    individual_costs[k] = cost_k
                    if return_embedding:
                        dX += dY_k @ projections[k][:2, :3]
                    if return_projections:
                        dQ.append(dY_k.T @ embedding)
                if return_embedding:
                    dX /= self.n_perspectives
                cost = self.total_cost_function(individual_costs)
                if return_embedding is False:
                    grad = np.array(dQ)
                elif return_projections is False:
                    grad = dX
                else:
                    grad = [dX,np.array(dQ)]
                if return_individual_costs:
                    return grad, cost, individual_costs
                else:
                    return grad, cost
            self.gradient = gradient
        else:
            def gradient_X(X,Q,Y=None):
                pgradient = self.proj.compute_gradient(X[0],params_list=Q)
                if Y is None:
                    Y = self.proj.project(X,params_list=Q)
                gradient = np.zeros((self.n_samples,self.embedding_dimension))
                for k in range(self.n_perspectives):
                    gradient += self.visualization[k].gradient(Y[k]) \
                                @ pgradient[k]
                return gradient
            self.gradient_X = gradient_X

        #set up initial embedding and projections (fixed optional):
        if verbose > 0:
            print(indent+'  initialize:')
        #set fixed and initial embedding:
        if fixed_embedding is not None:
            if verbose > 0:
                print(indent+'    fixed embedding : True')
            self.embedding = fixed_embedding
            self.initial_embedding = fixed_embedding
            self.fixed_embedding = True
        else:
            if verbose > 0:
                print(indent+'    fixed embedding : False')
            if initial_embedding is None:
                if verbose > 0:
                    print(indent+'    initial embedding : random')
                self.initial_embedding = misc.initial_embedding(
                    self.n_samples,dim=self.embedding_dimension, radius=1)
            else:
                assert isinstance(initial_embedding,np.ndarray)
                assert initial_embedding.shape == (
                    self.n_samples, self.embedding_dimension)
                if verbose > 0:
                    print(indent+'    initial embedding : given')
                self.initial_embedding = initial_embedding
            self.embedding = self.initial_embedding
            self.fixed_embedding = False
        #set fixed and initial projections:
        if fixed_projections is not None:
            if isinstance(fixed_projections,str):
                fixed_projections = self.proj.generate(number= \
                            self.n_perspectives,method=fixed_projections)
            assert(all([isinstance(fp,np.ndarray) for fp in fixed_projections]))
            fixed_projections = [f[:2, :3] for f in fixed_projections]
            self.projections = fixed_projections
            self.initial_projections = fixed_projections
            self.fixed_projections = True
            if verbose > 0:
                print(indent+'    fixed projections : True')
        else:
            if verbose > 0:
                print(indent+'    fixed projections : False')
            if initial_projections is None:
                if verbose > 0:
                    print(indent+'    initial projections : random')
                self.initial_projections = self.proj.generate(
                    number=self.n_perspectives, **kwargs)
            else:
                if verbose > 0:
                    print(indent+'    initial projections : given')
                if isinstance(initial_projections,str):
                    initial_projections = self.proj.generate(number= \
                            self.n_perspectives,method=initial_projections)
                self.initial_projections = initial_projections
            self.projections = self.initial_projections
            self.fixed_projections = False        
        print(indent+' Projection is:')
        print(self.projections)

        self.initial_cost = None
        self.initial_individual_cost = None
        self.computation_history = []
        self.time = 0
        self.update(**kwargs)
Exemplo n.º 15
0
def main(D,
         persp,
         method='mds',
         separate=True,
         fixed=True,
         varying=True,
         verbose=0,
         title='',
         names=None,
         labels=None,
         edges=None,
         **kwargs):
    """
    Runs all algorithms on specified data.
    """
    K = len(D)
    if names is None:
        names = list(range(1, K + 1))

    fig, axes = plt.subplots(3, K)
    [ax.set_axis_off() for ax in axes.ravel()]
    plt.tight_layout()

    # Separate visualization
    if separate is True:
        for k in range(K):
            vis = mds.MDS(D[k], labels=labels)
            vis.initialize()
            vis.optimize(verbose=verbose, **kwargs)
            vis.figureX(ax=axes[0, k], edges=edges[k])
            axes[0, k].title.set_text(names[k] + f'\n {vis.ncost:0.2e}')
        vis.figure(plot=False)
    if fixed is True:
        vis = multiview.Multiview(D, persp, verbose=verbose, labels=labels)
        vis.setup_visualization()
        vis.initialize_X()
        vis.optimize_X()
        vis.figureY(axes=axes[1], edges=edges)
        for k in range(K):
            axes[1, k].title.set_text(f'{vis.individual_ncost[k]:0.2e}')
        vis.figure(plot=False)
        vis.figureX(edges=edges[0])
    if varying is True:
        vis = multiview.Multiview(D, persp, verbose=verbose, labels=labels)
        vis.setup_visualization()
        vis.initialize_X()
        vis.initialize_Q()
        vis.optimize_all()
        print(vis.ncost)
        vis.figureY(axes=axes[2], edges=edges)
        for k in range(K):
            axes[2, k].title.set_text(f'{vis.individual_ncost[k]:0.2e}')
        vis.figure()
        vis.figureX(edges=edges[0])

    axes[0, 0].set_ylabel('individual')
    axes[1, 0].set_ylabel('fixed perspectives')
    for ax in axes.flat:
        ax.set(xlabel='x-label', ylabel='y-label')

    plt.show()
Exemplo n.º 16
0
'''
Created on Nov 22, 2011

@author: Zephyre
'''

import mds
if __name__ == '__main__':
    dev = mds.MDS('COM3')
    dev.setDriverMode(0)
    dev.setLine(2)
    dev.switch(True)
    dev.setPowerdBm(22.5)
    print(dev.getStatus())