推广 外贸 网站,做自己的彩票网站,网站开发 微信收款,平面设计正规培训机构以下是一个增强版的将 A* 算法与卷积神经网络#xff08;CNN#xff09;结合的代码实现#xff0c;其中 CNN 增加了卷积层的数量#xff0c;并对卷积核大小进行了调整。整体思路依然是先利用 A* 算法生成训练数据#xff0c;再用这些数据训练 CNN 模型#xff0c;最后使用…以下是一个增强版的将 A* 算法与卷积神经网络CNN结合的代码实现其中 CNN 增加了卷积层的数量并对卷积核大小进行了调整。整体思路依然是先利用 A* 算法生成训练数据再用这些数据训练 CNN 模型最后使用训练好的模型进行路径规划。
import numpy as np
import heapq
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader# A* 算法实现
class Node:def __init__(self, x, y, gfloat(inf), hfloat(inf), parentNone):self.x xself.y yself.g gself.h hself.f g hself.parent parentdef __lt__(self, other):return self.f other.fdef heuristic(current, goal):return abs(current[0] - goal[0]) abs(current[1] - goal[1])def astar(grid, start, goal):rows, cols grid.shapeopen_list []closed_set set()start_node Node(start[0], start[1], g0, hheuristic(start, goal))heapq.heappush(open_list, start_node)while open_list:current_node heapq.heappop(open_list)if (current_node.x, current_node.y) goal:path []while current_node:path.append((current_node.x, current_node.y))current_node current_node.parentreturn path[::-1]closed_set.add((current_node.x, current_node.y))neighbors [(0, 1), (0, -1), (1, 0), (-1, 0)]for dx, dy in neighbors:new_x, new_y current_node.x dx, current_node.y dyif 0 new_x rows and 0 new_y cols and grid[new_x][new_y] 0 and (new_x, new_y) not in closed_set:new_g current_node.g 1new_h heuristic((new_x, new_y), goal)new_node Node(new_x, new_y, gnew_g, hnew_h, parentcurrent_node)found Falsefor i, node in enumerate(open_list):if node.x new_x and node.y new_y:if new_g node.g:open_list[i] new_nodeheapq.heapify(open_list)found Truebreakif not found:heapq.heappush(open_list, new_node)return None# 生成训练数据
def generate_training_data(grid, num_samples):rows, cols grid.shapeinputs []outputs []for _ in range(num_samples):start (np.random.randint(0, rows), np.random.randint(0, cols))goal (np.random.randint(0, rows), np.random.randint(0, cols))path astar(grid, start, goal)if path:input_data np.zeros((1, rows, cols))input_data[0, start[0], start[1]] 1input_data[0, goal[0], goal[1]] 2output_data np.zeros((1, rows, cols))for point in path:output_data[0, point[0], point[1]] 1inputs.append(input_data)outputs.append(output_data)return np.array(inputs), np.array(outputs)# 自定义数据集类
class PathDataset(Dataset):def __init__(self, inputs, outputs):self.inputs torch.tensor(inputs, dtypetorch.float32)self.outputs torch.tensor(outputs, dtypetorch.float32)def __len__(self):return len(self.inputs)def __getitem__(self, idx):return self.inputs[idx], self.outputs[idx]# 定义增强版卷积神经网络模型
class EnhancedPathCNN(nn.Module):def __init__(self):super(EnhancedPathCNN, self).__init__()self.conv1 nn.Conv2d(1, 32, kernel_size5, padding2)self.relu1 nn.ReLU()self.conv2 nn.Conv2d(32, 64, kernel_size5, padding2)self.relu2 nn.ReLU()self.conv3 nn.Conv2d(64, 128, kernel_size3, padding1)self.relu3 nn.ReLU()self.conv4 nn.Conv2d(128, 64, kernel_size3, padding1)self.relu4 nn.ReLU()self.conv5 nn.Conv2d(64, 1, kernel_size3, padding1)def forward(self, x):x self.relu1(self.conv1(x))x self.relu2(self.conv2(x))x self.relu3(self.conv3(x))x self.relu4(self.conv4(x))x self.conv5(x)return x# 训练神经网络
def train_model(model, dataloader, criterion, optimizer, epochs):for epoch in range(epochs):running_loss 0.0for inputs, labels in dataloader:optimizer.zero_grad()outputs model(inputs)loss criterion(outputs, labels)loss.backward()optimizer.step()running_loss loss.item()print(fEpoch {epoch 1}, Loss: {running_loss / len(dataloader)})# 主程序
if __name__ __main__:# 示例地图map_grid np.array([[0, 0, 0, 0, 0],[0, 1, 1, 0, 0],[0, 0, 0, 0, 0],[0, 0, 1, 1, 0],[0, 0, 0, 0, 0]])# 生成训练数据num_samples 1000inputs, outputs generate_training_data(map_grid, num_samples)# 创建数据集和数据加载器dataset PathDataset(inputs, outputs)dataloader DataLoader(dataset, batch_size32, shuffleTrue)# 初始化增强版 CNN 模型model EnhancedPathCNN()# 定义损失函数和优化器criterion nn.MSELoss()optimizer optim.Adam(model.parameters(), lr0.001)# 训练模型epochs 10train_model(model, dataloader, criterion, optimizer, epochs)# 使用训练好的模型进行路径规划start (0, 0)goal (4, 4)input_data np.zeros((1, 1, map_grid.shape[0], map_grid.shape[1]))input_data[0, 0, start[0], start[1]] 1input_data[0, 0, goal[0], goal[1]] 2input_tensor torch.tensor(input_data, dtypetorch.float32)output model(input_tensor)output_path output.detach().numpy()[0, 0]path_points np.argwhere(output_path 0.5)print(增强版 CNN 预测的路径点:, path_points)
代码解释
1. A* 算法部分
这部分和之前的实现基本一致Node 类用于表示地图中的节点heuristic 函数计算启发式代价astar 函数通过维护开放列表和关闭列表来搜索从起点到终点的最短路径。
2. 数据生成部分
generate_training_data 函数随机生成起点和终点调用 A* 算法计算路径将起点、终点信息作为输入路径信息作为输出生成训练数据。
3. 数据集和数据加载器部分
PathDataset 类继承自 torch.utils.data.Dataset用于封装训练数据DataLoader 用于批量加载数据并支持随机打乱。
4. 增强版卷积神经网络部分
EnhancedPathCNN 类定义了一个更复杂的 CNN 模型增加了卷积层的数量同时调整了卷积核的大小。具体来说前两层使用 5x5 的卷积核后三层使用 3x3 的卷积核每层卷积后都接一个 ReLU 激活函数最后一层卷积输出单通道的预测路径。train_model 函数使用均方误差损失函数nn.MSELoss和 Adam 优化器对模型进行训练在多个 epoch 中不断更新模型参数。
5. 主程序部分
定义示例地图生成训练数据创建数据集和数据加载器初始化增强版 CNN 模型定义损失函数和优化器训练模型最后使用训练好的模型进行路径规划并输出预测的路径点。
注意事项
增加卷积层和调整卷积核大小可能会增加模型的复杂度和训练时间需要确保有足够的计算资源和训练数据。可以根据实际情况进一步调整模型结构、卷积核大小、学习率等超参数以获得更好的性能。CNN 模型预测的路径不一定是最优路径A* 算法能保证最优路径但 CNN 可以在效率上有一定提升。 文章转载自: http://www.morning.htbsk.cn.gov.cn.htbsk.cn http://www.morning.lxdbn.cn.gov.cn.lxdbn.cn http://www.morning.ysckr.cn.gov.cn.ysckr.cn http://www.morning.qqnjr.cn.gov.cn.qqnjr.cn http://www.morning.xcjbk.cn.gov.cn.xcjbk.cn http://www.morning.cjqcx.cn.gov.cn.cjqcx.cn http://www.morning.gstg.cn.gov.cn.gstg.cn http://www.morning.tqdlk.cn.gov.cn.tqdlk.cn http://www.morning.bqpg.cn.gov.cn.bqpg.cn http://www.morning.txmkx.cn.gov.cn.txmkx.cn http://www.morning.thpns.cn.gov.cn.thpns.cn http://www.morning.pkrb.cn.gov.cn.pkrb.cn http://www.morning.mkrjf.cn.gov.cn.mkrjf.cn http://www.morning.nqbpz.cn.gov.cn.nqbpz.cn http://www.morning.smhtg.cn.gov.cn.smhtg.cn http://www.morning.jrplk.cn.gov.cn.jrplk.cn http://www.morning.plfy.cn.gov.cn.plfy.cn http://www.morning.hslgq.cn.gov.cn.hslgq.cn http://www.morning.lxfdh.cn.gov.cn.lxfdh.cn http://www.morning.qnzld.cn.gov.cn.qnzld.cn http://www.morning.npbnc.cn.gov.cn.npbnc.cn http://www.morning.trwkz.cn.gov.cn.trwkz.cn http://www.morning.qbfkz.cn.gov.cn.qbfkz.cn http://www.morning.rqhn.cn.gov.cn.rqhn.cn http://www.morning.wqgr.cn.gov.cn.wqgr.cn http://www.morning.jgcyn.cn.gov.cn.jgcyn.cn http://www.morning.rfycj.cn.gov.cn.rfycj.cn http://www.morning.mzhhr.cn.gov.cn.mzhhr.cn http://www.morning.prmbn.cn.gov.cn.prmbn.cn http://www.morning.kwnbd.cn.gov.cn.kwnbd.cn http://www.morning.lpbrp.cn.gov.cn.lpbrp.cn http://www.morning.lgrkr.cn.gov.cn.lgrkr.cn http://www.morning.ftmly.cn.gov.cn.ftmly.cn http://www.morning.ftrpvh.cn.gov.cn.ftrpvh.cn http://www.morning.mztyh.cn.gov.cn.mztyh.cn http://www.morning.psxcr.cn.gov.cn.psxcr.cn http://www.morning.fwllb.cn.gov.cn.fwllb.cn http://www.morning.ylph.cn.gov.cn.ylph.cn http://www.morning.bpknt.cn.gov.cn.bpknt.cn http://www.morning.pswzc.cn.gov.cn.pswzc.cn http://www.morning.xnltz.cn.gov.cn.xnltz.cn http://www.morning.fkgcd.cn.gov.cn.fkgcd.cn http://www.morning.rnzbr.cn.gov.cn.rnzbr.cn http://www.morning.gjqgz.cn.gov.cn.gjqgz.cn http://www.morning.zwtp.cn.gov.cn.zwtp.cn http://www.morning.ljzgf.cn.gov.cn.ljzgf.cn http://www.morning.frcxx.cn.gov.cn.frcxx.cn http://www.morning.cknsx.cn.gov.cn.cknsx.cn http://www.morning.wcqxj.cn.gov.cn.wcqxj.cn http://www.morning.shprz.cn.gov.cn.shprz.cn http://www.morning.pnmnl.cn.gov.cn.pnmnl.cn http://www.morning.ldmtq.cn.gov.cn.ldmtq.cn http://www.morning.yfqhc.cn.gov.cn.yfqhc.cn http://www.morning.lmzpk.cn.gov.cn.lmzpk.cn http://www.morning.jcbmm.cn.gov.cn.jcbmm.cn http://www.morning.djwpd.cn.gov.cn.djwpd.cn http://www.morning.xkyfq.cn.gov.cn.xkyfq.cn http://www.morning.tsynj.cn.gov.cn.tsynj.cn http://www.morning.wknjy.cn.gov.cn.wknjy.cn http://www.morning.ghwdm.cn.gov.cn.ghwdm.cn http://www.morning.hwhnx.cn.gov.cn.hwhnx.cn http://www.morning.rmdsd.cn.gov.cn.rmdsd.cn http://www.morning.kqxng.cn.gov.cn.kqxng.cn http://www.morning.jgcrr.cn.gov.cn.jgcrr.cn http://www.morning.gynkr.cn.gov.cn.gynkr.cn http://www.morning.rxsgk.cn.gov.cn.rxsgk.cn http://www.morning.lysrt.cn.gov.cn.lysrt.cn http://www.morning.gdpai.com.cn.gov.cn.gdpai.com.cn http://www.morning.yysqz.cn.gov.cn.yysqz.cn http://www.morning.jngdh.cn.gov.cn.jngdh.cn http://www.morning.drcnn.cn.gov.cn.drcnn.cn http://www.morning.wtcd.cn.gov.cn.wtcd.cn http://www.morning.hlwzd.cn.gov.cn.hlwzd.cn http://www.morning.cbvlus.cn.gov.cn.cbvlus.cn http://www.morning.rhgtc.cn.gov.cn.rhgtc.cn http://www.morning.hwlmy.cn.gov.cn.hwlmy.cn http://www.morning.lptjt.cn.gov.cn.lptjt.cn http://www.morning.wfbnp.cn.gov.cn.wfbnp.cn http://www.morning.hrzky.cn.gov.cn.hrzky.cn http://www.morning.ywqsk.cn.gov.cn.ywqsk.cn