Gurobi的Python接口学习笔记和TSP问题求解案例

Gurobi求解器基础入门官方教程 Gurobi是一种数学规划(线性和凸二次规划)优化器。支持多种语言接口,本文以python+gurobi为主。 阅读详情

Basic Gurobi Concepts

在这里插入图片描述

  1. Parameters:参数用于控制求解器的行为,相关参数参考: https://docs.gurobi.com/projects/optimizer/en/current/concepts/parameters/groups.html
  2. Attributes:属性是查询和修改相关对象特征的机制,相关属性参考:https://docs.gurobi.com/projects/optimizer/en/current/concepts/attributes/types.html
  3. Environment:环境是Model的容器,gurobi的python接口会自动创建环境。设置环境的Parameters会让环境中的每个Model都默认这些Parameters,也可以单独为每个模型设置Parameters。

Python API Fundamentals

  1. Important global functions
    • setParam():设置环境的参数
    • read():从一个model文件中读取,创建
  2. Primary objects
    • Model
    • Var
    • Constr
  3. Other important methods
    • Model.setObjective(expression):传入Expr对象,创建目标函数
    • Model.optimize():开启优化
    • Model.reset():重置模型的状态,discarding any previously computed solution information.
  4. Model summary information methods
    • Model.printAtrr():Print the value of one or more attributes.
    • Model.printStatus():Print statistics about the model (number of constraints and variables, number of non-zeros in constraint matrix, smallest and largest coefficients, etc.).
    • Model.printQuality():Print statistics about the quality of the computed solution (constraint violations, integrality violations, etc.).
    • Model.getVars():Retrieve a list of all variables in the model.
    • Model.getConstrs():Retrieve a list of all linear constraints in the model.
    • Model.getRow():Retrieve the list of variables that participate in a constraint, and the associated coefficients. The result is returned as a LinExprobject.
    • Model.getCol():Retrieve the list of constraints in which a variable participates, and the associated coefficients. The result is returned as a Column object.

Model Generator Best Practices

在这里插入图片描述

使用Gurobi求解优化模型比较有条理的步骤如下:

  1. 先建模,建模可按以下步骤一步一步分析,避免脑袋绕晕
    1. 定义模型中要使用的集合
    2. 定义模型中要使用的参数
    3. 定义模型中要使用的决策变量
    4. 定义模型的目标函数
    5. 分析处模型设计的所有约束条件
  2. 然后使用Gurobi求解,具体又可按以下步骤进行
    1. 使用list或tuplelist对象保存集合(附:集合在模型中一般用作索引)
    2. 使用dict或tupledict对象保存参数
    3. 创建模型对象
      1. 添加变量
      2. 设置目标函数
      3. 添加约束条件
      4. 进行优化

tuplelist和tupledict相比list和dict的关系是什么?前者时专门为gurobi设计的,索引和运算能力更强大。

Iterating in Python and Aggregate Sums1

当遇到for-all这种建模结构时,使用Python的for循环语句很有帮助,考虑下面这样一个约束条件:
∑ j ∈ J x i j ≤ 5 , ∀ i ∈ I \sum_{j\in J}x_{ij}\le5,\quad \forall i\in I j∈J∑​xij​≤5,∀i∈I

for i in I:
	model.addConstr(gp.quicksum(x[i,j] for j in J)<=5)

先版本支持一种使用生成器的更简洁写法,只不过没有第一种好理解,

model.addConstrs((x.sum(i,'*')<=5 for i in I))

全局函数quicksum和tupledict对象的sum/prod方法的关系:(1)quicksum与sum方法相比更灵活,因为它可以接受任何可迭代的表达式,可以处理不同类型的变量和系数组合,甚至是复杂的表达式,只要它们最终可以相加。tupledict的 sum方法则局限于对 tupledict对象中的变量进行求和。(2)对于点积用tupledict对象的prod方法和全局函数quicksum进行计算没啥区别。

TSP Example2

TSP 问题最早的描述是1759年欧拉研究的骑士周游问题, 即对于国际象棋棋盘中的64 个方格, 走访64个方格一次且仅一次, 并最终返回起点。 其一般性描述为: 有一旅行商要访问 𝑛个城市, 每个城市必须访问且只能访问一次, 需要寻求到一条包含所有 𝑛个城市的最短访问路线。TSP问题的模型可以写为:
m i n z = ∑ ( i , j ) ∈ A , i ≠ j d i j x i j s . t . { ∑ j ≠ i x i j = 1 , ∀ i ∈ V ∑ i ≠ j x i j = 1 , ∀ j ∈ V u i − u j + ∣ V ∣ x i j ≤ ∣ V ∣ − 1 , ∀ ( i , j ) ∈ A , i ≠ j , i ≠ o , j ≠ 0 x i j = 0 或 1 , ( i , j ) ∈ A u i ≥ 0 , i ∈ V \begin{align} &min\quad z=\sum_{(i,j)\in A,i\ne j}d_{ij}x_{ij}\\s.t. &\left\{\begin{matrix} \sum_{j\ne i}x_{ij}&=1,&\forall i \in V\\ \sum_{i\ne j}x_{ij}&=1,&\forall j \in V\\ u_{i}-u_{j}+|V|x_{ij}&\le|V|-1,&\forall (i,j)\in A,i\ne j,i\ne o,j\ne 0\\ x_{ij}&=0或1,&(i,j)\in A\\ u_{i}&\ge0,&i\in V \end{matrix}\right. \end{align} s.t.​minz=(i,j)∈A,i=j∑​dij​xij​⎩ ⎨ ⎧​∑j=i​xij​∑i=j​xij​ui​−uj​+∣V∣xij​xij​ui​​=1,=1,≤∣V∣−1,=0或1,≥0,​∀i∈V∀j∈V∀(i,j)∈A,i=j,i=o,j=0(i,j)∈Ai∈V​​​
建模说明:

  • 集合
    • V:图中节点集合
    • A:途中所有弧的集合
  • 参数
    • d i j d_{ij} dij​:节点i和j之间的距离
  • 决策变量
    • x i j x_{ij} xij​是01变量,如果为1则表示从i走到j,否则不从i走到j
    • u i u_{i} ui​是为了使用MTZ约束引入的决策变量,可以理解为节点的访问次序?3
  • 目标函数:最小化总的旅行距离
  • 约束条件:从起点经过每一个点最后回到起点,即哈密顿回路约束——前两个约束表示图中任何一个点都离开1次到达1次,第三个约束叫做MTZ约束,用于消除子回路。此外,消除子回路还可以使用subtour-elimination,这个约束原理比较简单,通过枚举消除所有子回路,只留下最大的那个回路,但是在在gurobi里面得用回调函数写2,不方便。

求解说明,仍然以TSPLIB提供的brilin52算例进行实验,算例获取方式参考。

首先,导入需要使用的包,

import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import gurobipy as gp
from gurobipy import GRB

再把berlin52的数据读进来,

# 读取berlin52算例
def read_locations(loc):
    matrix = []
    with open(loc, 'r') as file:
        lines = file.readlines()
        start_reading = False
        for line in lines:
            if line.startswith('NODE_COORD_SECTION'):
                start_reading = True
                continue
            if line.startswith('EOF'):
                break
            if start_reading:
                parts = line.strip().split()
                if len(parts) == 3:
                    _, x, y = parts
                    matrix.append([float(x), float(y)])
    return np.array(matrix)

# 计算任意两地的距离
def calc_distances(city_locations):
    return np.array(([[math.sqrt(np.sum((loc1-loc2)**2)) for loc2 in city_locations]
             for loc1 in city_locations]))

city_locations = read_locations(loc=r"D:/待处理的文件/CodeSpace_for_spyder/遗传算法案例/berlin52/berlin52.tsp") # 读取到berlin52处地点的欧几里得坐标
distances = calc_distances(city_locations) # 计算出任意两地之间的距离矩阵

然后,按照我们上文提到过的Gurobi求解步骤,一步一步的写求解代码,避免脑袋绕晕,

# 定义模型中要用到的集合
V = [i for i in range(distances.shape[0])]
A = [(i,j) for i in range(distances.shape[0]) for j in range(distances.shape[0])]
# 定义模型中要用到的参数
d = gp.tupledict({(i,j):distances[i,j] for i in range(distances.shape[0]) for j in range(distances.shape[0])})
# 创建模型
model = gp.Model(name='TSP')
# 添加决策变量
x = model.addVars(A,vtype=GRB.BINARY,name='x') # x_{ij}
u = model.addVars(V,vtype=GRB.CONTINUOUS,name='u') # u_{i}
# 设置目标函数
model.setObjective(x.prod(d),sense=GRB.MINIMIZE)
# 添加约束条件
## 约束(1)
for i in V:
    model.addConstr(
        gp.quicksum(x[i,j] for j in V if j!=i) == 1
        )
## 约束(2)
for j in V:
    model.addConstr(
        gp.quicksum(x[i,j] for i in V if i!=j) == 1
        )
## 约束(3)
V_abs = len(V)
for i in V[1:]:
    for j in V[1:]:
        if i != j :
            model.addConstr(
                u[i]-u[j]+V_abs*x[i,j] <= V_abs-1
                )
# 进行优化
model.optimize()

最后,分析并可视化以下求解结果,

# 结果分析与可视化
if model.Status == GRB.OPTIMAL:
    print('最小巡游距离:{:.2f}'.format(model.ObjVal))
best_x = np.zeros((V_abs,V_abs)) # 用于存放最优解
for i in range(V_abs):
    for j in range(V_abs):
        best_x[i,j] = int(x[i,j].X)
pos1,pos2 = np.where(best_x) # 找到所有非0值对应索引,pos1是行索引,pos2是列索引
order = [] # 将最优解转换为访问次序,存储在order中
previous_point = pos1[0]
order.append(previous_point)
for _ in range(V_abs):
    order.append(pos2[previous_point])
    previous_point = pos2[previous_point]
print('巡游次序:');print(0,end='')
for i in range(1,V_abs):
    print('->{}'.format(order[i]),end='')
print('->0',end='')
mpl.rcParams['font.sans-serif']=['Times New Roman']
plt.close('all')
fig,ax = plt.subplots(dpi=150)
ax.scatter(city_locations[:,0],city_locations[:,1],c='r',alpha=0.5)
for i in range(V_abs):
    ax.plot([city_locations[order[i]][0],city_locations[order[i+1]][0]],
            [city_locations[order[i]][1],city_locations[order[i+1]][1]],c='b')
ax.set_title('TSP Tour');ax.set_xlabel('x');ax.set_ylabel('y')
plt.show()

在这里插入图片描述

求解结果,最优解与TSPLIB公布的最优值7542基本相近,比咱之前用遗传算法求解的结果好不少,这么看来Gurobi确实厉害,实验结束。

Optimal solution found (tolerance 1.00e-04)
Best objective 7.544365901904e+03, best bound 7.544365901904e+03, gap 0.0000%
最小巡游距离:7544.37
巡游次序:
0->21->30->17->2->16->20->41->6->1->29->22->19->49->28->15->45->43->33->34->35->38->39->36->37->47->23->4->14->5->3->24->11->27->26->25->46->12->13->51->10->50->32->42->9->8->7->40->18->44->31->48->0

  1. https://www.youtube.com/watch?v=vnLc_3VnVcw&t=2860s ↩︎

  2. https://blog.youkuaiyun.com/baidu/article/details/124844167 ↩︎ ↩︎

  3. https://blog.youkuaiyun.com/HsinglukLiu/article/details/107848461 ↩︎

论文代码复现 | 无人机与卡车联合配送(Python+Gurobi)(The flying sidekick traveling salesman problem) 无人机配送-代码复现The flying sidekick traveling salesman problem-Part 1文献笔记:(无人机配送-代码复现)The flying sidekick traveling salesman problem-Part 1摘要论文主要图标摘录数值实验算例结果参考文献 文献笔记:(无人机配送-代码复现)The flying sidekick traveling salesman problem-Part 1 摘要 Once limited to the milit 阅读详情

相关推荐

python求解TSP问题+gurobi+PSO(粒子群算法)

用两种方法通过python编程对TSP问题的求解 , 一是通过gurobi求解器求解 , 二是通过智能算法PSO(粒子群算法)进行求解 . 并画出最优路径 . 资源中包括TSP问题的数学模型 , 两种求解方法的python代码 , 以及求解结果图 . 是学习最优化算法的绝佳实践项目 . 另:包含生成随机城市代码 , 可随意调整问题规模 , 获取实验结果 .

【建模算法】Python调用Gurobi求解TSP问题

TSP (traveling salesman problem,旅行商问题)是典型的NP完全问题,即其最坏情况下的时间复杂度随着问题规模的增大按指数方式增长,到目前为止还未找到一个多项式时间的有效算法。本文探讨了Python调用Gurobi优化器求解TSP问题。

baidu的专栏 1万+

基于混合整数线性规划的旅行商问题求解(python+gurobi)

旅行商问题(TSP)是最著名的组合优化问题之一。 TSP的目标是找到访问每个城市一次并返回原始城市的最短路线。 在组合优化领域中,它被列为NP难题。

使用Gurobi求解TSP问题(Python)

使用Gurobi求解TSP问题,Python实现,适合gurobi初学者熟悉框架

TAO__HUI的博客 2666

【雷达图】R语言绘制雷达图(ggradar),NBA季后赛数据为例

一起用R语言给nba球星画球技雷达图吧!

池塘春草梦的博客 6252

Pytorch transformers tokenizer 分词器词汇表添加新的词语和embedding

NLP添加新词汇

7322

gurobi使用系列之一——gurobi+Python的实例使用(简单整数规划)

gurobi是由美国Gurobi公司开发的新一代大规模数学规划优化器,在 Decision Tree for Optimization Software 网站举行的第三方优化器评估中,展示出更快的优化速度和精度,成为优化器领域的新翘楚。 一个简单的整数规划实例,感受一下gurobi的魅力。 题目图片中缺少一个约束条件——每部电影至少放映一次。 ![整数规划题目](https://img-blog.csdnimg.cn/20200623101845260.jpg?x-oss-p....

sanpi329的博客 3万+

物体检测之非极大值抑制:NMS、softNMS、softerNMS、IoU-Net

当前的物体检测算法为了保证召回率,对于同一个真实物体往往会有多个的候选框输出。由于多余的候选框会影响检测精度,因此需要利用NMS过滤掉重叠的候选框,得到最佳的预测输出。当前有如下几种较为常见的NMS方法, 1.基本NMS 非极大值抑制, 顾名思义就是抑制不是极大值的边框,这里的抑制通常是直接去掉冗余的边框。 这个过程涉及以下两个量化指标: 1.预测得分:NMS假设一个边框的预测得分越高,这个框...

LeoLee 1941

模拟退火+Gurobi 解决 旅行家问题TSP

模拟退火算法,顾名思义,模拟晶体退火过程。晶体在加热后固体化为液态,内部原子运动加剧,会离开原有位置向四周扩散。此时慢慢进行退火冷却使其重新固化,粒子往往会停留在比原先能量低得多的位置上,本质上也是通过随机性跳出局部最优。 本文尝试用模拟退火算法对TSP问题(travelling salesman problem)进行求解,并与Gurobi求解器进行对比。

weixin_52435933的博客 1202

计算机组成原理实验:手把手教你用模拟程序实现中断机制(附完整代码)

本文通过一个计算机组成原理模拟实验,手把手教你从零实现一个可工作的中断系统。实验详细演示了如何配置中断控制器、编写主程序与中断服务程序,并观察中断响应、现场保护和恢复的全过程,深入解析了中断原理的核心机制。

471

用 ABAP CDS 把树建起来:Hierarchy 的建模、调试与消费全流程

CDS Hierarchy 将树形数据结构作为一等公民引入 ABAP 开发,通过定义父子关联、根节点条件和兄弟排序规则,让数据库原生支持层级查询。相比传统递归处理方式,它能避免性能瓶颈,提供$node系统字段描述节点结构信息,并支持与SAP UI框架无缝集成。这种方法简化了组织架构、成本中心等业务场景的层级数据处理,使开发人员能够专注于业务逻辑而非底层实现。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 205

运筹学修炼日记:TSP中两种不同消除子环路的方法及callback实现(Python调用Gurobi求解,附以王者荣耀视角解读callback的工作逻辑)

Python调用Gurobi实现列生成求解TSP运筹学修炼日记:Python调用Gurobi实现列生成求解TSP--两种不同消除子环路的方法TSP问题的一般模型TSP Model 1: `subtour-elimination` 消除子环路模型Python调用Gurobi实现的问题TSP Model 1 : MTZ约束消除子环路为什么`MTZ`约束可以消除子环路?Python+Gurobi: 用callback实现TSP的`subtour-elimination`Python+Gurobi: 实现TSP的`

HsinglukLiu的博客 1万+

【GameFramework框架内置模块】10、本地化(Localization)

本地化(Localization),也就是我们所说的不同地区的语言适配,比如说中文版“你好”,英文版是“Hello”。GameFramework在本地化方面,不仅支持文本的本地化,还支持任意资源的本地化,比如说游戏中释放烟花的特效也可以做出不同地区的版本,使得中文版烟花里面的“新年好”字样的特效,在英文版里面是“Happy New Year”字样的特效。

优快云博客专家,Unity3D高级软件工程师,《Unity 3D从入门到实战》作者。 2301

TSP问题求解环绕中国的最短路线

TSP问题求解环绕中国省份的最短路线

gaopan812的博客 2314

自动驾驶系统研发系列—全智能驾驶新高度:深入解析车道保持辅助(ELK)功能

车道保持辅助系统(ELK)是一种基于先进视觉感知技术的主动安全系统,能够通过车载摄像头实时监测道路上的车道线、道路边缘以及周围车辆的位置。这一功能的核心在于为驾驶员提供智能化的安全辅助,尤其是在驾驶员可能因疲劳、分心或其他原因无意识地偏离车道时,系统能够主动干预,从而避免危险发生。ELK系统不仅仅依靠摄像头对道路进行感知,还结合其他传感器的数据(如雷达),实时评估自车与车道线、周边车辆的相对位置。当系统检测到车辆即将偏离车道,或越过道路边缘时,ELK会通过控制电子助力转向系统(EPS)

u013889591的专栏 1211

YOLOv11低照度目标检测优化方案:基于SCINet可训练预处理主干的全流程实现指南

创建一个新的Python文件,如。

FJN110的博客 188

路径规划问题数学模型及Python+Gurobi求解(旅行商TSP/容量约束CVRP/时间窗约束VRPTW/取送货PDPTW)

对路径规划四大类问题进行建模求解:(1)TSP旅行商问题(2)CVRP带容量约束(3)VRPTW带时间窗约束(4)PDPTW带取送货约束,分别给出数学模型和Guro bi求解代码

weixin_45526117的博客 7009

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

基于禁忌搜索算法的TSP问题建模求解

禁忌搜索算法(Tabu Search,TS)的思想最早由美国工程院院士Glover教授于1986年提出,并在1989年和1990年对该方法做出了进一步的定义和发展。在自然计算的研究领域中,禁忌搜索算法以其灵活的存储结构和相应的禁忌准则来避免迂回搜索,在智能算法中独树一帜,成为一个研究热点,受到了国内外学者的广泛关注。迄今为止,禁忌搜索算法在组合优化、生产调度、机器学习、电路设计和神经网络等领域取得了很大的成功。

博客简介 1350

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

rn 调用子组件方法_优化│TSP中两种不同消除子环路的方法及callback实现(Python调用Gurobi求解)...

@TSP Model 1: `subtour-elimination` 消除子环路TSP整数规划模型Python调用Gurobi实现中的一些小问题TSP Model 2 : MTZ约束消除子环路MTZ约束消除子环路为什么`MTZ`约束可以消除子环路?`callback`的工作逻辑: 王者荣耀版独家解读使用`callback`的通用步骤`callback`实现`subtour-elimination...

weixin_39833290的博客 1039

rn 调用子组件方法_优化 | TSP中两种不同消除子环路的方法及Callback实现(Python调用Gurobi求解)...

以下文章来源于运筹OR帷幄,作者刘兴禄TSP Model 1:subtour-elimination消除子环路TSP整数规划模型Python调用Gurobi实现中的一些小问题TSP Model 2 :MTZ约束消除子环路MTZ约束消除子环路为什么MTZ约束可以消除子环路?Callback的工作逻辑: 王者荣耀版独家解读使用Callback的通用步骤Callback实现subtour-el...

weixin_42470145的博客 795

使用Gurobi与Python精确求解旅行商问题:建模、回调与优化实践

组合优化是运筹学与计算机科学的核心领域,旨在从有限集合中寻找最优解。其原理通常涉及将实际问题抽象为数学模型,如整数规划,并通过算法在可行解空间中搜索。这类技术的核心价值在于为物流、调度、资源分配等复杂决策问题提供精确或近似最优方案,广泛应用于供应链管理、电路设计、路径规划等场景。本文聚焦于经典的旅行商问题,探讨如何利用Gurobi这一强大的商业求解器及其Python接口gurobipy,通过混合整数规划建模与动态约束添加(回调函数)技术,实现高效、可靠的精确求解。文中将详细解析子回路消除、惰性约束等关键热词

weixin_34408624的博客 401

本类中怎么调用自己的方法_优化 | TSP中两种不同消除子环路的方法及Callback实现(Python调用Gurobi求解)...

以下文章来源于运筹OR帷幄,作者刘兴禄TSP Model 1:subtour-elimination消除子环路TSP整数规划模型Python调用Gurobi实现中的一些小问题TSP Model 2 :MTZ约束消除子环路MTZ约束消除子环路为什么MTZ约束可以消除子环路?Callback的工作逻辑: 王者荣耀版独家解读使用Callback的通用步骤Callback实现subtour-el...

weixin_39876877的博客 864

pannel添加的子窗体很大_优化│TSP中两种不同消除子环路的方法及callback实现(Python调用Gurobi求解)...

@TSP Model 1: `subtour-elimination` 消除子环路TSP整数规划模型Python调用Gurobi实现中的一些小问题TSP Model 2 : MTZ约束消除子环路MTZ约束消除子环路为什么`MTZ`约束可以消除子环路?`callback`的工作逻辑: 王者荣耀版独家解读使用`callback`的通用步骤`callback`实现`subtour-elimination...

weixin_39839968的博客 837

模拟退火、禁忌搜索、迭代局部搜索求解TSP问题Python代码分享

本文来源于公众号【程序猿声】,作者舟寒丶 写在前面 众所周知,python是近几年来最火的语言之一,也因为容易上手、代码简洁深受各位刚刚接触编程的同学的喜爱。小编这学期也有一门python的课程。 然而,公众号内代码基本通过C++、Java编写,很少有python。但是还是有部分童鞋想要python代码。 还有同学发出疑问:为什么不用python? 为了熟悉python,同时本着...

infinitor的博客 663

2.1. Gurobi建模介绍

Gurobi简介2.1. Gurobi建模介绍模型类模型的Attribute创建模型决策变量决策变量类型加决策变量决策变量的Attribute线性表达式线性表达式非线性表达式约束添加线性约束添加非线性约束加General约束添加Range约束约束的Attribute目标函数添加目标函数目标函数的Attribute求解模型求解模型求解模型参数设置输出解的结果参数设置和调优2.2 Gurobi的简单应用案例简单LPAssignment Problem按行建模按列建模文件读入2.3 Gurobi的高级应用Call

HsinglukLiu的博客 4845
上一篇: Gurobi求解相关问题的python源码学习
下一篇: Git学习笔记
SACUKI
博客等级 码龄5年 139粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值