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

Algorithmes et structures de données Discussion :

Une IA plus artificielle qu'intelligente [Python]


Sujet :

Algorithmes et structures de données

  1. #1
    Futur Membre du Club
    Homme Profil pro
    aucune
    Inscrit en
    Juillet 2020
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Juillet 2020
    Messages : 15
    Points : 6
    Points
    6
    Par défaut Une IA plus artificielle qu'intelligente [Python]
    Bonjour,
    J'ai essayer de coder une IA a apprentissage par renforcement qui apprend a jouer au morpion elle s'appelle Amna (Car Amna = A.Mna. (En Xhosa) = AI (En Anglais) = IA (En francais) OUI je suis parti loin), pas si compliquer dans l'idée, mais comme c'est la première IA par renforcement que je code, j'ai surement fait un peut n'importe quoi...
    J'ai coder assez clairement, j'ai mis des commentaires partout, c'est pas si dure a comprendre ce que j'ai fait.
    Donc le problème c'est que mon IA est pas très I, même au bout de 100 000 partie, ce qui me parait très bizarre pour apprendre le morpion...
    Donc j'ai surement fait des erreurs de logiques...
    Il y a surement des erreur dans :
    - Ma façon de récompenser
    - Si c'est pas dans ma façon de récompenser c'est dans ma BackPropagation
    - Si c'est pas dans la BackPropagation c'est dans la façon dont l'IA fait ses choix (Elle les fait par rapport a ce que l'adversaire viens de jouer et pas par rapport a ce qu'il a jouer au long de la partie)
    - C'est peut être dans tout a la fois...
    - Et elle a un bug que je ne comprend pas, le plateau ce rempli dans des moment ou il ne devrai pas être remplis

    Donc c'est surement n'importe quoi mon code mais le voici pour m'aider a le corriger et pour que j’apprenne de mes erreurs :
    Code Python : 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
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    ###############################################################################
    # Amna
    ###############################################################################
     
    """
    N = Niveau (Répondre à N) (De l'état N à ...)
    xp = Experience (Data / Données / Cerveau)
    P = player (La personne qui jou en ce momant)
     
    """
     
    ### INI ###
    terrain = list([0,0,0,0,0,0,0,0,0]) #Map morpion
    # Experience / Cerveau
    xp = list([])
    for a in range(10):
        xp.append([])
        for b in range(9):
            xp[a].append([(b+1),0])
     
    """
    Map morpion :
    |1|2|3|
    |4|5|6|
    |7|8|9|
     
    Plan de la base de donnée de l'IA / Cerveau :
    [
    Si le joueur adverse choisi 0 (Tu jou en premier) : [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    Si le joueur adverse choisi 1 : [[(Alors jouer 1)>1, (Niveau d'envie de jouer 1)>0], [(Alors jouer 2)>2, (Niveau d'envie de jouer 2)>0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    Si le joueur adverse choisi 2 : [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]]
    ]
    """
    ### IMP ###
    import random
    import os #Pour la commande cls de system pour clear l'affichage pour le chargement
     
    ### DEF ###
    def choisir(N):
        randomlist = list([]) #Liste pour tout les choix qui ont la même valleurs qu'il faudra départager grance a l'aleatoire
        best = list([0,0])
        choix = xp[N].copy() #Copie de la base de donnée pour ne pas la modifier
        for i in range(9): # Tri des choix possible
            if terrain[8-i] == 1 or terrain[8-i] == 2:
                choix.remove(choix[8-i]) #Suppretion des choix impossible
        # Recherche du meilleur choix
        for i in range(len(choix)):
            if choix[i][1] > best[1]:
                best = choix[i]
                randomlist = list([])
            if choix[i][1] == best[1]:
                randomlist.append(choix[i])
        # Si il y a confrontation alors place au random
        if len(randomlist) > 0:
            best = randomlist[random.randint(0,(len(randomlist)-1))]
        # Return le nom de la case (entre 1 et 9)
        return best[0]
     
    def choisirALL(): #Pour choisir premier tour
        most = list([])
        for N in range(10):
            randomlist = list([])
            best = list([0,0])
            choix = xp[N].copy()
            for i in range(9): # Tri des choix possible
                if terrain[8-i] == 1 or terrain[8-i] == 2:
                    choix.remove(choix[8-i])
            # Recherche du meilleur choix
            for i in range(len(choix)):
                if choix[i][1] > best[1]:
                    best = choix[i]
                    randomlist = list([])
                if choix[i][1] == best[1]:
                    randomlist.append(choix[i])
            # Si il y a confrontation alors place au random
            if len(randomlist) > 0:
                best = randomlist[random.randint(0,(len(randomlist)-1))]
            # Ajoute a la liste des meilleur
            most.append(best)
        choix = most
        for i in range(len(choix)):
            if choix[i][1] > best[1]:
                best = choix[i]
                randomlist = list([])
            if choix[i][1] == best[1]:
                randomlist.append(choix[i])
        # Si il y a confrontation alors place au random
        if len(randomlist) > 0:
            best = randomlist[random.randint(0,(len(randomlist)-1))]
        # Return le nom de la case (entre 1 et 9)
        return best[0]
     
     
    def Gagner():
        global terrain
        if ((terrain[0]==1 and terrain[1]==1 and terrain[2]==1) or
            (terrain[0]==1 and terrain[4]==1 and terrain[8]==1) or
            (terrain[0]==1 and terrain[3]==1 and terrain[6]==1) or
            (terrain[1]==1 and terrain[4]==1 and terrain[7]==1) or
            (terrain[2]==1 and terrain[5]==1 and terrain[8]==1) or
            (terrain[2]==1 and terrain[4]==1 and terrain[6]==1) or
            (terrain[3]==1 and terrain[4]==1 and terrain[5]==1) or
            (terrain[6]==1 and terrain[7]==1 and terrain[8]==1)):
            return True
        elif ((terrain[0]==2 and terrain[1]==2 and terrain[2]==2) or
             (terrain[0]==2 and terrain[4]==2 and terrain[8]==2) or
             (terrain[0]==2 and terrain[3]==2 and terrain[6]==2) or
             (terrain[1]==2 and terrain[4]==2 and terrain[7]==2) or
             (terrain[2]==2 and terrain[5]==2 and terrain[8]==2) or
             (terrain[2]==2 and terrain[4]==2 and terrain[6]==2) or
             (terrain[3]==2 and terrain[4]==2 and terrain[5]==2) or
             (terrain[6]==2 and terrain[7]==2 and terrain[8]==2)):
             return True
        else:
            return False
    #############
    # Algorytme #
    #####################################
     
    learningRate = 0.01 #Learning rate pété
    long = 1000000 #Nombre de partie d'apprentissage
    barre = list([]) #Barre de chargement
     
    for app in range(long):
        if (app/long)*100 == int((app/long)*100):
            os.system("cls")
            barre.append("|")
            print("Apprentisage :",int((app/long)*100),"% /",app,"parties jouées")
            print("---------------------------------------------------------------------------------------------") #Top la classe XD
            print(''.join(barre))
            print("---------------------------------------------------------------------------------------------")
            print("")
            print("Learning rate :", learningRate)
            print("")
            print(terrain[0],terrain[1],terrain[2])
            print(terrain[3],terrain[4],terrain[5])
            print(terrain[6],terrain[7],terrain[8])
            print("")
            for i in range(9): #Montre les données
                print(xp[i])
        """
        #Fonction d'avencement du learning rate durant la partie
        if learningRate < 1:
            learningRate += learningRate/(100000)
        elif learningRate > 1:
            learningRate = 1
        """
        historique = list([]) #Historique de la partie pour la backpropagation
        terrain = list([0,0,0,0,0,0,0,0,0]) #Nettoyage du terrain
        P = 1 #Joueur 1 commence
        ### Démarage de la partie ###
        for i in range(10):
            if sum(terrain) > 12: #Anti bug du terrain remplis
                """
                print("BUG : Terrain rempli (Non resolu)")
                print(terrain[0],terrain[1],terrain[2])
                print(terrain[3],terrain[4],terrain[5])
                print(terrain[6],terrain[7],terrain[8])
                """
                break
            if random.random() > learningRate: #Esay de faire quelque chose avec le learning rate
                choix = xp[0].copy()
                for i in range(9): # Tri des choix possible
                    if terrain[8-i] == 1 or terrain[8-i] == 2:
                        choix.remove(choix[8-i])
                choix = choix[random.randint(0,(len(choix)-1))][0] #Choix aléatoire pour cartographier le jeu
            else:
                if len(historique) > 0: #Savoir si on jou en premier ou pas
                    choix = choisir(historique[-1])
                else:
                    choix = choisirALL()
            historique.append(choix) #Sauvegarde dans l'historique
            if P == 1: #Switch entre joueur 1 et 2
                terrain[choix-1] = 1
            elif P == -1:
                terrain[choix-1] = 2
            P *= -1
            # System de reward surement foireux
            if Gagner():
                xp[historique[-2]-1][historique[-1]-1][1] = xp[historique[-2]-1][historique[-1]-1][1]+learningRate*(5)
                xp[historique[-3]-1][historique[-2]-1][1] = xp[historique[-3]-1][historique[-2]-1][1]+learningRate*(-5)
                xp[historique[-4]-1][historique[-3]-1][1] = xp[historique[-4]-1][historique[-3]-1][1]+learningRate*(xp[historique[-2]-1][historique[-1]-1][1]-xp[historique[-4]-1][historique[-3]-1][1])
                xp[historique[-5]-1][historique[-4]-1][1] = xp[historique[-5]-1][historique[-4]-1][1]+learningRate*(xp[historique[-3]-1][historique[-2]-1][1]-xp[historique[-5]-1][historique[-4]-1][1])
                if not len(historique) > 5: break
                xp[historique[-6]-1][historique[-5]-1][1] = xp[historique[-6]-1][historique[-5]-1][1]+learningRate*(xp[historique[-4]-1][historique[-3]-1][1]-xp[historique[-6]-1][historique[-5]-1][1])
                if not len(historique) > 6: break
                xp[historique[-7]-1][historique[-6]-1][1] = xp[historique[-7]-1][historique[-6]-1][1]+learningRate*(xp[historique[-5]-1][historique[-4]-1][1]-xp[historique[-7]-1][historique[-6]-1][1])
                if not len(historique) > 7: break
                xp[historique[-8]-1][historique[-7]-1][1] = xp[historique[-8]-1][historique[-7]-1][1]+learningRate*(xp[historique[-6]-1][historique[-5]-1][1]-xp[historique[-8]-1][historique[-7]-1][1])
                if not len(historique) > 8: break
                xp[historique[-9]-1][historique[-8]-1][1] = xp[historique[-9]-1][historique[-8]-1][1]+learningRate*(xp[historique[-7]-1][historique[-6]-1][1]-xp[historique[-9]-1][historique[-8]-1][1])
                if not len(historique) > 9: break
                xp[historique[-10]-1][historique[-9]-1][1] = xp[historique[-10]-1][historique[-9]-1][1]+learningRate*(xp[historique[-8]-1][historique[-7]-1][1]-xp[historique[-10]-1][historique[-9]-1][1])
                break
            if i == 9: #Egalité
                xp[historique[-2]-1][historique[-1]-1][1] += learningRate*(0)
                xp[historique[-3]-1][historique[-2]-1][1] += learningRate*(0)
                xp[historique[-4]-1][historique[-3]-1][1] = xp[historique[-4]-1][historique[-3]-1][1]+learningRate*(xp[historique[-2]-1][historique[-1]-1][1]-xp[historique[-4]-1][historique[-3]-1][1])
                xp[historique[-5]-1][historique[-4]-1][1] = xp[historique[-5]-1][historique[-4]-1][1]+learningRate*(xp[historique[-3]-1][historique[-2]-1][1]-xp[historique[-5]-1][historique[-4]-1][1])
                xp[historique[-6]-1][historique[-5]-1][1] = xp[historique[-6]-1][historique[-5]-1][1]+learningRate*(xp[historique[-4]-1][historique[-3]-1][1]-xp[historique[-6]-1][historique[-5]-1][1])
                xp[historique[-7]-1][historique[-6]-1][1] = xp[historique[-7]-1][historique[-6]-1][1]+learningRate*(xp[historique[-5]-1][historique[-4]-1][1]-xp[historique[-7]-1][historique[-6]-1][1])
                xp[historique[-8]-1][historique[-7]-1][1] = xp[historique[-8]-1][historique[-7]-1][1]+learningRate*(xp[historique[-6]-1][historique[-5]-1][1]-xp[historique[-8]-1][historique[-7]-1][1])
                xp[historique[-9]-1][historique[-8]-1][1] = xp[historique[-9]-1][historique[-8]-1][1]+learningRate*(xp[historique[-7]-1][historique[-6]-1][1]-xp[historique[-9]-1][historique[-8]-1][1])
                xp[historique[-10]-1][historique[-9]-1][1] = xp[historique[-10]-1][historique[-9]-1][1]+learningRate*(xp[historique[-8]-1][historique[-7]-1][1]-xp[historique[-10]-1][historique[-9]-1][1])
                break
    print("")
    print("A vous de jouer")
    print("")
    print("0 1 2")
    print("3 4 5")
    print("6 7 8")
    print("")
    while True:
        terrain = list([0,0,0,0,0,0,0,0,0])
        for i in range(9):
            print("Etat du jeu :")
            print(terrain[0],terrain[1],terrain[2])
            print(terrain[3],terrain[4],terrain[5])
            print(terrain[6],terrain[7],terrain[8])
            print("")
            ch = int(input("Choix : "))
            terrain[ch] = 1
            if Gagner():
                print("Vous avez gagner :")
                print(terrain[0],terrain[1],terrain[2])
                print(terrain[3],terrain[4],terrain[5])
                print(terrain[6],terrain[7],terrain[8])
                break
            terrain[choisir(ch)-1] = 2
            if Gagner():
                print("Vous avez perdu :")
                print(terrain[0],terrain[1],terrain[2])
                print(terrain[3],terrain[4],terrain[5])
                print(terrain[6],terrain[7],terrain[8])
                break
            print("")
        print("-------------------------")
    Il y a surement des fautes de français partout, je m'en excuse

    Si vous ne comprenez pas quelque lignes, dite le moi je vous expliquerais, si vous ne comprenez rien manger votre chapeau (Attention l’abus de chapeau est dangereux pour la santé)

    Merci de votre aide

  2. #2
    Membre actif
    Homme Profil pro
    Développeur de jeux vidéo
    Inscrit en
    Février 2013
    Messages
    317
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations professionnelles :
    Activité : Développeur de jeux vidéo

    Informations forums :
    Inscription : Février 2013
    Messages : 317
    Points : 233
    Points
    233
    Par défaut
    Avec une grille de 3 x 3 le jeu est plié en huit tests.
    ça peut aider ?
    Savoir pour comprendre et vice versa.

  3. #3
    Futur Membre du Club
    Homme Profil pro
    aucune
    Inscrit en
    Juillet 2020
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Juillet 2020
    Messages : 15
    Points : 6
    Points
    6
    Par défaut
    Citation Envoyé par valentin03 Voir le message
    Avec une grille de 3 x 3 le jeu est plié en huit tests.
    ça peut aider ?
    Merci de ta réponse mais je ne veut pas une IA rapide et optimiser, je veut juste apprendre a coder une IA a apprentissage par renforcement...

  4. #4
    Futur Membre du Club
    Homme Profil pro
    aucune
    Inscrit en
    Juillet 2020
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Juillet 2020
    Messages : 15
    Points : 6
    Points
    6
    Par défaut
    Amna avance avec les 5 heures que je lui est consacré mais j'ai un problème pour faire la backpropagation

    Je veut une fonction avec une courbe qui tan vers 0 et puis vers 10 comme la sigmoïde tan vers 0 et 1 mais pas vraiment en fonction ou alors avec le moyen de retrouver le nombre de départ:

    Pas vraiment une fonction :
    A = [-∞;+∞]
    x tan vers 0 et 10
    Code Python : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    while True:
       x += LaFonctionPasFonction(A,x)
    Un grand merci a celui qui trouve LaFonctionPasFonction !


    le moyen de retrouver le nombre de départ:
    x = [-∞;+∞]

    a = 1/(1+exp(-x))
    -x = ?

    Un grand merci a celui qui trouve le "?" !
    (J'ai un peut chercher sur internet et dans ma tête mais je crois que je suis con... En plus ça m'a pas l'aire trop complexe...)



    Voila l’avancement de Amna :
    Code Python : 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
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
     
    ###############################################################################
    # Amna
    ###############################################################################
     
    """
    N = Niveau (Répondre à N) (De l'état N à ...)
    xp = Experience (Data / Données / Cerveau)
    P = player (La personne qui jou en ce momant)
     
    """
     
    ### INI ###
    terrain = list([0,0,0,0,0,0,0,0,0]) #Map morpion
    # Experience / Cerveau
    xp = list([])
    for i in range(2):
        xp.append([])
        for a in range(10):
            xp[i].append([])
            for b in range(9):
                xp[i][a].append([(b+1),5])
     
    """
    Map morpion :
    |1|2|3|
    |4|5|6|
    |7|8|9|
     
    Plan de la base de donnée de l'IA / Cerveau TOUT BEAU et avec 2 partie du cerveau :
    [[
    Si le joueur adverse choisi 0 (Tu jou en premier) : [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    Si le joueur adverse choisi 1 : [[(Alors jouer 1)>1, (Niveau d'envie de jouer 1)>0], [(Alors jouer 2)>2, (Niveau d'envie de jouer 2)>0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    Si le joueur adverse choisi 2 : [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]]
    ][
    Si le joueur adverse choisi 0 (Tu jou en premier) : [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    Si le joueur adverse choisi 1 : [[(Alors jouer 1)>1, (Niveau d'envie de jouer 1)>0], [(Alors jouer 2)>2, (Niveau d'envie de jouer 2)>0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    Si le joueur adverse choisi 2 : [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]],
    [[1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 0], [7, 0], [8, 0], [9, 0]]
    ]]
    """
    ### IMP ###
    import random
    from os import system #Pour la commande cls de system pour clear l'affichage pour le chargement
    from math import exp #Pour la fonction Sigmoïde
     
    ### DEF ###
    def sigmoid(x): #Magnifique
        return 1/(1+exp(-x))
     
    def choisir(J,N): #SO smart :)
        global learningRate
        global xp
        J -= 1 #Pour que ça donne la possition dans la liste [J]
        S = 0 #Somme
        temp = 0 #Valleur d'ajustement pour la proba
        best = list([0,0]) #Pour l'issue rnd = 100 (P=1%)
        for i in range(len(xp[J][N])):
            S += xp[J][N][i][1]
        rnd = random.random()*100
        for i in range(len(xp[J][N])):
            if rnd >= temp and rnd < temp+xp[J][N][i][1]/S*100/(xp[J][N][i][1]/learningRate):
                return xp[J][N][i][1]
            temp += xp[J][N][i][1]/S*100/(xp[J][N][i][1]/learningRate)
            if xp[J][N][i][1]/S*100/(xp[J][N][i][1]/learningRate) > best[0]:
                best[0] = xp[J][N][i][1]/S*100/(xp[J][N][i][1]/learningRate)
                best[1] = xp[J][N][i][1]
        #print("/!\ Erreur de choix /!\ => Issue possible : rnd = 100")
        if rnd == 100:
            #print("Issue confirmée : rnd = 100")
            return best[1]
        print("/!\CRITICAL/!\ => Issue NON confirmée : rnd n'est pas égale a 100")
        return best[1]
     
    """
    Ruines :
     
    def choisir(N):
        randomlist = list([]) #Liste pour tout les choix qui ont la même valleurs qu'il faudra départager grance a l'aleatoire
        best = list([0,0])
        choix = xp[N].copy() #Copie de la base de donnée pour ne pas la modifier
        for i in range(9): # Tri des choix possible
            if terrain[8-i] == 1 or terrain[8-i] == 2:
                choix.remove(choix[8-i]) #Suppretion des choix impossible
        # Recherche du meilleur choix
        for i in range(len(choix)):
            if choix[i][1] > best[1]:
                best = choix[i]
                randomlist = list([])
            if choix[i][1] == best[1]:
                randomlist.append(choix[i])
        # Si il y a confrontation alors place au random
        if len(randomlist) > 0:
            best = randomlist[random.randint(0,(len(randomlist)-1))]
        # Return le nom de la case (entre 1 et 9)
        return best[0]
     
    def choisirALL(): #Pour choisir premier tour
        most = list([])
        for N in range(10):
            randomlist = list([])
            best = list([0,0])
            choix = xp[N].copy()
            for i in range(9): # Tri des choix possible
                if terrain[8-i] == 1 or terrain[8-i] == 2:
                    choix.remove(choix[8-i])
            # Recherche du meilleur choix
            for i in range(len(choix)):
                if choix[i][1] > best[1]:
                    best = choix[i]
                    randomlist = list([])
                if choix[i][1] == best[1]:
                    randomlist.append(choix[i])
            # Si il y a confrontation alors place au random
            if len(randomlist) > 0:
                best = randomlist[random.randint(0,(len(randomlist)-1))]
            # Ajoute a la liste des meilleur
            most.append(best)
        choix = most
        for i in range(len(choix)):
            if choix[i][1] > best[1]:
                best = choix[i]
                randomlist = list([])
            if choix[i][1] == best[1]:
                randomlist.append(choix[i])
        # Si il y a confrontation alors place au random
        if len(randomlist) > 0:
            best = randomlist[random.randint(0,(len(randomlist)-1))]
        # Return le nom de la case (entre 1 et 9)
        return best[0]
    """
     
    def Gagner(J):
        global terrain
        if ((terrain[0]==J and terrain[1]==J and terrain[2]==J) or
            (terrain[0]==J and terrain[4]==J and terrain[8]==J) or
            (terrain[0]==J and terrain[3]==J and terrain[6]==J) or
            (terrain[1]==J and terrain[4]==J and terrain[7]==J) or
            (terrain[2]==J and terrain[5]==J and terrain[8]==J) or
            (terrain[2]==J and terrain[4]==J and terrain[6]==J) or
            (terrain[3]==J and terrain[4]==J and terrain[5]==J) or
            (terrain[6]==J and terrain[7]==J and terrain[8]==J)):
            return True
        else:
            return False
    #############
    # Algorytme #
    #####################################
     
    learningRate = 0.01
    long = 100000 #Nombre de partie d'apprentissage
    barre = list([]) #Barre de chargement
     
    for app in range(long):
        learingRate = sigmoid(app/100) #WaW
        if (app/long)*100 == int((app/long)*100): #View
            os.system("cls")
            barre.append("|")
            print("Apprentisage :",int((app/long)*100),"% /",app,"parties jouées")
            print("---------------------------------------------------------------------------------------------") #Top la classe :)
            print(''.join(barre))
            print("---------------------------------------------------------------------------------------------")
            print("")
            print("Learning rate :", learningRate)
            print("")
            print(terrain[0],terrain[1],terrain[2])
            print(terrain[3],terrain[4],terrain[5])
            print(terrain[6],terrain[7],terrain[8])
            print("")
            for i in range(9): #Montre les données
                print(xp[i])
        historique = list([]) #Historique de la partie pour la backpropagation
        terrain = list([0,0,0,0,0,0,0,0,0]) #Nettoyage du terrain
        P = 1 #Joueur 1 commence
        ### Démarage de la partie ###
        for i in range(10):
            #Jeu#
            if len(historique) > 0:
                historique.append(choisir(P,historique[-1])) #Attention ne pas faire le con : ce historique[-1] et pas pareil que
                terrain[historique[-1]-1] = P                  #Celui la
            else:
                historique.append(choisir(P,0)) #P est forcément 1 mais on sait jamais si je suis fou et que g envi que le joueur 2 jou en premier XD
                terrain[historique[0]-1] = P
            #Inversement du P#
            if P == 1:
                P = 2
            else:
                P = 1
            #backpropag#
            if gagner(1):
                """
                Je veut que l'envie evolue avec une fonction sigmoid qui va de 0.00000001 a 9.999... Donc la souce (Dernier choix) = sigmoid(x) (x += 1 a chaque fois que l'ia fini avec ce coup) et que le coup jouer avent evolu de sigmoid(sigmoid(x)) et avent en sigmoid(sigmoid(sigmoid(x)))...
                """
                """ Y'a mieux
                if xp[0][historique[-3]][historique[-2]] + learningRate > 10: #Bisou
                    xp[0][historique[-3]][historique[-2]] = 10
                else:
                    xp[0][historique[-3]][historique[-2]] += learningRate
     
                if xp[0][historique[-3]][historique[-2]] - learningRate < 0: #Claque
                    xp[0][historique[-3]][historique[-2]] = 0
                else:
                    xp[0][historique[-3]][historique[-2]] -= learningRate
                """

    Merci pour votre aide <3
    Désolé pour le français mais ça avait qu'a être plus logique

  5. #5
    Membre éprouvé Avatar de balkany
    Homme Profil pro
    Touriste
    Inscrit en
    Juillet 2017
    Messages
    346
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Touriste

    Informations forums :
    Inscription : Juillet 2017
    Messages : 346
    Points : 977
    Points
    977
    Par défaut
    Que tu aies du mal avec le français, soit, mais fais au moins un effort avec les symboles mathématiques.
    Là on ne sait pas ce que sont A, x et a : des intervalles ? des réels ?
    Si tu veux une fonction qui tend vers 0 en -∞ et en 10 en +∞, il te suffit de multiplier la sigmoïde par 10.
    Si tu veux x tel que a = 1/(1+exp(-x)), alors x = - ln(1/a - 1).

  6. #6
    Futur Membre du Club
    Homme Profil pro
    aucune
    Inscrit en
    Juillet 2020
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Juillet 2020
    Messages : 15
    Points : 6
    Points
    6
    Par défaut
    Citation Envoyé par balkany Voir le message
    Que tu aies du mal avec le français, soit, mais fais au moins un effort avec les symboles mathématiques.
    Là on ne sait pas ce que sont A, x et a : des intervalles ? des réels ?
    Si tu veux une fonction qui tend vers 0 en -∞ et en 10 en +∞, il te suffit de multiplier la sigmoïde par 10.
    Si tu veux x tel que a = 1/(1+exp(-x)), alors x = - ln(1/a - 1).
    Bonjour,

    Désolé du manque d'info mais merci de votre réponse

    Un intervalle quelconque
    Des nombres Rationnel

    J'avais déjà vu cette réponse mais je n'arrive pas a l'appliquer dans python car ln() n'est pas compris dans le module math donc j'avais cherché et j'ai vu que en fait ln() c'est log(). Donc log() est bien compris dans le module math mais je n'arrive pas a m'en servir... Il faut une base de je sait pas quoi... Je ne suis pas aller aussi loin en math...Je ne suis quand seconde (avec un aussi mauvais en français oui )...J'ai peut être trop d’ambition...Mais je vais réussir !

    Encore désolé pour toutes mes fautes finalement...

  7. #7
    Membre éprouvé Avatar de balkany
    Homme Profil pro
    Touriste
    Inscrit en
    Juillet 2017
    Messages
    346
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Touriste

    Informations forums :
    Inscription : Juillet 2017
    Messages : 346
    Points : 977
    Points
    977
    Par défaut
    Tu as peut-être effectivement les yeux plus gros que le ventre
    Il va falloir que tu patientes un ou deux ans, ou alors il faut que tu t'attaques sérieusement au programme de terminale (je ne crois pas qu'on voit les exponentielles et logarithmes en première, peut-être que si…)

    ln est le logarithme népérien, qui est dit de base e car ln(e) = 1.
    D'une manière générale, un logarithme noté log est de base a, si log(a) = 1.
    Voir https://fr.wikipedia.org/wiki/Logarithme_naturel

    Quant à tes nombres, je doute qu'ils soient seulement rationnels, car le logarithme est une fonction d'une variable réelle à valeurs réelles : ln(2), par exemple, est irrationnel(1), alors que 2 est rationnel.
    Voir https://fr.wikipedia.org/wiki/Nombre_r%C3%A9el

    --
    (1) : ce qui ne semble pas du tout évident à montrer : voir http://www.les-mathematiques.net/pho...ad.php?2,56404, si tu veux t'amuser

  8. #8
    Futur Membre du Club
    Homme Profil pro
    aucune
    Inscrit en
    Juillet 2020
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Juillet 2020
    Messages : 15
    Points : 6
    Points
    6
    Par défaut
    mmmh...
    J'ai mal a la tête...

    Peut on pas retrouver x en un calcule compatible avec python ?

    En fait mon idée c'est ça :
    envie = % d'activation / envie de faire ce choix (Par exemple jouer en case N°5 au dernier tour)

    for i in range(Gagne avec ce coup):
    envie = 1/(1+exp(-i))

    Je ne veut pas avoir i dans ma base de donnée car ... eeeeh ... si il y a une manière plus optimisé c'est mieux...

    Donc je voudrait :
    A chaque fois que l'IA gagne avec ce coup :

    x = - ln(1/envie - 1). #On retrouve X
    envie = 1/(1+exp(-(x+1))) #On avance de 1 dans la fonction sigmoïde (On tan vers 10)

    Ou a chaque fois que l'IA perd avec ce coup :

    x = - ln(1/envie - 1). #On retrouve X
    envie = 1/(1+exp(-(x-1))) #On recule de 1 dans la fonction sigmoïde (On tan vers 0)


    Sinon je fait pas chier et je met le "i" dans la base de donnée (Pour compter le nombre de fois que l'IA a réussit a finir avec ce coup)

    En fait tout ce que je veut faire c'est :
    Si l'IA gagne avec un coup alors l'envie de jouer ce coup tan vars 10
    Si l'IA perd avec un coup alors l'envie de jouer ce coup tan vars 0

    Je sait pas si il y a pas une autre méthode moins énervé que les fonction logarithmique, sigmoïdite...

  9. #9
    Membre éprouvé Avatar de balkany
    Homme Profil pro
    Touriste
    Inscrit en
    Juillet 2017
    Messages
    346
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Touriste

    Informations forums :
    Inscription : Juillet 2017
    Messages : 346
    Points : 977
    Points
    977
    Par défaut
    Ce calcul est évidemment compatible avec python, comme avec tout langage qui dispose d'une bibliothèque mathématique : l'exponentielle et le logarithme en font toujours partie.
    Tu fais d'ailleurs l'import de l'exponentielle dans ton code, donc pourquoi ne pourrais-tu pas faire celui du logarithme ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    $ python -c 'from math import log; y=0.9; x=-log(1/y-1); print(x)'
    2.197224577336219
    $
    Après je ne connais pas bien python, ni l'apprentissage d'IA, donc je ne vais pas m'aventurer plus loin là-dedans…

  10. #10
    Futur Membre du Club
    Homme Profil pro
    aucune
    Inscrit en
    Juillet 2020
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Juillet 2020
    Messages : 15
    Points : 6
    Points
    6
    Par défaut
    J'ai trouver plus simple !
    Hier soir, je me suis dit "C'est maintenant que t'a de l'inspiration donc réfléchi !" et devine quoi, j'ai réfléchi !
    Donc j'ai trouver en 15min :
    B => but (Tan vers but)
    E => État actuel (Envie/Activation actuelle)
    R => Learning rate (Vitesse)

    E = E+((B-E)/R)


    Et voila ! E tan vers B et en plus a vitesse R ! Parfait pour ce que je veut faire !

    Merci quand même d'avoir voulu m'aider avec les fonctions compliqué, mais j'ai trouver plus simple...

    Reste plus qu'a coder tout ça et a voir que j'ai fait de la merde de tout les cotées mais là pour l'instant je pence que c'est clean

  11. #11
    Membre éprouvé Avatar de balkany
    Homme Profil pro
    Touriste
    Inscrit en
    Juillet 2017
    Messages
    346
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Touriste

    Informations forums :
    Inscription : Juillet 2017
    Messages : 346
    Points : 977
    Points
    977
    Par défaut
    Citation Envoyé par Personne3443 Voir le message
    Merci quand même d'avoir voulu m'aider avec les fonctions compliqué, mais j'ai trouver plus simple...
    Tant mieux ! Comme je te disais, je ne me prononce pas sur le fond (l'algo d'apprentissage), je faisais juste une remarque en passant au niveau des maths.
    Bon courage !

    --
    PS : E tend vers B, du verbe tendre, et non pas tan, qui fait plutôt référence à la fonction tangente en maths…

  12. #12
    Futur Membre du Club
    Homme Profil pro
    aucune
    Inscrit en
    Juillet 2020
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : aucune

    Informations forums :
    Inscription : Juillet 2020
    Messages : 15
    Points : 6
    Points
    6
    Par défaut
    Citation Envoyé par balkany Voir le message
    Tant mieux ! Comme je te disais, je ne me prononce pas sur le fond (l'algo d'apprentissage), je faisais juste une remarque en passant au niveau des maths.
    Bon courage !

    --
    PS : E tend vers B, du verbe tendre, et non pas tan, qui fait plutôt référence à la fonction tangente en maths…
    Merci

    PS : Désolé je ne savait pas comment ça s'écrivait...

Discussions similaires

  1. [PERL] faire une condition plus compacte
    Par LE NEINDRE dans le forum Langage
    Réponses: 4
    Dernier message: 28/10/2005, 16h03
  2. Comparer une valeur à plus ou moins quelque chose...?
    Par Thierry8 dans le forum Langage
    Réponses: 4
    Dernier message: 11/10/2005, 13h17
  3. néophyte, faire une requête plus courte
    Par LE NEINDRE dans le forum Requêtes
    Réponses: 8
    Dernier message: 10/10/2005, 09h44
  4. [JFrame] Création d'une fenetre plus grande que l'ecran
    Par thetoctoc dans le forum Agents de placement/Fenêtres
    Réponses: 2
    Dernier message: 23/09/2004, 11h05
  5. [Tomcat] migration vers une version plus récente
    Par butcher dans le forum Tomcat et TomEE
    Réponses: 4
    Dernier message: 31/10/2003, 21h46

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