IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

Lire l'output du Multiprocessing python [Python 2.X]


Sujet :

Python

  1. #1
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Lire l'output du Multiprocessing python
    Bonjour,

    J'utilise un programme très simple pour lancer des simulations multiprocess, de ma méthode Metropolis_Sampling. Voici mon code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
            ntasks = 1
            chunk_size = int(self.convergence_iteration/ntasks)
     
            pool = multiprocessing.Pool()
            results_async = []
            for i in range(ntasks):
                results_async.append(pool.apply_async(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,)))
     
            hits = np.array(r.get() for r in results_async)
            print(hits)
    La valeur retour de la méthode Metropolis_Sampling is un numpy array. Toutefois, je reçois toujours "generator object <genexpr> at 0x03E58440", et je n'ai aucune idée comme lire cet objet 'hits'. Pourriez vous m'aider s'il vous plait?

    Merci

  2. #2
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Salut,

    Citation Envoyé par hazem2410 Voir le message
    Pourriez vous m'aider s'il vous plait?
    C'est pas si compliqué d'écrire une fonction qui retourne un tableau numpy, de l'appeler via .apply_async et de vérifier que le résultat est bien le tableau attendu. Donc le problème est dans le code que vous ne montrez pas.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  3. #3
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Merci
    Il n'y a aucune erreure générée dans le code. Pourriez vous expliciter plus svp comment écrire cette fonction?

  4. #4
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    Il n'y a aucune erreure générée dans le code. Pourriez vous expliciter plus svp comment écrire cette fonction?
    Si vous n'arrivez pas à écrire des choses simples comme:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    import numpy as np
     
    def f():
        return np.ones(5)
    mettre au point des constructions plus compliquées sera difficile...


    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  5. #5
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Réponse
    Citation Envoyé par wiztricks Voir le message
    Si vous n'arrivez pas à écrire des choses simples comme:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    import numpy as np
     
    def f():
        return np.ones(5)
    mettre au point des constructions plus compliquées sera difficile...


    - W
    Mais pourquoi vous m'insulter en répondant? Il ne s'agit guère de np.ones(5), et j'arrive à peine à faire le lien entre ce que je demande et ce que vous répondez. C'est la première fois que j'utilise le multiprocessing, donc si vous pouvez m'éclaircir merci, sinon pas la peine de me traiter comme un nul.

  6. #6
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    C'est la première fois que j'utilise le multiprocessing, donc si vous pouvez m'éclaircir merci, sinon pas la peine de me traiter comme un nul.
    Pas grand monde pourra vous éclairer sans que vous preniez la peine de posez un code minimal reproduisant le problème constaté.... car si votre fonction retourne normalement un np.array, il n'y a pas de raison pour qu'elle retourne autre chose appelée via multiprocessing.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  7. #7
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Explication détaillée sur code
    Citation Envoyé par wiztricks Voir le message
    Pas grand monde pourra vous éclairer sans que vous preniez la peine de posez un code minimal reproduisant le problème constaté.... car si votre fonction retourne normalement un np.array, il n'y a pas de raison pour qu'elle retourne autre chose appelée via multiprocessing.

    - W
    Voilà le code en détail. J'ai une classe MCMC_MLE (simulation monte carlo), dans laquelle j'ai développé 2 méthodes. La première méthodes est une méthodes d'échantillonnage, elle retourne à la fin un np.array de dimension (12,1). Voici le code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
     
        def Metropolis_Sampling(self, theta, network, configuration):
     
            #Statistics = Change_Statistics.StatisticMeasure(network,10,2,10,2)
     
            z_edge, z_reciprocity, z_sector, z_geographic, z_profit, z_triangle_t, z_triangle_c, z_triangle_u, z_triangle_d, z_in_star, z_out_star, z_two_path  = 0,0,0,0,0,0,0,0,0,0,0,0
            theta_edge, theta_reciprocity, theta_in_star , theta_out_star,theta_two_path, theta_triangle_t = theta[0],theta[1] ,theta[2], theta[3], theta[4],theta[5]
            theta_triangle_c ,theta_triangle_u , theta_triangle_d, theta_sector, theta_geographic, theta_profit = theta[6], theta[7], theta[8] , theta[9] , theta[10], theta[11]
     
            P_0 = np.exp(theta_edge*z_edge + theta_reciprocity*z_reciprocity + theta_sector*z_sector + theta_geographic*z_geographic + theta_profit*z_profit + z_triangle_t*theta_triangle_t
                          + z_triangle_c*theta_triangle_c + z_triangle_u*theta_triangle_u + z_triangle_d*theta_triangle_d + z_in_star*theta_in_star + z_out_star*theta_out_star 
                          + z_two_path*theta_two_path)
     
            network_0 = Graph()
            network_0 = network_0.as_directed()
            network_1 = Graph()
            network_1 = network_1.as_directed()
     
            network_0.add_vertices(network.vcount()) 
            network_1.add_vertices(network.vcount())
     
            network_0.add_edges(network.get_edgelist())
            network_1.add_edges(network.get_edgelist())
     
            network_0.vs["Profit"] = network.vs["Profit"]
            network_0.vs["Sectors"] = network.vs["Sectors"]
            network_0.vs["Geographic"] = network.vs["Geographic"]
     
            network_1.vs["Profit"] = network.vs["Profit"]
            network_1.vs["Sectors"] = network.vs["Sectors"]
            network_1.vs["Geographic"] = network.vs["Geographic"]
     
     
            for m in range(1,self.metropolis_iteration):
     
                i, j  = np.random.randint(0, network_1.vcount()), np.random.randint(0, network_1.vcount())
     
                while (i == j):
                    j = np.random.randint(0, network_1.vcount())
     
                network_1[i,j] = 1 - network_0[i,j]
     
                z_edge = Change_Statistics.StatisticMeasure.Edge_Change(network_0, network_1, i, j)
                z_reciprocity = Change_Statistics.StatisticMeasure.Reciprocity_Change(network_0, network_1, i, j)
                z_sector = Change_Statistics.StatisticMeasure.Sector_Change(network_0, network_1, i, j)
                z_geographic = Change_Statistics.StatisticMeasure.Geographic_Change(network_0, network_1, i, j)
                z_profit = Change_Statistics.StatisticMeasure.Profit_Change(network_0, network_1, i, j)
     
                z_triangle = Change_Statistics.StatisticMeasure.Triangles_Change(network_0, network_1, i, j) 
                z_triangle_t, z_triangle_c, z_triangle_u, z_triangle_d = z_triangle[0], z_triangle[1], z_triangle[2], z_triangle[3]                  
     
                z_stars = Change_Statistics.StatisticMeasure.Stars_Change(network_0, network_1, i, j)
                z_in_star , z_out_star = z_stars[0], z_stars[1]
     
                z_two_path = Change_Statistics.StatisticMeasure.Two_Path_Change(network_0, network_1, i, j)
     
                P_1 = np.exp(theta_edge*z_edge + theta_reciprocity*z_reciprocity + theta_sector*z_sector + theta_geographic*z_geographic + theta_profit*z_profit + z_triangle_t*theta_triangle_t
                              + z_triangle_c*theta_triangle_c + z_triangle_u*theta_triangle_u + z_triangle_d*theta_triangle_d+ z_in_star*theta_in_star + z_out_star*theta_out_star 
                              + z_two_path*theta_two_path)
     
                P = rand.random()
     
                Hasting_ratio = min(1,P_1/P_0)
     
                if P<Hasting_ratio:
     
                    network_0[i,j] = network_1[i,j]
                    P_0 = P_1
     
                else:
                    network_1[i,j] = network_0[i,j]
     
            final_configuration = Change_Statistics.StatisticMeasure.Network_Configuration(network_0)
     
            return final_configuration
    J'utilise après les échantillons simulés pour une routine d'optimisation non-linéaire que j'ai développé, comme suit, et vers la fin vous trouvez mon multiprocessing:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
     
        def MLE_Robins_Monro(self, theta, a_scaling, configuration):            
     
            edges_changes, reciprocity_changes, in_star_changes, out_star_changes, two_path_changes = np.array([]), np.array([]),np.array([]), np.array([]), np.array([])
            triangle_t_change, triangle_c_change, triangle_u_change, triangle_d_change = np.array([]), np.array([]),np.array([]), np.array([])
            sector_changes, geographic_changes, profit_changes = np.array([]) ,np.array([]), np.array([])
     
            for k in range(1,self.initial_iteration):
     
                sampling = self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration)
     
                edges_changes = np.append(edges_changes,sampling[0])
                reciprocity_changes = np.append(reciprocity_changes,sampling[1])
                in_star_changes = np.append(in_star_changes,sampling[2])
                out_star_changes = np.append(out_star_changes,sampling[3])
                two_path_changes = np.append(two_path_changes,sampling[4])
                triangle_t_change = np.append(triangle_t_change,sampling[5])
                triangle_c_change = np.append(triangle_c_change,sampling[6])
                triangle_u_change = np.append(triangle_u_change,sampling[7])
                triangle_d_change = np.append(triangle_d_change,sampling[8])
                sector_changes = np.append(sector_changes,sampling[9])
                geographic_changes = np.append(geographic_changes,sampling[10])
                profit_changes = np.append(profit_changes,sampling[11])
     
            M = np.matrix([edges_changes,reciprocity_changes,in_star_changes, out_star_changes, two_path_changes,triangle_t_change, triangle_c_change, triangle_u_change, triangle_d_change,
                           sector_changes,geographic_changes,profit_changes])   
            D = np.cov(M)
            invD = np.linalg.inv(D)
            E = np.array([np.mean(edges_changes),np.mean(reciprocity_changes),np.mean(in_star_changes),np.mean(out_star_changes),np.mean(two_path_changes),np.mean(triangle_t_change),
                          np.mean(triangle_c_change),np.mean(triangle_u_change),np.mean(triangle_d_change),np.mean(sector_changes),np.mean(geographic_changes),np.mean(profit_changes)])
     
            theta = theta - a_scaling*np.matmul(invD,E - configuration)
     
            #burn-in loop
     
            for m in range(1,self.burn_in):
     
                sampling = self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration)
                edges_changes, reciprocity_changes, in_star_changes, out_star_changes, two_path_changes = sampling[0], sampling[1],sampling[2], sampling[3], sampling[4]
                triangle_t_change, triangle_c_change, triangle_u_change, triangle_d_change = sampling[5], sampling[6],sampling[7], sampling[8]
                sector_changes, geographic_changes, profit_changes = sampling[9] ,sampling[10], sampling[11]
     
                final_configuration = np.array([edges_changes,reciprocity_changes,in_star_changes, out_star_changes, two_path_changes,triangle_t_change, triangle_c_change, triangle_u_change, 
                                                triangle_d_change,sector_changes,geographic_changes,profit_changes])        
                theta = theta - a_scaling*np.matmul(invD,final_configuration - configuration) 
     
            r = 1
            convergence_test = False
     
            while convergence_test == False:
                while r <= self.NR_subphases:
     
                    NR_max_iteration = (7+ self.number_variable)*2^(4*r/3) + 200 
                    NR_min_iteration = (7+ self.number_variable)*2^(4*r/3)           
                    past_configuration = configuration
                    for m in range(1,NR_max_iteration):
     
                        sampling = self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration)
                        edges_changes, reciprocity_changes, in_star_changes, out_star_changes, two_path_changes = sampling[0], sampling[1],sampling[2], sampling[3], sampling[4]
                        triangle_t_change, triangle_c_change, triangle_u_change, triangle_d_change = sampling[5], sampling[6],sampling[7], sampling[8]
                        sector_changes, geographic_changes, profit_changes = sampling[9] ,sampling[10], sampling[11]
     
                        final_configuration = np.array([edges_changes,reciprocity_changes,in_star_changes, out_star_changes, two_path_changes,triangle_t_change, triangle_c_change, triangle_u_change, 
                                                triangle_d_change,sector_changes,geographic_changes,profit_changes])        
                        theta = theta - a_scaling*np.matmul(invD,final_configuration - configuration)           
                        #print(theta)            
                        if (np.mean(configuration)>np.mean(final_configuration)) and (np.mean(configuration)<np.mean(past_configuration)) and (m>NR_min_iteration):
                            break
                        past_configuration = final_configuration
     
                    r = r+1
                    a_scaling = a_scaling/2
     
     
                edges_changes_test, reciprocity_changes_test, in_star_changes_test, out_star_changes_test, two_path_changes_test = np.array([]), np.array([]),np.array([]), np.array([]), np.array([])
                triangle_t_change_test, triangle_c_change_test, triangle_u_change_test, triangle_d_change_test = np.array([]), np.array([]),np.array([]), np.array([])
                sector_changes_test, geographic_changes_test, profit_changes_test = np.array([]) ,np.array([]), np.array([])
     
                for k in range(1,self.convergence_iteration):
                    sampling = self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration)
                    edges_changes_test = np.append(edges_changes_test,sampling[0])
                    reciprocity_changes_test = np.append(reciprocity_changes_test,sampling[1])
                    in_star_changes_test = np.append(in_star_changes_test,sampling[2])
                    out_star_changes_test = np.append(out_star_changes_test,sampling[3])
                    two_path_changes_test = np.append(two_path_changes_test,sampling[4])
                    triangle_t_change_test = np.append(triangle_t_change_test,sampling[5])
                    triangle_c_change_test = np.append(triangle_c_change_test,sampling[6])
                    triangle_u_change_test = np.append(triangle_u_change_test,sampling[7])
                    triangle_d_change_test = np.append(triangle_d_change_test,sampling[8])
                    sector_changes_test = np.append(sector_changes_test,sampling[9])
                    geographic_changes_test = np.append(geographic_changes_test,sampling[10])
                    profit_changes_test = np.append(profit_changes_test,sampling[11])
     
                M = np.matrix([edges_changes_test,reciprocity_changes_test,in_star_changes_test,out_star_changes_test,two_path_changes_test,triangle_t_change_test,
                               triangle_c_change_test,triangle_u_change_test,triangle_d_change_test,sector_changes_test,geographic_changes_test,profit_changes_test])
                SD = np.sqrt(M.var())
                E = np.mean(M)
     
                convergence = (E-np.mean(configuration))/SD
     
                if np.abs(convergence) < 0.11:
                    convergence_test = True
                else:
                    r = r-1
                    a_scaling = 0.005
     
     
            ntasks = 4
            chunk_size = int(self.convergence_iteration/ntasks)
     
            pool = multiprocessing.Pool()
            results_async = []
            for i in range(ntasks):
                results_async.append(pool.apply_async(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,)))
     
            hits = np.array(r.get() for r in results_async)
            print(hits) 
            return (theta,convergence)
    En gros, je veux valider mon modèle, donc je peux générer plusieurs échantillon d'une manière indépendante. Pour les besoins de mes calcules, pour chaque échantillon, j'ai besoin de récupérer le np.array (final_configuration), qui est sensé être dans le hits.

    Veuillez noter, que lorsque j'écris ceci:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    hits = [r.get() for r in results_async]
    Le code me renvoie l'erreur suivante:

    hits = [r.get() for r in results_async]
    File "C:\Python27\lib\multiprocessing\pool.py", line 567, in get
    raise self._value
    TypeError: 'numpy.ndarray' object is not callable
    Merci d'avance

  8. #8
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    Voilà le code en détail. J'ai une classe MCMC_MLE (simulation monte carlo),
    Vous fournissez un code certes mais il n'est ni complet (on ne peut pas reproduire, juste lire...) ni minimal.
    De toutes façons, multiprocessing devrait juste permettre d'accélérer (avec de la chance) le traitement donc vous devriez pouvoir faire fonctionner votre code "sans".
    i.e. à la place de:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
            pool = multiprocessing.Pool()
            results_async = []
            for i in range(ntasks):
                results_async.append(pool.apply_async(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,)))
     
            hits = np.array(r.get() for r in results_async)
    écrire:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
            results_async = []
            for i in range(ntasks):
                results_async.append(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,))
     
            hits = np.array(r for r in results_async)
    devrait fonctionner.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  9. #9
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Réponse
    Citation Envoyé par wiztricks Voir le message
    Vous fournissez un code certes mais il n'est ni complet (on ne peut pas reproduire, juste lire...) ni minimal.
    De toutes façons, multiprocessing devrait juste permettre d'accélérer (avec de la chance) le traitement donc vous devriez pouvoir faire fonctionner votre code "sans".
    i.e. à la place de:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
            pool = multiprocessing.Pool()
            results_async = []
            for i in range(ntasks):
                results_async.append(pool.apply_async(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,)))
     
            hits = np.array(r.get() for r in results_async)
    écrire:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
            results_async = []
            for i in range(ntasks):
                results_async.append(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,))
     
            hits = np.array(r for r in results_async)
    devrait fonctionner.

    - W
    Le code est extrêment long et compliqué, ça ne serait pas possible de l'exécuter. Ce sont deux méthodes qui appartiennent à la même classe comme je vous ai dit. Le code fonctionne sans ce multiprocessing. En faisant ce que vous avez suggérer:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
     hits = [r for r in results_async]
    je récupère cet objet:
    [<multiprocessing.pool.ApplyResult object at 0x03628DD0>]
    Je veux accéder aux éléments de mon np.array de la méthode Metropolis_Sampling, c'est ça mon soucis.

  10. #10
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    En faisant ce que vous avez suggérer:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
     hits = [r for r in results_async]
    je récupère cet objet: Je veux accéder aux éléments de mon np.array de la méthode Metropolis_Sampling, c'est ça mon soucis.
    Ça c'est parce que vous avez laissé pool.apply_async au lieu d'exécuter cela de façon séquentielle.
    note: si vous ne savez pas traiter le retour de vos fonctions/méthodes sans multiprocessing, vous ne saurez pas mieux avec...

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  11. #11
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Réponse
    Citation Envoyé par wiztricks Voir le message
    Ça c'est parce que vous avez laissé pool.apply_async au lieu d'exécuter cela de façon séquentielle.
    note: si vous ne savez pas traiter le retour de vos fonctions/méthodes sans multiprocessing, vous ne saurez pas mieux avec...

    - W
    Si, je sais gérer le retour de mes méthodes. Je travaille sur ce code depuis deux mois et j'ai eu tous les retours. J'ai executé le multiprocessing sur un exemple simple. Je reçois le retour escompté. Ce que j'attendais de ce code, c'est d'avoir N np.array final_configuration, au nombre de la simulation. Pourriez vous m'éclaircir mieux?

  12. #12
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    J'ai executé le multiprocessing sur un exemple simple. Je reçois le retour escompté. Ce que j'attendais de ce code, c'est d'avoir N np.array final_configuration, au nombre de la simulation.
    Pourriez vous m'éclaircir mieux?
    Je vous ai déjà proposé un test pour (déjà) vérifier cela...

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  13. #13
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Réponse
    Citation Envoyé par wiztricks Voir le message
    Je vous ai déjà proposé un test pour (déjà) vérifier cela...

    - W
    Quel test? Execution séquentielle? Ca donne N np.array comme je vous ai dit. Ou vous parlez d'un autre test?

  14. #14
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    Quel test? Execution séquentielle? Ca donne N np.array comme je vous ai dit. Ou vous parlez d'un autre test?
    post #8:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    results_async = []
            for i in range(ntasks):
                results_async.append(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,))
     
            hits = np.array(r for r in results_async)
    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  15. #15
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Réponse
    Citation Envoyé par wiztricks Voir le message
    post #8:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    results_async = []
            for i in range(ntasks):
                results_async.append(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration), (chunk_size,))
     
            hits = np.array(r for r in results_async)
    - W
    Je vous ai déjà repondu. Ca marche, mais l'objet récupéré j'ai pas su l'exploiter pour extraire les np.array.

  16. #16
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    Je vous ai déjà repondu. Ca marche, mais l'objet récupéré j'ai pas su l'exploiter pour extraire les np.array.
    Ce qui a été votre réponse #9 et comme il n'y a que .apply_async qui retourne un ApplyResult, je vous ai demandé de les supprimer dans la réponse #10...
    note: le but étant de voir ces fameux np.array....

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  17. #17
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Réponse
    Citation Envoyé par wiztricks Voir le message
    Ce qui a été votre réponse #9 et comme il n'y a que .apply_async qui retourne un ApplyResult, je vous ai demandé de les supprimer dans la réponse #10...
    note: le but étant de voir ces fameux np.array....

    - W
    Mais si je vais enlever le pool ca sera en séquentiel. Alors que je veux accélérer les calculs.

  18. #18
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 679
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 679
    Par défaut
    Citation Envoyé par hazem2410 Voir le message
    Mais si je vais enlever le pool ca sera en séquentiel. Alors que je veux accélérer les calculs.
    Le but du test (comme mentionné plusieurs fois) est de vérifier que la fonction appelée retourne bien un np.array (et non un generator) comme vous l'indiquiez dans votre premier message.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  19. #19
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Test
    Citation Envoyé par wiztricks Voir le message
    Le but du test (comme mentionné plusieurs fois) est de vérifier que la fonction appelée retourne bien un np.array (et non un generator) comme vous l'indiquiez dans votre premier message.

    - W
    En effet, en faisant ce test (pour 2 iteration), voici mon retour hits:

    [array([ 70. , 26. , 216. , 213. ,
    -266. , 790. , 816. , 790. ,
    791. , 7. , 4. , 1293.50051746]), array([ 70. , 27. , 215. , 213. ,
    -258. , 788. , 797. , 789. ,
    787. , 5. , 4. , 1401.40437835])]

    voici le code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
            for i in range(ntasks):
                results_async.append(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration))
     
            hits = [r for r in results_async]
            print(hits)
    Est ce que la syntaxe est correction de mon pool? car je ne comprends pas pourquoi ça donne un autre objet.

  20. #20
    Membre confirmé
    Inscrit en
    Novembre 2010
    Messages
    163
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 163
    Par défaut Solution
    Citation Envoyé par hazem2410 Voir le message
    En effet, en faisant ce test (pour 2 iteration), voici mon retour hits:




    voici le code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
            for i in range(ntasks):
                results_async.append(self.Metropolis_Sampling(theta, Change_Statistics.StatisticMeasure.Network, configuration))
     
            hits = [r for r in results_async]
            print(hits)
    Est ce que la syntaxe est correction de mon pool? car je ne comprends pas pourquoi ça donne un autre objet.
    En effet, la syntaxe et la structure sont fausses. J'ai dû essayer des codes simples pour comprendre. Premièrement, on ne peut pas mapper la méthode de la même classe, il faut la définir comme function globale, c'est ainsi que j'ai fait:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    def sample_multiple(theta, network, configuration,samples_partial):
     
        Statistics = constructeur 1
        test = constructeur 2
        return [test.Metropolis_Sampling(theta, network, configuration) for i in range(samples_partial)]
    Ensuite, le pool ne prend pas la méthode à argument multiple, ainsi j'ai dû passé par la méthode partielle, et mon code devient:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    from functools import partial
     
    ntasks = 1
    chunk_size = int(self.convergence_iteration/ntasks)
     
    pool = multiprocessing.Pool()
    func = partial(sample_multiple, theta, Change_Statistics.StatisticMeasure.Network, configuration)
    results_async = [pool.apply_async(func, (chunk_size,)) for i in range(ntasks)]
     
    hits = [r.get() for r in results_async]
    Ainsi, je récupère mes np.array comme pour l'éxécution en série

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. multiprocessing python cluster
    Par StingerBell dans le forum Général Python
    Réponses: 4
    Dernier message: 25/04/2016, 10h21
  2. multiprocessing python 2.6
    Par asmaeH dans le forum Général Python
    Réponses: 5
    Dernier message: 24/07/2012, 16h52
  3. Lire une figure matlab avec python
    Par Bénarès77 dans le forum Calcul scientifique
    Réponses: 1
    Dernier message: 17/05/2012, 18h14
  4. lire des fichiers .mat avec python
    Par diallokoula dans le forum Calcul scientifique
    Réponses: 4
    Dernier message: 14/01/2011, 13h25
  5. Lire un fichier XML avec Python
    Par eyquem dans le forum Général Python
    Réponses: 2
    Dernier message: 19/12/2007, 13h54

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo