机器学习-人为设置函数方法和神经网络方法解决智能五子棋问题

2023-11-15

2  智能决策

2.1 博弈树模型算法

2.1.1 全局估算函数

此次项目中评估函数有两种:

    (1)人为设定函数方法:更具人的经验,对一些特定的棋形在棋盘上进行检索。并且计数,最后赋予相应权值求和得到对棋盘的评价值。典型的棋形有“活一”“活二”“活三”“冲四”“成龙”。越接近于五子连珠的棋形应有越大的权重。由于先手优势,同一种棋形黑棋的权重的绝对值应略大于白棋的权重。博弈双方的权重的符号应相反。不失一般性,黑棋的权重设置为正。

    (2)人工神经网络方法:用225个输入节点1个输出节点的神经网络对棋局进行评估。考虑到笔记本电脑计算条件本次实验中采用三层全连接网络结构,中间节点数为10。255个输入节点对应15*15棋盘上的所有点。如该点为黑棋输入为1,白棋输入-1,无子输入0。神经网络初始参数有高斯分布确定,再用遗传算法优化

2.1.2 极大极小算法

假设对弈的甲乙双方均为理性人,则对于甲走的每一步,乙都会选择下使得自己优势最大,甲的劣势最大的一步,甲下棋时亦然。例如在图6中在A棋局情况下,如果甲选择走B棋局, 那么乙将选择走对甲不利的E棋局;如果甲选择走 C棋局,乙将选择走G棋局;如果甲选择走D棋局, 那么乙将选择走K棋局……所以,综合来看,甲应该选择走B棋局,这样对自己最有利,这种算法就是极大极小算法。

         图8 博弈树模型

2.2  博弈树模型算法优化与实现

2.2.1 增量分析法

   在用人为设定函数计算棋局价值数值时,如果每次都遍历整个棋盘,则需要大量时间,事实上,只需计算出当前这一步落子在四个方向上的价值和未落子时该点四个方向上的价值之差再加上原来棋盘的价值及即可求得落子之后期盼的总价值

2.2.2 局部性原理

控制博弈树的层次和每层展开的节点数目,对反应速度和智能程度至关重要,根据人类棋手的经验,五子棋问题中,新下的棋与其余棋子的距离和该点的价值相关,距离越远,对整个棋盘影响越小,距离越近影响越大。这就是局部性原理,运用它可以选择有“潜力”的点进行展开,缩小搜索范围,提高搜索效率。

2.2.3 α-β剪枝

   很多时候遍历整个博弈树是没有必要的,如图6中,在A棋局下轮到甲走棋,甲首先搜索叶子节点E=7,F=11,计算得到B 棋局的倒推值为7;然后,当甲继续搜索到节点G= 1时,发现C(C≤1)必定小于B。也就是说,走第二 个子节点C棋局肯定不如走第一个子节点曰棋局 有利,那么子节点C棋局往下的其它节点棋局(H、I)就不用再搜索了,此过程就称为α-β剪枝。,运用α-β剪枝可以加快搜索速度,且党棋局越明郎,搜索速度越快。

2.3 实验结果与分析

2.3.1 人为设定函数的机器棋手表现

表1 机器五子棋的测试结果

采用算法及优化手段

博弈树每层分支

博弈树层次

下棋速度

与普通棋手下胜算

基本的博弈树算法

几百

至多3层

很慢

约1成

加入优化2.2.1

7

增至5层

较慢

约3成

加入优化2.2.2

7

增至7层

约5成

加入优化2.2.3

7

增至9层

很快

8成多

2.3.1采用神经网络和遗传算法的机器棋手表现

运用遗传算法神经网络训练出的机器棋手表现极为不佳分析原因有以下两点:

(1)种群数量太小,基因多样性丢失:在种群数量20,突变率为0.1的实验中,实验进行到第28代后,每次棋局都是变得一模一样,主要原因是种群数量太小,次要原因是突变率太小

图9 种群20第28代出现多样性丢失

(2)训练代数太小,未学到智能性:在种群数量为100,突变率为0.3的实验中,经过长达两小时的训练到达第33代时,虽然没有出现基因多样性消失的现象,但机器棋手仍未表现出智能的迹象,主要原因是计算能力有限,短时间内训练代数太少,次要原因是网络初始参数不带有任何先天经验,从零开始学习比较费时

图10 种群100第33代仍未有智能表现

import time
import numpy as np
import copy
import pygame
import sys


#首先是‘活一’,‘冲四’等特定棋形的检测模板设置
flex1 = [[0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, ], [0, 0, 0, 0, 1, 0]]
Flex1 = [[0, -1, 0, 0, 0, 0], [0, 0, -1, 0, 0, 0], [0, 0, 0, -1, 0, 0, ], [0, 0, 0, 0, -1, 0]]
flex2 = [[0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0],
         [0, 1, 0, 0, 1, 0]]
Flex2 = [[0, -1, -1, 0, 0, 0], [0, 0, -1, -1, 0, 0], [0, 0, 0, -1, -1, 0], [0, -1, 0, -1, 0, 0], [0, 0, -1, 0, -1, 0]]
flex3 = [[0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [0, 0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 0]]
Flex3 = [[0, -1, -1, -1, 0, 0], [0, -1, -1, 0, -1, 0], [0, 0, -1, -1, -1, 0], [0, -1, 0, -1, -1, 0]]
flex4 = [[0, 1, 1, 1, 1, 0]]
Flex4 = [[0, -1, -1, -1, -1, 0]]
white_win = [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, ], [-1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, -1],
             [2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 2]]
black_win = [[-1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, 0], [0, -1, -1, -1, -1, -1, ], [1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, 1], [2, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, 2]]

block2 = [[2, 1, 1, 0, 0, 0, ], [0, 0, 0, 1, 1, 2], [-1, 1, 1, 0, 0, 0, ], [0, 0, 0, 1, 1, -1]]
Block2 = [[2, -1, -1, 0, 0, 0, ], [0, 0, 0, -1, -1, 2], [1, -1, -1, 0, 0, 0, ], [0, 0, 0, -1, -1, 1]]
block3 = [[2, 1, 1, 1, 0, 0, ], [0, 0, 1, 1, 1, 2], [-1, 1, 1, 1, 0, 0, ], [0, 0, 1, 1, 1, -1], [2, 1, 1, 0, 1, 0, ],
          [0, 1, 0, 1, 1, 2], [-1, 1, 1, 0, 1, 0, ], [0, 1, 0, 1, 1, -1]]
Block3 = [[2, -1, -1, -1, 0, 0, ], [0, 0, -1, -1, -1, 2], [1, -1, -1, -1, 0, 0, ], [0, 0, -1, -1, -1, 1],
          [2, -1, -1, 0, -1, 0, ], [0, -1, 0, -1, -1, 2], [1, -1, -1, 0, -1, 0, ], [0, -1, 0, -1, -1, 1]]
block4 = [[2, 1, 1, 1, 1, 0, ], [0, 1, 1, 1, 1, 2], [-1, 1, 1, 1, 1, 0, ], [0, 1, 1, 1, 1, -1], [2, 1, 1, 0, 1, 1],
          [2, 1, 0, 1, 1, 1], [2, 1, 1, 1, 0, 1]]
Block4 = [[2, -1, -1, -1, -1, 0, ], [0, -1, -1, -1, -1, 2], [1, -1, -1, -1, -1, 0, ], [0, -1, -1, -1, -1, 1],
          [2, -1, -1, 0, -1, -1], [2, -1, 0, -1, -1, -1], [2, -1, -1, -1, 0, -1]]

#游戏界面的参数设置
screen_size = (671, 671)
WIDTH = 720
HEIGHT = 720
width = 44
GRID_WIDTH = WIDTH // 20
WHITE = (255, 250, 255)
BLACK = (0, 0, 0)
GREEN = (0, 0xff, 0)
RED = (0xff, 0, 0)
bgcolor = (255, 255, 255)
color = [BLACK, WHITE]
pygame.init()
icon = pygame.image.load("image/五子棋.jpeg")
pygame.display.set_icon(icon)
screen = pygame.display.set_mode(screen_size, 0, 32)
pygame.display.set_caption('欢乐五子棋')
clock = pygame.time.Clock()
bg = pygame.image.load("image/checker.png")

#函数作用同函数名
def draw_check(surf):
    screen.fill(bgcolor)
    surf.blit(bg, (0, 0))


def draw_checker(surf, x, y, color):
    if color == 1:  # 执白棋
        pygame.draw.circle(surf, BLACK, ((x) * width + 27, (y) * width + 26), 20, 0)
    if color == -1:  # 执黑棋
        pygame.draw.circle(surf, WHITE, ((x) * width + 27, (y) * width + 26), 20, 0)


def winner_check(chessboard, ones_turn, board_size, chesser):
    counter_x, counter_y, counter_1, counter_2 = 0, 0, 0, 0
    for i in range(board_size):
        if chessboard[ones_turn[0]][i] == chesser:
            counter_x += 1
        else:
            counter_x = 0
        if counter_x == 5:
            return 1

        if chessboard[i][ones_turn[1]] == chesser:
            counter_y += 1
        else:
            counter_y = 0
        if counter_y == 5:
            return 1

    tip = ones_turn.index(max(ones_turn))
    if tip == 0:
        i, j = ones_turn[0] - ones_turn[1], 0
    else:
        i, j = 0, ones_turn[1] - ones_turn[0]
    while j < board_size and i < board_size:
        if chessboard[i][j] == chesser:
            counter_1 += 1
        else:
            counter_1 = 0
        if counter_1 == 5:
            return 1
        i += 1
        j += 1

    if ones_turn[0] + ones_turn[1] >= board_size + 1:
        i, j = ones_turn[0] + ones_turn[1] - (board_size + 1), board_size + 1
    else:
        i, j = 0, ones_turn[0] + ones_turn[1]

    while j >= 0 and i <= board_size + 1:
        if chessboard[i][j] == chesser:
            counter_2 += 1
        else:
            counter_2 = 0
        if counter_2 == 5:
            return 1
        i += 1
        j -= 1
    return 0

#得分计算
def score_count(windows, black_score, white_score):
    weight = [1, 1, 20, 20, 400, 50000, 10000, 500000, ]
    ex = 0.3
    if windows in flex1:
        white_score += weight[0]
    if windows in Flex1:
        black_score -= ex * weight[0]
    if windows in block2:
        white_score += weight[1]
    if windows in Block2:
        black_score -= ex * weight[1]
    if windows in flex2:
        white_score += weight[2]
    if windows in Flex2:
        black_score -= ex * weight[2]
    if windows in block3:
        white_score += weight[3]
    if windows in Block3:
        black_score -= ex * weight[3]
    if windows in flex3:
        white_score += weight[4]
    if windows in Flex3:
        black_score -= ex * weight[4]
    if windows in block4:
        white_score += weight[5]
    if windows in Block4:
        black_score -= ex * weight[5]
    if windows in flex4:
        white_score += weight[6]
    if windows in Flex4:
        black_score -= ex * weight[6]

    if windows in white_win:
        white_score += weight[7]
    if windows in black_win:
        black_score -= ex * weight[7]
    return black_score, white_score

#棋盘得分计算
def eval_chessboard(chessboard, ones_turn, old_score):  # ones_turn,old_score
    white_score, black_score = 0, 0
    #   x y axis
    for i in range(chessboard.shape[0] - 5):
        windows = list(chessboard[i:i + 6, ones_turn[1]])
        black_score, white_score = score_count(windows, black_score, white_score)
        windows = list(chessboard[ones_turn[0], i: i + 6, ])
        black_score, white_score = score_count(windows, black_score, white_score)
    tip = ones_turn.index(max(ones_turn))
    if tip == 0:
        i, j = ones_turn[0] - ones_turn[1], 0
    else:
        i, j = 0, ones_turn[1] - ones_turn[0]
    while j <= board_size - 4 and i <= board_size - 4:
        windows.clear()
        for k in range(6):
            windows.append(chessboard[i + k][j + k])
        black_score, white_score = score_count(windows, black_score, white_score)
        j += 1
        i += 1

    if ones_turn[0] + ones_turn[1] >= board_size + 1:
        i, j = ones_turn[0] + ones_turn[1] - (board_size + 1), board_size + 1
    else:
        i, j = 0, ones_turn[0] + ones_turn[1]

    while j >= 5 and i <= board_size - 4:
        windows.clear()
        for k in range(6):
            windows.append(chessboard[i + k][j - k])
        black_score, white_score = score_count(windows, black_score, white_score)
        i += 1
        j -= 1

    return old_score + white_score + black_score

#得分增益
def compute_score(chessboard, ones_turn, old_score):
    t1 = eval_chessboard(chessboard, ones_turn, old_score)
    ori_chessboard = copy.deepcopy(chessboard)
    ori_chessboard[ones_turn[0]][ones_turn[1]] = 0
    t0 = eval_chessboard(ori_chessboard, ones_turn, old_score)
    return t1 - t0 + old_score


# 更新搜索边界,这是用来优化减小搜索空间的
def update_boundary(boundary, i, j, size):  # size max axis from 1

    width = 2
    if i == 15:
        width = width
    if boundary[0] == 0:
        boundary[0], boundary[1] = j, j
        boundary[2], boundary[3] = i, i
    if boundary[2] >= i - width:
        if i - width >= 1:
            boundary[2] = i - width
        else:
            boundary[2] = 1

    if boundary[3] <= i + width:
        if i + width <= size:
            boundary[3] = i + width
        else:
            boundary[3] = size

    if boundary[0] >= j - width:
        if j - width >= 1:
            boundary[0] = j - width
        else:
            boundary[0] = 1
    if boundary[1] <= j + width:
        if j + width <= size:
            boundary[1] = j + width
        else:
            boundary[1] = size

    return boundary

# 树搜索
def tree_search(chessboard, boundary, search_degree, type, pre_step, pre_score, apha, beta):
    # boundry=(l,r,t,d)
    # boundry should be a tuple with four feature represent the boundary square
    score_list, position_list, back_score_list = [], [], []

    if search_degree == 0:
        """score_1=compute_score(chessboard,pre_step,pre_score)
        chessboard[pre_step[0]][pre_step[1]]=0
        score_0=compute_score(chessboard,pre_step,pre_score)"""
        return compute_score(chessboard, pre_step, pre_score), pre_step  # maybe?

    for i in range(boundary[2], boundary[3] + 1):
        for j in range(boundary[0], boundary[1] + 1):
            if chessboard[i][j] == 0:
                if type == 1:
                    chessboard[i][j] = 1
                    tem_score = compute_score(chessboard, (i, j), pre_score)
                    score_list.append((tem_score, i, j))
                else:
                    chessboard[i][j] = -1
                    tem_score = compute_score(chessboard, (i, j), pre_score)
                    score_list.append((tem_score, i, j))
                chessboard[i][j] = 0
    score_list.sort(key=lambda x: x[0], reverse=(type == 1))
    for k in range(8):
        i, j, tem_score = score_list[k][1], score_list[k][2], score_list[k][0]
        new_boundary = copy.deepcopy(boundary)
        new_boundary = update_boundary(new_boundary, i, j, chessboard.shape[0] - 1)

        tem0, tem1 = tree_search(chessboard, new_boundary, search_degree - 1, -type, (i, j), tem_score, apha, beta)
        back_score_list.append(tem0)

        if tem0 > apha:
            apha = tem0
        if tem0 < beta:
            beta = tem0
        chessboard[i][j] = 0
        if beta <= apha:
            return tem0, (i, j)

        if type == 1:
            return max(back_score_list), score_list[back_score_list.index(max(back_score_list))][1], \
                   score_list[back_score_list.index(max(back_score_list))][2]
        if type == -1:
            return min(back_score_list), score_list[back_score_list.index(min(back_score_list))][1], \
                   score_list[back_score_list.index(min(back_score_list))][2]





score = 0
score_max = 0
board_size = 15  # needs boundary filled by 2
boundary = [0, 0, 0, 0]
# flex1,Flex1,block2,Block2,flex2,Flex2,block3,Block3,flex3,Flex3,block4,Block4,w1,W1
chance_count = np.zeros((1, board_size))
chessboard = np.zeros((board_size + 2, board_size + 2)) + 2
chessboard[1:-1, 1:-1] -= 2
# black_chess = eval(input()) #
black_chess = 1
out = 0
while 1:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = event.pos
            human_turn1 = (int(round((pos[0] - 27) / width)), int(round((pos[1] - 26) / width)))
            human_turn = human_turn1[0] + 1, human_turn1[1] + 1
            if chessboard[human_turn[0]][human_turn[1]] == 0:
                chessboard[human_turn[0]][human_turn[1]] = 1
                boundary = update_boundary(boundary, human_turn[0], human_turn[1], board_size)
                if winner_check(chessboard, human_turn, board_size, 1) == 1:
                    pygame.display.set_caption('哇,妈妈赢了,腻害腻害')
                    out = 1
                    break
            for i in range(1, board_size + 1):
                for j in range(1, board_size + 1):
                    draw_checker(screen, i - 1, j - 1, chessboard[i][j])
            pygame.display.update()
            clock.tick(50)

            score = compute_score(chessboard, human_turn, score)
            score_max, robot_turn = tree_search(chessboard, boundary, 2, -1, (0, 0), score, -100000000, 100000000)
            chessboard[robot_turn[0]][robot_turn[1]] = -1
            score = compute_score(chessboard, robot_turn, score)
            boundary = update_boundary(boundary, robot_turn[0], robot_turn[1], board_size)
            if winner_check(chessboard, robot_turn, board_size, -1) == 1:
                print("robot win")
                pygame.display.set_caption('承让承让了妈妈')
                out = 1
                break

        draw_check(screen)
        for i in range(1, board_size + 1):
            for j in range(1, board_size + 1):
                draw_checker(screen, i - 1, j - 1, chessboard[i][j])
        pygame.display.update()
        if out == 1:
            time.sleep(3)
            sys.exit()
        clock.tick(50)

import torch
import random
import copy
import pygame
import time

chessboard = torch.randn((255,1))
ensor =  torch.Tensor(100,100,255,)
torch.nn.init.normal_(ensor)

screen_size = (671,671)
WIDTH = 720
HEIGHT = 720
width = 44
GRID_WIDTH = WIDTH // 20
WHITE = (255, 250, 255)
BLACK = (0, 0, 0)
GREEN = (0, 0xff, 0)
RED = (0xff, 0, 0)
bgcolor = (255,255,255)
color = [BLACK,WHITE]
pygame.init()
screen_size = (671, 671)
pygame.init()
icon = pygame.image.load("image/五子棋.jpeg")
pygame.display.set_icon(icon)
screen = pygame.display.set_mode(screen_size, 0, 32)
pygame.display.set_caption('欢乐五子棋')
clock = pygame.time.Clock()
bg = pygame.image.load("image/checker.png")
fname ="weight.txt"

class F_c(torch.nn.Module):
    def __init__(self, input_size, hidden_size, num_classes):
        super(F_c, self).__init__()
        self.fc1 = torch.nn.Linear(input_size, hidden_size,)
        self.sigmoid = torch.nn.Sigmoid()
        self.fc2 = torch.nn.Linear(hidden_size, num_classes,)

    def forward(self, x):
        out = self.fc1(x)
        out = self.sigmoid(out)
        out = self.fc2(out)
        return out


def draw_check(surf):
    screen.fill(bgcolor)
    surf.blit(bg, (0, 0))


def draw_checker(surf,x,y,color):

    if color == 1:#执白棋
        pygame.draw.circle( surf, BLACK, ((x) * width+27, (y) * width+26), 20, 0)
    if color == -1:#执黑棋
        pygame.draw.circle( surf, WHITE, ((x) * width+27, (y) * width+26), 20, 0)

def winner_check(chessboard,ones_turn,board_size,chesser):
    counter_x,counter_y,counter_1,counter_2 =0,0,0,0
    for i in range(board_size):
            if chessboard[ones_turn[0]][i]==chesser:
                counter_x += 1
            else:
                counter_x= 0
            if counter_x==5:
                return 1

            if chessboard[i][ones_turn[1]]==chesser:
                counter_y += 1
            else:
                counter_y= 0
            if counter_y==5:
                return 1

    tip =ones_turn.index(max(ones_turn))
    if tip==0:
        i,j=ones_turn[0]-ones_turn[1],0
    else:
        i,j =0,ones_turn[1]-ones_turn[0]
    while j<board_size and i<board_size:
        if chessboard[i][j]==chesser:
            counter_1+=1
        else:
            counter_1=0
        if counter_1==5:
            return 1
        i+=1
        j+=1

    if ones_turn[0]+ones_turn[1]>=board_size:
        i,j=ones_turn[0]+ones_turn[1]-(board_size-1),board_size-1
    else:
        i,j=0,ones_turn[0]+ones_turn[1]


    while j>=0 and  i<=board_size-1:
        if chessboard[i][j]==chesser:
            counter_2+=1
        else:
            counter_2=0
        if counter_2==5:
            return 1
        i+=1
        j-=1
    return 0
def update_boundary(boundary,i,j,size):# size max axis from 1

    width =2
    if boundary[0] == -1:
        boundary[0], boundary[1] = j, j
        boundary[2], boundary[3] = i, i
    if boundary[0]>=j-width:
        if j-width>=0:
            boundary[0]=j-width
        else:
            boundary[1]=0
    if boundary[1]<=j+width:
        if j+width<size-1:
            boundary[1]=j+width
        else:
            boundary[1]=size-1

    if boundary[2]>=i-width:
        if i-width>=0:
            boundary[2]=i-width
        else:
            boundary[2]=0

    if boundary[3]<=i+width:
        if i+width<size-1:
            boundary[3]=i+width
        else:
            boundary[3]=size-1

    return boundary

def compute_score(chessboard,weight_tensor):#the latter should be the object lof F_c
    chessboard_tensor=chessboard.clone().detach()
    #chessboard_tensor=torch.cuda.FloatTensor(chessboard_tensor)
    chessboard_tensor = chessboard_tensor.to(device)
    chessboard=chessboard-2
    chessboard_tensor.resize_(225)
    #ues torch.nn
    x =weight_tensor.forward(chessboard_tensor)
    return x



def tree_search(chessboard,weight_tensor,boundary,pre_step,search_degree,type,apha,beta):
    # boundry=(l,r,t,d)
    # boundry should be a tuple with four feature represent the boundary square
    score_list, position_list, back_score_list = [], [], []
    if search_degree == 0:
        return compute_score(chessboard,weight_tensor), pre_step  # maybe?

    for i in range(boundary[2], boundary[3]+1 ):
        for j in range(boundary[0], boundary[1]+1 ):
            if chessboard[i][j] == 2:
                if type == 1:
                    chessboard[i][j] = 1
                    tem_score = compute_score(chessboard,weight_tensor)
                    score_list.append((tem_score, i, j))
                else:
                    chessboard[i][j] = -1
                    tem_score = compute_score(chessboard,weight_tensor)
                    score_list.append((tem_score, i, j))
                chessboard[i][j] =2
    score_list.sort(key=lambda x: x[0], reverse=(type == 1))
    for k in range(min(8,len(score_list))):
        i, j, tem_score = score_list[k][1], score_list[k][2], score_list[k][0]
        new_boundary = copy.deepcopy(boundary)
        new_boundary = update_boundary(new_boundary, i, j, chessboard.shape[0] - 1)
        tem0, tem1 = tree_search(chessboard, weight_tensor,new_boundary,(i,j), search_degree - 1, -type, apha, beta)
        back_score_list.append(tem0)

        if tem0 > apha:
            apha = tem0
        if tem0 < beta:
            beta = tem0
        chessboard[i][j] = 2
        if beta <= apha:
            return tem0, (i, j)

        if type == 1:
            return max(back_score_list), (score_list[back_score_list.index(max(back_score_list))][1], \
                   score_list[back_score_list.index(max(back_score_list))][2])
        if type == -1:
            return min(back_score_list), (score_list[back_score_list.index(min(back_score_list))][1], \
                   score_list[back_score_list.index(min(back_score_list))][2])


def play(c1,c2,generation):
    board_size = 15
    chessboard = torch.zeros((15,15))+2
    c1_turn =(8,8)
    boundary=[-1]*4
    while 1:
        chessboard[c1_turn[0]][c1_turn[1]]=1
        boundary = update_boundary(boundary, c1_turn[0], c1_turn[1], board_size)
        if winner_check(chessboard,c1_turn,board_size,1)==1:
            break
        if torch.max(chessboard) < 2:
            return 1
            #平局
            #score 是不同的
        score2,c2_turn=tree_search(chessboard,c2,boundary,(0, 0),2,-1, -100000000, 100000000)
        chessboard[c2_turn[0]][c2_turn[1]] = -1
        boundary = update_boundary(boundary, c2_turn[0], c2_turn[1], board_size)
        if winner_check(chessboard,c2_turn,board_size,-1)==1:
            break
        score1,c1_turn=tree_search(chessboard,c1,boundary,(0, 0),2,1, -100000000, 100000000)
    draw_check(screen)
    for i in range(board_size):
        for j in range(board_size):
            draw_checker(screen, i , j , chessboard[i][j])


    pygame.display.update()
    pygame.display.set_caption("N0.{} match".format(generation))
    if winner_check(chessboard,c2_turn,board_size,-1) == 1:
        print("white win")
        return 1
    else:
        print("black win")
        return 0

def competation(population,generation):
    l =len(population)#len应为双数promoted[i],promoted[i+1]
    i=0
    promoted=[]
    print(l)
    while i<l:
        x=population[i]
        f =play(population[i],population[i+1],generation)
        promoted.append(population[i+f])
        i+=2
    return promoted
#还要先交配 再 选出其余一半子代


def reproduction(p,q):
    x = random.randint(0,p.fc1.weight.shape[0]*p.fc1.weight.shape[1])
    y = random.randint(0, p.fc1.weight.shape[0] * p.fc1.weight.shape[1])
    a=p.fc1.weight
    b=p.fc2.weight
    p.fc1.weight[0,x:y]=q.fc1.weight[0,x:y]
    q.fc1.weight[0,x:y]=a[0,x:y]
    x = random.randint(0, p.fc2.weight.shape[0] * p.fc2.weight.shape[1])
    y = random.randint(0, p.fc2.weight.shape[0] * p.fc2.weight.shape[1])
    p.fc2.weight[0,x:y]=q.fc2.weight[0,x:y]
    q.fc2.weight[0,x:y]=b[0,x:y]
    #print(q.fc2.weight[0,x:y])
    return p,q






#how to initialize stochastic net
def genetic_algrothim(population,generation):#weight_tensor is object list
    if generation==0:
        torch.save(population[0],"net_params.pkl")
        print("ok")
        return population#to get the best one

    mutation_rate =0.3
    # how to initialize stochastic net

    promoted =competation(population,generation)#needs object
    population += promoted
    l =len(promoted)
    print(len(promoted))

    for i in range(len(promoted),1):
        promoted[i],promoted[i+1]=reproduction(promoted[i],promoted[i+1])
    for i in range(l):
        promoted.append(population[random.randint(0, len(population)-1)])
    #mutation
    for i in promoted:
        for j in range(i.fc1.weight.shape[1]):
            if random.random() < mutation_rate:
                i.fc1.weight[0,j] += random.random()
        for j in range(i.fc2.weight.shape[1]):
            if random.random() < mutation_rate:
                i.fc2.weight[0,j] += random.random()
    torch.save(population[0], "net_params0.pkl")
    torch.save(population[1], "net_params1.pkl")
    torch.save(population[2], "net_params2.pkl")
    torch.save(population[3], "net_params3.pkl")
    answer=genetic_algrothim(promoted,generation-1)
    return answer
#
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
a = torch.zeros(225)

population,weight=[],[]
for i in range(100):
    people = F_c(225,10,1)
    torch.manual_seed(i)
    torch.nn.init.normal_(people.fc1.weight,mean=0,std=1)
    torch.nn.init.normal_(people.fc2.weight,mean=0,std=1)
    people.to(device)
    population.append(people)


#weight=torch.tensor(weight)
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

        print(weight)
        new_weight =genetic_algrothim(population,10000)

        print(new_weight)

 转载请注明出处!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

机器学习-人为设置函数方法和神经网络方法解决智能五子棋问题 的相关文章

  • 推荐系统:机器学习中基于内容的过滤

    概述 顾名思义 基于内容的筛选是一种机器学习实现 它使用系统中收集的内容或功能来提供类似的建议 根据用户观察结果从数据集中获取最相关的信息 最常见的例子是 Netflix Myntra Hulu Hotstar Instagram Expl
  • 杂项:机器学习平台

    概述 机器学习学科正在快速扩展 因此 选择合适的机器学习平台至关重要 这有助于利用端到端方法成功构建模型 机器学习平台为用户提供了创建 实施和增强机器学习 尤其是机器学习算法 的工具 介绍 随着组织收集更多数据 使用机器学习和其他人工智能
  • 最小二乘法

    最小二乘法 最小二乘法是指 残余误差平方和最小 最小二乘法应用 至少 最可信赖估计 回归分析
  • 机器学习 高维数据可视化:t-SNE 降维算法

    作者简介 人工智能专业本科在读 喜欢计算机与编程 写博客记录自己的学习历程 个人主页 小嗷犬的个人主页 个人网站 小嗷犬的技术小站 个人信条 为天地立心 为生民立命 为往圣继绝学 为万世开太平 本文目录 t SNE 简介 sklearn 中
  • 人工智能知识表示与推理:构建智能系统的认知引擎

    导言 人工智能知识表示与推理是构建智能系统认知引擎的关键组成部分 本文将深入研究知识表示的方法和推理技术 以及它们在解决现实问题和提升智能系统智能水平中的作用 1 知识表示方法 符号表示法 使用符号和逻辑关系来表示知识 例如谓词逻辑 连接主
  • 人工智能深度学习:探索智能的深邃奥秘

    导言 人工智能深度学习作为当今科技领域的明星 正引领着智能时代的浪潮 深度学习和机器学习作为人工智能领域的两大支柱 它们之间的关系既有协同合作 又存在着显著的区别 本文将深入研究深度学习在人工智能领域的角色 以及其在各行各业中的深远影响 研
  • 吴恩达机器学习笔记七 逻辑回归的梯度下降 过拟合及解决方法

    两个偏导数 逻辑回归的梯度下降 泛化 generalization 对全新的示例也能做出良好的预测 解决过拟合的方法 1 收集更多的测试数据 2 特征选择 feature selection 使用更少的特征 3 正则化 regulariza
  • 软件测试/测试开发/人工智能丨机器学习中特征的含义,什么是离散特征,什么是连续特征。

    在机器学习中 特征 Feature 是输入数据中的属性或变量 用于描述样本或数据点 特征对于机器学习模型而言是输入的一部分 模型通过学习样本的特征与其对应的标签 或输出 之间的关系来做出预测或分类 特征可以分为不同类型 其中两个主要的类型是
  • 软件测试/测试开发/人工智能丨分类,二分类和回归问题的对应场景与区别

    分类 二分类和回归问题是机器学习中常见的三种任务类型 它们分别适用于不同的场景 具有不同的目标和输出 1 分类问题 Classification 场景 适用于将数据点分到不同的类别或标签中的问题 每个类别代表一种离散的类别或状态 例子 判断
  • 基于BP神经网络结合自适应带宽核函数密度估计区间预测。BP-ABKDE区间概率预测,BP神经网络核密度估计下置信区间预测。区间预测(区间覆盖率PICP、区间平均宽度百分比PINAW,CRPS,CW

    清空环境变量 warning off 关闭报警信息 close all 关闭开启的图窗 clear 清空变量 clc 清空命令行 res xlsread 数据集 xlsx num size 0 8 训练集占数据集比例 dataran 0 不
  • 第二部分相移干涉术

    典型干涉图 相移干涉术 相移干涉术的优点 1 测量精度高 gt 1 1000 条纹 边缘跟踪仅为 1 10 边缘 2 快速测量 3 低对比度条纹测量结果良好 4 测量结果不受瞳孔间强度变化的影响 独立于整个瞳孔的强度变化 5 在固定网格点获
  • 机器学习---决策树

    介绍 决策树和随机森林都是非线性有监督的分类模型 决策树是一种树形结构 树内部每个节点表示一个属性上的测试 每个分支代表一个测试输出 每个叶子节点代表一个分类类别 通过训练数据构建决策树 可以对未知数据进行分类 随机森林是由多个决策树组成
  • 吴恩达机器学习笔记八 正则化

    使第一项均方差较小来符合数据 使第二项正则化项较小来使 w 较小 0 采用高阶多项式会过拟合 非常大 则每个 w 都很小 F X 约为 b 结果为一条直线 欠拟合 含正则化线性回归的梯度下降 含正则化逻辑回归的梯度下降 到这里第一个专项课程
  • 澳鹏干货解答!“关于机器学习的十大常见问题”

    探索机器学习的常见问题 了解机器学习和人工智能的基本概念 原理 发展趋势 用途 方法和所需的数据要求从而发掘潜在的商机 什么是机器学习 机器学习即教授机器如何学习的过程 为机器提供指导 帮助它们自己开发逻辑 访问您希望它们访问的数据 机器学
  • 互操作性(Interoperability)如何影响着机器学习的发展?

    互操作性 Interoperability 也称为互用性 即两个系统之间有效沟通的能力 是机器学习未来发展中的关键因素 对于银行业 医疗和其他生活服务行业 我们期望那些用于信息交换的平台可以在我们需要时无缝沟通 我们每个人都有成千上万个数据
  • 互操作性(Interoperability)如何影响着机器学习的发展?

    互操作性 Interoperability 也称为互用性 即两个系统之间有效沟通的能力 是机器学习未来发展中的关键因素 对于银行业 医疗和其他生活服务行业 我们期望那些用于信息交换的平台可以在我们需要时无缝沟通 我们每个人都有成千上万个数据
  • 详解数据科学自动化与机器学习自动化

    过去十年里 人工智能 AI 构建自动化发展迅速并取得了多项成就 在关于AI未来的讨论中 您可能会经常听到人们交替使用数据科学自动化与机器学习自动化这两个术语 事实上 这些术语有着不同的定义 如今的自动化机器学习 即 AutoML 特指模型构
  • 图神经网络与智能教育:创新教育技术的未来

    导言 图神经网络 GNNs 和智能教育技术的结合为教育领域注入新活力 本文深入研究二者的结合可能性 涉及各自侧重 当前研究动态 技术运用 实际场景 未来展望 并提供相关链接 1 图神经网络与智能教育的结合方向 1 1 图神经网络在教育技术中
  • 毕业设计-基于深度学习的细菌微生物目标检测系统系统 YOLO python 目标检测 人工智能 卷积神经网络 机器学习

    目录 前言 设计思路 一 课题背景与意义 二 算法理论原理 2 1 CBAM模块 2 2 损失函数 三 检测的实现 3 1 数据集 3 2 实验环境搭建 3 3 实验及结果分析 实现效果图样例 最后 前言 大四是整个大学期间最忙碌的时光 一
  • 5_机械臂运动学基础_矩阵

    上次说的向量空间是为矩阵服务的 1 学科回顾 从科技实践中来的数学问题无非分为两类 一类是线性问题 一类是非线性问题 线性问题是研究最久 理论最完善的 而非线性问题则可以在一定基础上转化为线性问题求解 线性变换 数域 F 上线性空间V中的变

随机推荐

  • 计算机网络 概念

    一 计算机网络概念 计算机网络的组成 有若干个节点和连接的节点的链路组成 主机的概念 与网络相连接的计算机称为主机 计算机网络 是一个将分散的 具有独立功能的计算机系统 通过通信设备和线路 由功能完善的软件实现资源共享和信息传递 计算机网络
  • 再谈缓存

    凡是涉及管理数据的系统 都可以用图书馆来考虑 都要面临图书的位置查找和实际摆放两个问题 对应的两大组件就是就是index store 所有的数据管理系统都包含这两部分 缓存从过期又什么触发的角度分为容量触发和时间触发 容量触发 就是缓存满了
  • 内置tomcat整合SpringMVC

    spring MVC是一个基于MVC模式的表现层框架 在spring2 5以后增加了注解功能 使得开发变得更加高效 快捷 由于spring MVC是spring框架的一个模块 springmvc和spring无需通过中间整合层进行整合 可以
  • SQLServer 2008R2 配置允许外网访问

    SQL Server 2008 1433端口启用的解决方案 cqs 2012 CSDN博客
  • R聚类分析航空公司数据(筛选出不同的客户类别)

    效果图如下 图片是将3万四千条航空公司数据用k means算法分成五个类 并通过ggplot2包作图作出来的特征属性 我们将通过不同的属性值 分析出高价值用户 低价值用户 主力用户 一般用户 潜力用户 可以分析得F M C自然是越高越好 C
  • ext3grep恢复linux下误删除的文件

    在linux下使用rm rf时千万要小心 但是总有不小心的时候 导致误删除一些文件 这里我做个试验 故意删除 data 2 txt文件 测试文件恢复 此时2 txt文件已经删除 1 安装ext3grep软件 wget http ext3gr
  • vue之路由的嵌套(父子路由)

    路由的嵌套 1 配置路由 main js文件中 import Users from components Users import UserAdd from components Users UserAdd import UserList
  • 第二章 Scala入门——让你的代码跑起来

    一 Scala的安装方法 要使用Scala 首先需要保证已经安装好了Java 8 对于Linux操作系统 Java 8已经默认安装了 而使用Windows操作系统的用户 则需要在Java官网下载安装包进行安装 请在CMD PowerShel
  • 小米解bl锁跳过168小时_红米K30S至尊纪念版秒解BL工具分享支持小米红米机型秒解BL跳过168小时...

    目前小米的新机 官方风控都默认绑定7天也就是168小时才能解锁BL 部分账号需要绑定15天才能满足条件 导致很多爱玩机的小伙伴被拒门外 并不是所有人都愿意等待官方解锁时候 而跳过168小时解锁 也成为了很多小伙伴希望的事情 本工具来自ROM
  • 操作系统CPU调度

    概述 多道程序操作系统的基础 通过在进程之间切换CPU 操作系统可以提高计算机的吞吐率 对于单处理器系统 每次只允许一个进程运行 任何其他进程必须等待 直到CPU空闲能被调度为止 CPU按一定的调度算法从就绪队列中选择一个进程 把CPU的使
  • TorchVision中使用FasterRCNN+ResNet50+FPN进行目标检测

    TorchVision中给出了使用ResNet 50 FPN主干 backbone 构建Faster R CNN的pretrained模型 模型存放位置为https download pytorch org models fasterrcn
  • PE文件资源解析(七)manifest资源的解析

    mainfest资源 在这里指的是资源类型为RT MANIFEST的资源信息 通过ResHacker看到的效果图如下 manifest资源存储编码格式是UTF 8 开始3个字节是EF BB BF 解析代码如下 UTF8 EF BB BF H
  • Java练习10:输入两个正整数m和n,求其最大公约数和最小公倍数

    辗转相除法 package com qiqi test import java util Scanner 输入两个正整数m和n 求其最大公约数和最小公倍数 辗转相除法 1 用大数m 小数n得第一个余数 2 余数为0则n为最大公约数 3 余数
  • 【数据库原理选择题1-4章】

    1 1 数据库系统概述 1 1 DB DBMS 和DBS 三者之间的关系是 A DBMS包括DB和DBS B DB 包括DBMS和DBS C 不能相互包括 D DBS包括DB和DBMS 正确答案 D 2 位于用户和操作系统之间的一层数据管理
  • VS2017 登录账户时,反复让输入密码,而一直无法登陆。

    问题描述 VS2017 登录账户时 反复让输入密码 而一直无法登陆成功 最后显示无法刷新此账户凭据 解决办法 在排除是自己账户或者网络有问题后 通过清理用户数据解决问题 具体步骤如下 使用管理员权限打开命令终端 转到VS安装目录下的 Com
  • torch中的model.eval()、model.train()详解

    个人简介 深度学习图像领域工作者 工作总结链接 https blog csdn net qq 28949847 article details 128552785 链接中主要是个人工作的总结 每个链接都是一些常用demo 代码直接复制运行即
  • 欧几里得距离(欧式距离)

    文章目录 一 定义 二 公式 一 定义 欧几里得度量 欧氏距离 Euclidean Metric Euclidean Distance 指在m维空间中两个点之间的真实距离 或者向量的自然长度 即该点到原点的距离 比如 在二维和三维空间中的欧
  • 液滴/液膜蒸发过程—in文件模拟-后处理分析-Ovito/Python绘图

    关注 M r m a t e r i a l color Violet rm Mr material Mr material
  • FDR计算

    FDR计算 FDR的计算很简单 我折腾了一上午主要是因为遇到了以下几个问题 问题 FDR是什么 有什么用 怎么计算 我把几个模型的P值都合并成一个表了 所以每次运算FDR时 我需挑选特定的对象 我有多个模型 所以我想着要如何构建循环 FDR
  • 机器学习-人为设置函数方法和神经网络方法解决智能五子棋问题

    2 智能决策 2 1 博弈树模型算法 2 1 1 全局估算函数 此次项目中评估函数有两种 1 人为设定函数方法 更具人的经验 对一些特定的棋形在棋盘上进行检索 并且计数 最后赋予相应权值求和得到对棋盘的评价值 典型的棋形有 活一 活二 活三