龙空技术网

利用遗传算法求解几何问题

人工智能遇见磐创 478

前言:

目前朋友们对“数学建模遗传算法论文范文”大约比较讲究,兄弟们都想要剖析一些“数学建模遗传算法论文范文”的相关知识。那么小编同时在网上收集了一些对于“数学建模遗传算法论文范文””的相关资讯,希望你们能喜欢,兄弟们快快来学习一下吧!

最近看了一个关于“令人难以置信的人工智能发明”的ted演讲:

这个ted演讲的特色是使用直观的人工智能生成汽车模型。这部分内容很简短,没有详细说明什么类型的人工智能以及它是如何实现的,所以我决定尝试用遗传算法复制这个项目的一个小规模版本。

我为什么选择遗传算法?与神经网络不同的是,遗传算法可以很容易地生成内容,而无需对图像进行卷积,然后将其转换回原始尺寸。但是,要找到正确格式的汽车模型数据是极其困难的。

概述了项目类型后,我应该如何简化问题?

概念

我将用简单的想法来代替制造低空气阻力的汽车,即以点连接的方式创建一个由n个点组成的最大区域的形状。

形状的面积将使用鞋带(Shoelace )公式计算。从名称中可以推导出它是如何工作的:点坐标的交叉乘法创建了鞋带类型模式。

然后我将使用一种遗传算法(改编自这段代码: )来生成一组数字,然后将这些数字转换为坐标,从而绘制出一个形状。

代码步骤1 |依赖项

import randomimport numpy as npfrom IPython.display import clear_outputdef sigmoid(x):    return 1/(1+np.exp(-x))    def PolyArea(x,y):    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

导入程序运行所需的基本依赖项。random用于随机生成智能体,numpy用于初始化和操作矩阵,IPython display用于清除屏幕上的混乱。

为了简单起见,我将在这个项目中使用的唯一激活函数是sigmoid函数。

polyarea函数是以numpy为数学基础的鞋带算法的实现。

步骤2 |实现类

class genetic_algorithm:            def execute(pop_size,generations,threshold,network):        class Agent:            def __init__(self,network):                class neural_network:                    def __init__(self,network):                        self.weights = []                        self.activations = []                        for layer in network:                            if layer[0] != None:                                input_size = layer[0]                            else:                                input_size = network[network.index(layer)-1][1]                            output_size = layer[1]                            activation = layer[2]                                                        self.weights.append(np.random.randn(input_size,output_size))                            self.activations.append(activation)                    def propagate(self,data):                        input_data = data                        for i in range(len(self.weights)):                            z = np.dot(input_data,self.weights[i])                            a = self.activations[i](z)                            input_data = a                        yhat = a                        return yhat                self.neural_network = neural_network(network)                self.fitness = 0                self.gene_drive = []            def __str__(self):                    return 'Loss: ' + str(self.fitness[0])

这是程序的开始,创建了遗传算法类和执行函数。

在agent的init中,初始化一个神经网络类,并根据给定的矩阵结构随机生成其权重。

步骤3 |创建种群

def generate_agents(population, network):            return [Agent(network) for _ in range(population)]

该函数以种群大小和网络结构为参数,生成智能体的种群,神经网络随机生成权值。

步骤4 |计算适合度

def fitness(agents):            for agent in agents:                total_area = 0                                points = agent.neural_network.propagate(np.random.randn(1,semi_epochs))                                for shape in points:                    x = list(shape[:num_points])                    y = list(shape[num_points:])                                        y.insert(0,0)                    x.insert(0,0)     y.insert(-1,0)                    x.insert(-1,0)     total_area += PolyArea(x,y)                                     agent.fitness = total_area/semi_epochs                            return agents

我们将潜在点作为神经网络的输入。正因为如此,网络将进行多次尝试来生成形状,并记录这些形状的平均面积。

理论上,该算法将生成一个智能体,该智能体可以一致地生成具有n个点的高区域形状。观察这些形状可以帮助我们了解如何创建大面积的区域。

步骤5 |选择

def selection(agents):            agents = sorted(agents, key=lambda agent: agent.fitness, reverse=True)            print('\n'.join(map(str, agents)))            agents = agents[:int(0.2 * len(agents))]            return agents

程序的这一部分是选择算法,它根据智能体的适合度按逆序对它们进行排序。然后它会保留前五名。

步骤6 |交叉

def crossover(agents,network,pop_size):            offspring = []            for _ in range((pop_size - len(agents)) // 2):                parent1 = random.choice(agents)                parent2 = random.choice(agents)                child1 = Agent(network)                child2 = Agent(network)                                shapes = [a.shape for a in parent1.neural_network.weights]                                genes1 = np.concatenate([a.flatten() for a in parent1.neural_network.weights])                genes2 = np.concatenate([a.flatten() for a in parent2.neural_network.weights])                                split = random.randint(0,len(genes1)-1)child1_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist())                child2_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist())                                for gene in parent1.gene_drive:                    child1_genes[gene] = genes1[gene]                    child2_genes[gene] = genes1[gene]                                    for gene in parent2.gene_drive:                    child1_genes[gene] = genes2[gene]                    child2_genes[gene] = genes2[gene]                                child1.neural_network.weights = unflatten(child1_genes,shapes)                child2.neural_network.weights = unflatten(child2_genes,shapes)                                offspring.append(child1)                offspring.append(child2)            agents.extend(offspring)            return agents

从种群的20%中随机选出两个父类。然后繁殖。如何做到这一点:

他们的权重平坦化(flatten);找到一个随机的交点。这一点是单亲的遗传信息结束的地方,也是单亲遗传信息开始的地方;创建两个子代,然后将其添加到智能体列表中。这些子对象彼此不同,因为它们有不同的交点。

这有希望让优质父类的优良品质遗传给子代。

步骤7 |突变

def mutation(agents):            for agent in agents:                if random.uniform(0.0, 1.0) <= 0.1:                    weights = agent.neural_network.weights                    shapes = [a.shape for a in weights]flattened = np.concatenate([a.flatten() for a in weights])                    randint = random.randint(0,len(flattened)-1)                    flattened[randint] = np.random.randn()newarray = []                    indeweights = 0                    for shape in shapes:                        size = np.product(shape)                        newarray.append(flattened[indeweights : indeweights + size].reshape(shape                        indeweights += size                    agent.neural_network.weights = newarray            return agents

有10%的几率发生突变。在这种情况下,变异指的是某个权重值被一个随机浮点值替换。通过将权重展平,找到要更改的随机权重。

步骤9 |执行

for i in range(generations):            print('Generation',str(i),':')            agents = generate_agents(pop_size,network)            agents = fitness(agents)            agents = selection(agents)            agents = crossover(agents,network,pop_size)            agents = mutation(agents)            agents = fitness(agents)                        if any(agent.fitness > threshold for agent in agents):                print('Threshold met at generation '+str(i)+' !')                            if i % 100:                clear_output()                        return agents[0]

将最后一段代码粘贴到函数中,函数应该在调用时运行。

num_points = 3semi_epochs = 100network = [[semi_epochs,100,sigmoid],[None,num_points*2,sigmoid]]ga = genetic_algorithmagent = ga.execute(100,100,10,network)weights = agent.neural_network.weights

我们可以改变程序用来创建形状的点的数量,以及程序可以生成点的次数,以得到平均值。

标签: #数学建模遗传算法论文范文 #遗传算法子代数量