markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
我们看看http://localhost:4040 可以查看运行的Job
linesWithSpark = lines.filter(lambda line: 'spark' in line) linesWithSpark.count()
Python数据科学101.ipynb
liulixiang1988/documents
mit
This notebook shows an analysis of the Falcon-9 upper stage S-band telemetry frames. It is based on r00t.cz's analysis. The frames are CCSDS Reed-Solomon frames with an interleaving depth of 5, a (255,239) code, and an (uncoded) frame size of 1195 bytes.
x = np.fromfile('falcon9_frames_20210324_084608.u8', dtype = 'uint8') x = x.reshape((-1, 1195))
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
The first byte of all the frames is 0xe0. Here we see that one of the frames has an error in this byte.
collections.Counter(x[:,0])
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
The next three bytes form a header composed of a 13 bit frame counter and an 11 bit field that indicates where the first packet inside the payload starts (akin to a first header pointer in CCSDS protocols).
header = np.unpackbits(x[:,1:4], axis = 1) counter = header[:,:13] counter = np.concatenate((np.zeros((x.shape[0], 3), dtype = 'uint8'), counter), axis = 1) counter = np.packbits(counter, axis = 1) counter = counter.ravel().view('uint16').byteswap() start_offset = header[:,-11:] start_offset = np.concatenate((np.zeros((x.shape[0], 5), dtype = 'uint8'), start_offset), axis = 1) start_offset = np.packbits(start_offset, axis = 1) start_offset = start_offset.ravel().view('uint16').byteswap() plt.plot(counter, '.') plt.title('Falcon-9 frame counter') plt.ylabel('13-bit frame counter') plt.xlabel('Decoded frame');
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Valid packets contain a 2 byte header where the 4 MSBs are set to 1 and the remaining 12 bits indicate the size of the packet payload in bytes (so the total packet size is this value plus 2). Using this header, the packets can be defragmented in the same way as CCSDS Space Packets transmitted using the M_PDU protocol.
def packet_len(packet): packet = np.frombuffer(packet[:2], dtype = 'uint8') return (packet.view('uint16').byteswap()[0] & 0xfff) + 2 def valid_packet(packet): return packet[0] >> 4 == 0xf def defrag(x, counter, start_offset): packet = bytearray() frame_count = None for frame, count, first in zip(x, counter, start_offset): frame = frame[4:] if frame_count is not None \ and count != ((frame_count + 1) % 2**13): # broken stream packet = bytearray() frame_count = count if first == 0x7fe: # only idle continue elif first == 0x7ff: # no packet starts if packet: packet.extend(frame) continue if packet: packet.extend(frame[:first]) packet = bytes(packet) yield packet, frame_count while True: packet = bytearray(frame[first:][:2]) if len(packet) < 2: # not full header inside frame break first += 2 if not valid_packet(packet): # padding found packet = bytearray() break length = packet_len(packet) - 2 packet.extend(frame[first:][:length]) first += length if first > len(frame): # packet does not end in this frame break packet = bytes(packet) yield packet, frame_count packet = bytearray() if first == len(frame): # packet just ends in this frame break packets = list(defrag(x, counter, start_offset))
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Only ~76% of the frames payload contains packets. The rest is padding.
sum([len(p[0]) for p in packets])/x[:,4:].size
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
After the 2 byte header, the next 8 bytes of the packet can be used to identify its source or type.
source_ids = [p[0][2:10].hex().upper() for p in packets] collections.Counter(source_ids)
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Some packets have 64-bit timestamps starting 3 bytes after the packet source ID. These give nanoseconds since the GPS epoch.
timestamps = np.datetime64('1980-01-06') + \ np.array([np.frombuffer(p[0][13:][:8], dtype = 'uint64').byteswap()[0] for p in packets]) \ * np.timedelta64(1, 'ns') timestamps_valid = (timestamps >= np.datetime64('2021-01-01')) & (timestamps <= np.datetime64('2022-01-01')) plt.plot(timestamps[timestamps_valid], np.array([p[1] for p in packets])[timestamps_valid], '.') plt.title('Falcon-9 packet timestamps') plt.xlabel('Timestamp (GPS time)') plt.ylabel('Frame counter');
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Video packets Video packets are stored in a particular source ID. If we remove the first 25 and last 2 bytes of these packets, we obtain 5 188-byte transport stream packets.
video_source = '01123201042E1403' video_packets = [p for p,s in zip(packets, source_ids) if s == video_source] video_ts = bytes().join([p[0][25:-2] for p in video_packets])
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
Only around 28% of the transmitted data is the transport stream video.
len(video_ts)/sum([len(p[0]) for p in packets]) with open('/tmp/falcon9.ts', 'wb') as f: f.write(video_ts) ts = np.frombuffer(video_ts, dtype = 'uint8').reshape((-1,188)) # sync byte 71 = 0x47 np.unique(ts[:,0]) # TEI = 0 np.unique(ts[:,1] >> 7) pusi = (ts[:,1] >> 6) & 1 # priority = 0 np.unique((ts[:,1] >> 5) & 1) pid = ts[:,1:3].ravel().view('uint16').byteswap() & 0x1fff np.unique(pid) for p in np.unique(pid): print(f'PID {p} ratio {np.average(pid == p) * 100:.1f}%') # TSC = 0 np.unique(ts[:,3] >> 6) adaptation = (ts[:,3] >> 4) & 0x3 np.unique(adaptation) continuity = ts[:,3] & 0xf for p in np.unique(pid): print('PID', p, 'PUSI values', np.unique(pusi[pid == p]), 'adaptation field values', np.unique(adaptation[pid == p])) pcr_pid = ts[pid == 511] pcr = np.concatenate((np.zeros((pcr_pid.shape[0], 2), dtype = 'uint8'), pcr_pid[:,6:12]), axis = 1) pcr = pcr.view('uint64').byteswap().ravel() pcr_base = pcr >> 15 pcr_extension = pcr & 0x1ff pcr_value = (pcr_base * 300 + pcr_extension) / 27e6 video_timestamps = timestamps[[s == video_source for s in source_ids]] ts_timestamps = np.repeat(video_timestamps, 5) pcr_pid_timestamps = ts_timestamps[pid == 511] plt.plot(pcr_pid_timestamps, pcr_value, '.') plt.title('Falcon-9 PCR timestamps') plt.ylabel('PID 511 PCR (s)') plt.xlabel('Packet timestamp (GPS time)');
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
GPS log
gps_source = '0117FE0800320303' gps_packets = [p for p,s in zip(packets, source_ids) if s == gps_source] gps_log = ''.join([str(g[0][25:-2], encoding = 'ascii') for g in gps_packets]) with open('/tmp/gps.txt', 'w') as f: f.write(gps_log) print(gps_log)
Falcon-9/Falcon-9 frames.ipynb
daniestevez/jupyter_notebooks
gpl-3.0
元组中为不可变序列, 具体体现为元组元素__指向__的内存地址不能变, 但是如果元素为可变类型, 那元素的内容可变.
t1[0] = 2 t1[1] = 6.66 t1[2] = ("variadic",) t1[3].append("world") print(t1)
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
list列表 列表是可变序列,通常用于存放同类项目的集合, 通常用于储存相同类型的数据.当然也可以储存不同类型的数据.
# 与tuple相同, 可以直接使用 [] 或者 list() 来声明一个空数组 print( [], type([]), list(), type(list()) ) # 与tuple不同的是, 在声明单个元素的时候不需要在元素之后多写一个 , [1], type([1]) list1 = [1, 2.33, ("tuple",), ["hello"]]
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
另一个与tuple不同的是, list中元素指向的内存地址是可变的. 这就意味着我们能修改元素的指向
list1[0] = 2 # 这里同时修改了类型 list1[1] = "6.66" # 思考是否可以这样修改, 为什么? list1[2][0] = "variadic" # 思考是否可以这样修改, 为什么? list1[2] = "variadic" list1[3].append("world") print(list1)
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
比较常用的是, 我们可以使用sort方法来排序列表中的字段
list2 = [1, 2, 0, -1, 9, 7, 6, 5] list2.sort() list2
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
range对象 对于range对象, 我们之前有简单的介绍过, 这里我们复习一下. range类型表示不可变的数字序列,一般用于在 for 循环中循环指定的次数。 range 类型相比常规 list 或 tuple 的优势在于一个 range 对象总是占用固定数量的(较小)内存. 不论其所表示的范围有多大(因为它只保存了 start, stop 和 step 值,并会根据需要计算具体单项或子范围的值)
# 只传递一个参数的话, 表示从`0`开始到`X`的序列 list(range(10)) # 如果传递2个参数, 表示从`i`到`j`之间的序列 list(range(2, 8)) # 如果传递了3个参数, 表示从`i`到`j`步长为`k`的序列 list(range(0, 10, 2))
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
扩展阅读, 其实range的简单实现其实看做是一个生成器, 当然实际的range不是一个生成器这么简单
def my_range(stop: int): start = 0 while start != stop: yield start start += 1 list(my_range(10))
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
容器中的基本操作 判断元素是否存在于一个容器中 使用in或者not in来判断一个元素是否存在于一个容器中
1 in [1, 2, 3], 2 not in [1, 2, 3]
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
容器拼接 在Python中我们可以非常简单的使用+进行容器的拼接.
[1, 2, 3] + [4, 5, 6] (1, 2, 3) + (4, 5, 6) [1, 2, 3] + list(range(4, 10))
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
重复容器内元素 在Python中可以将一个容器 * 一个整数, 可以得到这个容器重复 X 次的结果.
[[]] * 3, [[1, [2, ]]] * 3 list(range(5)) * 3
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
其余操作 使用len()获取容器的长度 使用min()获取容器中的最小项 使用max()获取容器中的最大项 使用s.count(x)获取容器s中x出现的次数
len([]), len([()]), len(([], [], [])), len(range(10)) min([1, 2, 3, 4, -1]), max([1, 2, 3, 4, -1]) import random list3 = [] for _ in range(1000): list3.append(random.randint(0, 10)) print(list3.count(6))
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
容器切片(重点) 在Python中, 切片是非常好用且非常常用的一个特性. 使用[i]获取第i项数据(从0开始) 使用[i:j]获取从i到j的切片(左闭右开) 使用[i:j:k]获取i到j步长为k的切片
list4 = list(range(10)); print(list4) # python中支持使用负数作为索引, 表示从尾部开始取, 注意: 负数的起始值为 -1 list4[-1], list4[-2], list4[-3] # 获取一个切片, 从第2个元素到底6个元素 list4[2:6] # 如果不写 i 表示从头部开始取 list4[:5] # 如果不写 j 表示取到尾部为止 list4[5:] # 思考: 如果 i 和 j 都不写, 那会打印什么? list4[:] # 第三个参数为步长参数, 表示每次隔几个元素取一次值 list4[1:8:2] # 思考1: 如何反转一个容器? # 思考2: 如下打印什么 list4[::]
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
集合类型 Python中的集合类型有set和frozenset(较少使用, 表示创建之后不可修改, 可以简单看做是tuple版本的set). set对象和frozenset对象是由具有唯一性的 hashable 对象所组成的__无序__多项集. 常见的用途包括成员检测、从序列中去除重复项以及数学中的集合类计算,例如交集、并集、差集与对称差集等等。
set1 = set([1, 2, 3, 1, 4, 5, 5, 2]) set1.update([6, 7, 2, 3]); print(set1) fset1 = frozenset([1, 2, 3, 1, 4, 5, 5, 2]) # 可以使用 dir 来打印一个对象所包含的所有内容 print(dir(fset1))
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
映射类型 在Python中仅有一种映射类型, 即dict. 即javascript中的对象, php中的命名数组. 映射属于无序可变对象. 字典的键 几乎 可以是任何值。 非 hashable 的值,即包含列表、字典或其他可变类型的值(此类对象基于值而非对象标识进行比较)不可用作键。 数字类型用作键时遵循数字比较的一般规则:如果两个数值相等 (例如 1 和 1.0) 则两者可以被用来索引同一字典条目。 (但是请注意,由于计算机对于浮点数存储的只是近似值,因此将其用作字典键是不明智的。)
dict1 = { "key1": "value1", 123: 456, 123.0: 789, ("k", "e", "y"): ("k", "e", "y") } print(dict1) # 如果获取字典中不存在的键, 则会发生KeyError错误 dict1["key2"] # 为了避免这个问题我们可以使用get方法获取字典中的值, 并自定义获取不到的时候返回的默认值 dict1.get("key2", "default value") # 这里我们可以更近一步, 使用setdefault方法来当获取不到指定键的值的时候自动新增一个默认值, 并且返回默认值 print(dict1.setdefault("key2", "default value and set")) print(dict1) # 但是可以给字典中不存在的键赋值 dict1["key3"] = "value3" print(dict1) # 在字典上, 我们也可以使用`in`和`not in`判断一个键是否存在于一个字典中 "key1" in dict1, "key2" not in dict1
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
常用的原生扩展容器 Python中的常用原生扩展容易位于包collections中 namedtuple命名元组: 简易的纯属性类声明方式, 实际上是一个元组 deque双向链表: 用于解决需要频繁插入删除的业务下原生list效率太差的问题 OrderedDict有序字典: 用于解决原生dict无序的问题 namedtuple命名元组
from collections import namedtuple Pointer = namedtuple('Pointer', 'x y') Coordinate = namedtuple('Coordinate', 'x, y, z') start, end = Pointer(0, 0), Pointer(9, 9) coord1, coord2 =Coordinate(0, 0, 0), Coordinate(9, 9, 9) print(start, end, coord1, coord2) print(start.x, start.y) print(coord2.x, coord2.y, coord2.z)
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
deque双向链表
from collections import deque print(dir(deque()))
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
OrderedDict有序字典
from collections import OrderedDict od = OrderedDict() od["k1"] = 123 od["k2"] = 123 od["k3"] = 123 for k, v in od.items(): print(k, v)
python/course/ch02-syntax-and-container/常用容器.ipynb
JShadowMan/package
mit
En la red anterior el arco $(D, E)$ tiene costo igual a $3$ y el arco $(E, D)$ tiene costo igual a $2$. ```{margin} Obsérvese que es ligeramente distinta la nomenclatura de este problema en cuanto a los términos de flujo neto y demanda que tiene un nodo de acuerdo a lo que se describe en el {ref}ejemplo de flujo de costo mínimo &lt;EJREDFLUJOCOSTOMIN&gt; ``` Al lado de cada nodo en corchetes se presenta el flujo neto generado por el nodo. Los nodos origen tienen un flujo neto positivo y en la red son los nodos "A" y "B" (por ejemplo fábricas). Los nodos destino tienen un flujo neto negativo que en la red son los nodos "D" y "E" (por ejemplo clientes). El único nodo de transbordo es el nodo "C" que tiene flujo neto igual a cero (centro de distribución por ejemplo). Los valores de los costos se muestran en los arcos. Es una red sin capacidades. Entonces el modelo de PL que minimiza el costo de transferencia de flujo de modo que el flujo neto satisfaga lo representado en la red, considerando el flujo neto como el flujo total que sale del nodo menos el flujo total que entra al nodo es: $$\displaystyle \min_{x \in \mathbb{R}^7} 2 x_{AB} + 4 x_{AC} + 9 x_{AD} + 3 x_{BC} + x_{CE} + 3 x_{DE} + 2x_{ED}$$ $$\text{sujeto a: }$$ $$ \begin{eqnarray} &x_{AB}& + &x_{AC}& + &x_{AD}& && && && && &=& 50 \nonumber \ &-x_{AB}& && && + &x_{BC}& && && && &=& 40 \nonumber \ && - &x_{AC}& && - &x_{BC}& + &x_{CE}& && && &=& 0 \nonumber \ && && - &x_{AD}& && && + &x_{DE}& - &x_{ED}& &=& -30 \nonumber \ && && && && - &x_{CE}& - &x_{DE}& + &x_{ED}& &=& -60 \nonumber \end{eqnarray} $$ $$x_{ij} \geq 0 \forall i,j$$ La primer restricción de igualdad representa el flujo neto para el nodo $A$ y la última el flujo neto para el nodo $E$. A tales ecuaciones de las restricciones de igualdad se les conoce con el nombre de ecuaciones de conservación de flujo. ```{admonition} Observación :class: tip Obsérvese que la matriz que representa a las restricciones de igualdad es la matriz de incidencia nodo-arco. Ver {ref}Representación de redes: matriz de incidencia nodo-arco &lt;MATINCIDNODOARCO&gt; ``` ```{margin} Multiplicamos por $-1$ pues el resultado de la función incidence_matrix está volteado respecto a la definición de la matriz de incidencia nodo-arco. ```
print(-1*nx.incidence_matrix(G_min_cost_flow, oriented=True).todense())
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
El problema anterior lo podemos resolver directamente con scipy-optimize-linprog que es una función que resuelve PL's:
c = np.array([2, 4, 9, 3, 1, 3, 2]) A_eq = -1*nx.incidence_matrix(G_min_cost_flow, oriented=True).todense() print(A_eq) b = list(nx.get_node_attributes(G_min_cost_flow, "netflow").values())
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Cada tupla hace referencia a las cotas inferiores y superiores que tiene cada variable. ```
bounds = [(0, None), (0,None), (0,None), (0,None), (0,None), (0, None), (0, None)] print(linprog(c=c, A_eq=A_eq, b_eq=b,bounds=bounds))
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Los solvers son paquetes de software para resolver modelos de programación lineal y modelos relacionados que se encuentran en los lenguajes de modelado. ``` ```{margin} Se instala cvxopt, un paquete de Python para resolver problemas de optimización convexa que ya trae el solver GLPK, ver cvxpy: install-with-cvxopt-and-glpk-support. ``` También con cvxpy podemos resolver el PL anterior. Para mostrar la flexibilidad que tienen los lenguajes de modelado como cvxpy se define $x$ como variable entera. cvxpy puede resolver este tipo de problemas si se instala el solver GLPK :
!pip install --quiet cvxopt
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Ver cvxpy: linear_program ```
import cvxpy as cp n = 7 #number of variables x = cp.Variable(n, integer=True) #x as integer optimization variable fo_cvxpy = c.T@x #objective function constraints = [A_eq@x == b, x >=0 ] opt_objective = cp.Minimize(fo_cvxpy) prob = cp.Problem(opt_objective, constraints) print(prob.solve()) # Print result. print("\nThe optimal value is", prob.value) print("A solution x is") print(x.value)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
(EJPROTOTIPO)= Ejemplo prototipo Supóngase que una compañía tiene tres plantas en las que se producen dos productos. La compañía nos entrega los siguientes datos relacionados con: Número de horas de producción disponibles por semana en cada planta para fabricar estos productos. Número de horas de fabricación para producir cada lote de los productos. La ganancia por lote de cada producto. Lo anterior se resume en la siguiente tabla: | |Tiempo de producción por lote en horas ||| |:---:|:---:|:---:|:---:| | Planta |Producto 1|Producto 2| Tiempo de producción disponible a la semana en horas| |1|1|0|4| |2|0|2|12| |3|3|2|18| |Ganancia por lote| 3000| 5000|| La tabla anterior indica en su primer renglón que cada lote del producto 1 que se produce por semana emplea una hora de producción en la planta 1 y sólo se dispone de 4 horas semanales (recursos disponibles). Como se lee en la tabla, cada producto se fabrica en lotes de modo que la tasa de producción está definida como el número de lotes que se producen a la semana. Obsérvese que el producto 1 requiere parte de la capacidad de producción en las plantas 1, 3 y nada en la planta 2. El producto 2 necesita trabajo en las plantas 2 y 3. Por lo anterior no está claro cuál mezcla de productos sería la más rentable. Se permite cualquier combinación de tasas de producción que satisfaga estas restricciones, incluso no fabricar uno de los productos y elaborar todo lo que sea posible del otro. La tasa de producción está definida como el número de lotes que se producen a la semana. Se desea determinar cuáles tasas de producción (no negativas) deben tener los dos productos con el fin de maximizar las ganancias totales sujetas a las restricciones impuestas por las capacidades de producción limitadas disponibles en las tres plantas. Se asume que las plantas únicamente destinan su producción a estos dos productos y la ganancia incremental de cada lote adicional producido es constante sin importar el número total de lotes producidos. La ganancia total de cada producto es aproximadamente la ganancia por lote que se produce multiplicada por el número de lotes. Se modela el problema anterior como un PL con las siguientes variables: $x_1$: número de lotes del producto 1 que se fabrican por semana. $x_2$: número de lotes del producto 2 que se fabrican por semana. $f_o(x_1, x_2)$: ganancia semanal total (en miles de pesos) que generan estos dos productos. Se debe resolver el PL siguiente: $$\displaystyle \max_{x \in \mathbb{R}^2} 3x_1 + 5x_2$$ $$\text{sujeto a: }$$ $$x_1 \leq 4$$ $$2x_2 \leq 12$$ $$3x_1 + 2x_2 \leq 18$$ $$x_1 \geq 0, x_2 \geq 0$$ El término $3x_1$ representa la ganancia generada (en miles de pesos) cuando se fabrica el producto 1 a una tasa de $x_1$ lotes por semana. Se tienen contribuciones individuales de cada producto a la ganancia. Modelo de PL Algunas características generales de los problemas de PL se presentan a continuación Terminología en PL |Ejemplo prototipo | Problema general| |:---:|:---:| |Capacidad producción de las plantas | Recursos| |3 plantas | m recursos | |Fabricación de productos | Actividades | |2 productos | n actividades| |Tasa de producción del producto | Nivel de la actividad| |Ganancia | Medida global de desempeño| Y en la terminología del problema general se desea determinar la asignación de recursos a ciertas actividades. Lo anterior implica elegir los niveles de las actividades (puntos óptimos) que lograrán el mejor valor posible (valor óptimo) de la medida global de desempeño. En el PL: $f_o$: valor de la medida global de desempeño (función objetivo). $x_j$: nivel de la actividad $j$ con $j=1, 2, \dots, n$. También se les conoce con el nombre de variables de decisión (variables de optimización). $c_j$: incremento en $f_o$ que se obtiene al aumentar una unidad en el nivel de la actividad j. $b_i$: cantidad de recurso $i$ disponible para asignarse a las actividades con $i=1, 2, \dots, m$. $a_{ij}$: cantidad del recurso $i$ consumido por cada unidad de la actividad $j$. ```{admonition} Observación :class: tip Los valores de $c_j, b_i, a_{ij}$ son las constantes o parámetros del modelo. ``` Formas de un PL Es posible que se encuentren con PL en diferentes formas por ejemplo: 1.Minimizar en lugar de maximizar la función objetivo. 2.Restricciones con desigualdad en sentido mayor, menor o igual que. 3.Restricciones en forma de igualdad. 4.Variables de decisión sin la restricción de no negatividad (variables libres). Pero siempre que se cumpla con que la función objetivo y las restricciones son funciones lineales entonces tal problema se clasifica como un PL. ```{admonition} Observación :class: tip Si se utiliza un PL con otras formas diferentes a la del ejemplo prototipo (por ejemplo variables libres en lugar de no negativas) es posible que la interpretación de "asignación de recursos limitados entre actividades que compiten" puede ya no aplicarse muy bien; pero sin importar cuál sea la interpretación o el contexto, lo único necesario es que la formulación matemática del problema se ajuste a las formas permitidas. ``` (EJMETGRAFICOPL)= Ejemplo: método gráfico A continuación se muestra un procedimiento gráfico para resolver el PL del ejemplo prototipo. Esto es posible realizar pues tenemos sólo dos variables. Se tomará $x_1$ como el eje horizontal y $x_2$ el eje vertical. Recordando las variables del ejemplo prototipo: $x_1$: número de lotes del producto 1 que se fabrican por semana. $x_2$: número de lotes del producto 2 que se fabrican por semana. $f_o(x_1, x_2)$: ganancia semanal total (en miles de pesos) que generan estos dos productos. Y el PL es: $$\displaystyle \max_{x \in \mathbb{R}^2} 3x_1 + 5x_2$$ $$\text{sujeto a: }$$ $$x_1 \leq 4$$ $$2x_2 \leq 12$$ $$3x_1 + 2x_2 \leq 18$$ $$x_1 \geq 0, x_2 \geq 0$$ Entonces se tiene la siguiente región definida por las desigualdades del PL:
#x_1 ≤ 4 point1_x_1 = (4,0) point2_x_1 = (4, 10) point1_point2_x_1 = np.row_stack((point1_x_1, point2_x_1)) #x_1 ≥ 0 point3_x_1 = (0,0) point4_x_1 = (0, 10) point3_point4_x_1 = np.row_stack((point3_x_1, point4_x_1)) #2x_2 ≤ 12 or x_2 ≤ 6 point1_x_2 = (0, 6) point2_x_2 = (8, 6) point1_point2_x_2 = np.row_stack((point1_x_2, point2_x_2)) #x_2 ≥ 0 point3_x_2 = (0, 0) point4_x_2 = (8, 0) point3_point4_x_2 = np.row_stack((point3_x_2, point4_x_2)) #3x_1 + 2x_2 ≤ 18 x_1_region_1 = np.linspace(0,4, 100) x_2_region_1 = 1/2*(18 - 3*x_1_region_1) x_1 = np.linspace(0,6, 100) x_2 = 1/2*(18 - 3*x_1) plt.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], point3_point4_x_1[:,0], point3_point4_x_1[:,1], point1_point2_x_2[:,0], point1_point2_x_2[:,1], point3_point4_x_2[:,0], point3_point4_x_2[:,1], x_1, x_2) plt.legend(["$x_1 = 4$", "$x_1 = 0$", "$2x_2 = 12$", "$x_2 = 0$", "$3x_1+2x_2 = 18$"], bbox_to_anchor=(1, 1)) plt.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum") x_1_region_2 = np.linspace(0,2, 100) plt.fill_between(x_1_region_2, 0, 6, color="plum") plt.title("Región factible del PL") plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
La región sombreada es la región factible. Cualquier punto que se elija en la región factible satisface las desigualdades definidas en el PL. Ahora tenemos que seleccionar dentro de la región factible el punto que maximiza el valor de la función objetivo $f_o$. El procedimiento gráfico consiste en dar a $f_o$ algún valor arbitrario, dibujar la recta definida por tal valor y "mover tal recta de forma paralela" en la dirección que $f_o$ crece (si se desea maximizar y en la dirección en la que $f_o$ decrece si se desea minimizar) hasta que se mantenga en la región factible. Para la función objetivo del PL anterior queda como sigue: $$y = f_o(x) = 3x_1 + 5x_2$$ y vamos dando valores arbitrarios a $y$: ```{margin} Todas las rectas tienen la misma pendiente por lo que son paralelas. Cada una de las rectas son las curvas de nivel de $f_o$ ```
plt.figure(figsize=(7,7)) plt.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], "--", color="black", label = "_nolegend_") plt.plot(point3_point4_x_1[:,0], point3_point4_x_1[:,1], "--", color="black", label = "_nolegend_") plt.plot(point1_point2_x_2[:,0], point1_point2_x_2[:,1], "--", color="black", label = "_nolegend_") plt.plot(point3_point4_x_2[:,0], point3_point4_x_2[:,1], "--", color="black", label = "_nolegend_") plt.plot(x_1, x_2, "--", color="black", label="_nolegend_") plt.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum") plt.fill_between(x_1_region_2, 0, 6, color="plum") plt.title("Región factible del PL") x_1_line_1 = np.linspace(0, 4, 100) x_2_line_1 = 1/5*(-3*x_1_line_1 + 10) x_1_line_2 = np.linspace(0, 7, 100) x_2_line_2 = 1/5*(-3*x_1_line_2 + 20) x_1_line_3 = np.linspace(0, 8, 100) x_2_line_3 = 1/5*(-3*x_1_line_3 + 36) plt.plot(x_1_line_1, x_2_line_1, "green", x_1_line_2, x_2_line_2, "indigo", x_1_line_3, x_2_line_3, "darkturquoise" ) optimal_point = (2, 6) plt.scatter(optimal_point[0], optimal_point[1], marker='o', s=150, facecolors='none', edgecolors='b') point_origin = (0, 0) point_gradient_fo = (3, 5) points_for_gradient_fo = np.row_stack((point_origin, point_gradient_fo)) plt.arrow(point_origin[0], point_origin[1], point_gradient_fo[0], point_gradient_fo[1], width=.05, color="olive") plt.legend(["$10 = 3x_1 + 5x_2$", "$20 = 3x_1 + 5x_2$", "$36 = 3x_1 + 5x_2$", "$\\nabla f_o(x)$"], bbox_to_anchor=(1.4, 1)) plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Si realizamos este proceso para valores de $y$ iguales a $36, 20, 10$ observamos que la recta que da el mayor valor de la $f_o$ y que se mantiene en la región factible es aquella con valor $y_1= f_o(x) = 36$. Corresponde a la pareja $(x_1, x_2) = (2, 6)$ y es la solución óptima. Entonces produciendo los productos $1$ y $2$ a una tasa de $2$ y $6$ lotes por semana se maximiza la ganancia siendo de 36 mil pesos. No existen otras tasas de producción que sean tan redituables como la anterior de acuerdo con el modelo. ```{admonition} Comentarios El método gráfico anterior sólo funciona para dos o tres dimensiones. El gradiente de la función objetivo nos indica la dirección de máximo crecimiento de $f_o$. En el ejemplo prototipo $\nabla f_o(x) = \left [ \begin{array}{c} 3 \ 5 \end{array} \right ]$ y tal vector apunta hacia la derecha y hacia arriba. Entonces en esa dirección es hacia donde desplazamos las rectas paralelas. La región factible que resultó en el ejemplo prototipo se le conoce con el nombre de poliedro y es un conjunto convexo (en dos dimensiones se le nombra polígono). Es una intersección finita entre hiperplanos y semi espacios, también puede pensarse como el conjunto solución de un número finito de ecuaciones y desigualdades lineales. ``` ```{admonition} Ejercicio :class: tip Resuelve con el método gráfico el siguiente PL: $$\displaystyle \max_{x \in \mathbb{R}^2} 2x_1 + x_2$$ $$\text{sujeto a: }$$ $$x_2 \leq 10$$ $$2x_1 + 5x_2 \leq 60$$ $$x_1 + x_2 \leq 18$$ $$3x_1 + x_2 \leq 44$$ $$x_1 \geq 0, x_2 \geq 0$$ Marca al gradiente de la función objetivo en la gráfica. ``` Tipo de soluciones en un PL Los puntos factibles que resultan de la intersección entre las rectas del ejemplo prototipo que corresponden a las desigualdades se les nombra soluciones factibles en un vértice (FEV) (se encuentran en una esquina). Las soluciones FEV no son una combinación convexa estricta entre puntos distintos del poliedro formado en la región factible (no caen en algún segmento de línea formado por dos puntos distintos). ```{admonition} Observación :class: tip También a las soluciones FEV se les conoce como puntos extremos pero resulta más sencillo recordar FEV. ``` ```{admonition} Comentario El método gráfico en la región anterior ilustra una propiedad importante de los PL con soluciones factibles y una región acotada: siempre tiene soluciones FEV y al menos una solución óptima, aún más, la mejor solución en un FEV debe ser una solución óptima. ``` ¿A qué le llamamos solución en un PL? Cualquier conjunto de valores de las variables de decisión ($x_1, x_2, \dots, x_n$) se le nombra una solución y se identifican dos tipos: Una solución factible es aquella para la cual todas las restricciones se satisfacen. Una solución no factible es aquella para la cual al menos una restricción no se satisface. En el ejemplo prototipo los puntos $(2,3)$ y $(4,1)$ son soluciones factibles y $(-1, 3), (4,4)$ son soluciones no factibles.
plt.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], "black", label = "_nolegend_") plt.plot(point3_point4_x_1[:,0], point3_point4_x_1[:,1], "black", label = "_nolegend_") plt.plot(point1_point2_x_2[:,0], point1_point2_x_2[:,1], "black", label = "_nolegend_") plt.plot(point3_point4_x_2[:,0], point3_point4_x_2[:,1], "black", label = "_nolegend_") plt.plot(x_1, x_2, "black", label = "_nolegend_") plt.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum", label = "_nolegend_") plt.fill_between(x_1_region_2, 0, 6, color="plum", label = "_nolegend_") plt.scatter(2, 3, marker='o', s=150) plt.scatter(4, 1, marker='*', s=150) plt.scatter(-1, 3, marker='v', s=150) plt.scatter(4, 4, marker='^', s=150) plt.legend(["Solución factible", "Solución factible", "Solución no factible", "Solución no factible"]) plt.title("Tipos de soluciones en un PL") plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} "Valor más favorable de la función objetivo" depende si se tiene un problema de maximización o minimización. ``` De las soluciones factibles se busca aquella solución óptima (puede haber más de una) que nos dé el valor "más favorable" (valor óptimo) de la función objetivo. Ejemplo: más de una solución óptima Es posible tener más de una solución óptima, por ejemplo si la función objetivo hubiera sido $f_o(x) = 3x_1 + 2x_2$ entonces:
plt.figure(figsize=(6,6)) point4 = (2, 6) point5 = (4, 3) point4_point5 = np.row_stack((point4, point5)) plt.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], point3_point4_x_1[:,0], point3_point4_x_1[:,1], point1_point2_x_2[:,0], point1_point2_x_2[:,1], point3_point4_x_2[:,0], point3_point4_x_2[:,1], x_1, x_2) plt.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum") plt.fill_between(x_1_region_2, 0, 6, color="plum") plt.plot(point4_point5[:,0], point4_point5[:,1], linewidth=2, color = "darkred", linestyle='dashed') plt.legend(["$x_1 = 4$", "$x_1 = 0$", "$2x_2 = 12$", "$x_2 = 0$", "$3x_1+2x_2 = 18$", "$18 = f_o(x) = 3x_1 + 2x_2$"], bbox_to_anchor=(1, 1)) plt.title("Región factible del PL") plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
El segmento de recta que va de $(2,6)$ a $(4,3)$ (en línea punteada) son soluciones óptimas. Tal segmento es la curva de nivel de $f_o(x)$ con el valor $18$. Cualquier PL que tenga soluciones óptimas múltiples tendrá un número infinito de ellas, todas con el mismo valor óptimo. ```{admonition} Comentario Si un PL tiene exactamente una solución óptima, ésta debe ser una solución FEV. Si tiene múltiples soluciones óptimas, al menos dos deben ser soluciones FEV. Por esto para resolver problemas de PL sólo tenemos que considerar un número finito de soluciones. ``` Ejemplo: PL's sin solución Es posible que el PL no tenga soluciones óptimas lo cual ocurre sólo si: No tiene soluciones factibles y se le nombra PL no factible. Las restricciones no impiden que el valor de la función objetivo mejore indefinidamente en la dirección favorable. En este caso se tiene un PL con función objetivo no acotada y se le nombra PL no acotado. Un ejemplo de un PL no factible pues su región factible es vacía se obtiene al añadir la restricción $3x_1+ 5x_2 \geq 50$ a las restricciones anteriores:
#3x_1 + 5x_2 ≥ 50 x_1_b = np.linspace(0,8, 100) x_2_b = 1/5*(50 - 3*x_1_b) plt.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], point3_point4_x_1[:,0], point3_point4_x_1[:,1], point1_point2_x_2[:,0], point1_point2_x_2[:,1], point3_point4_x_2[:,0], point3_point4_x_2[:,1], x_1, x_2, x_1_b, x_2_b) plt.legend(["$x_1 = 4$", "$x_1 = 0$", "$2x_2 = 12$", "$x_2 = 0$", "$3x_1+2x_2 = 18$", "$3x_1 + 5x_2 = 50$"], bbox_to_anchor=(1, 1)) plt.fill_between(x_1_b, x_2_b, 10, color="plum") plt.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum") plt.fill_between(x_1_region_2, 0, 6, color="plum") plt.title("No existe solución factible") plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
La intersección entre las dos regiones sombreadas es vacía. Un ejemplo de un PL no acotado resulta de sólo considerar las restricciones $x_1 \leq 4, x_1 \geq 0, x_2 \geq 0$:
points = np.column_stack((4*np.ones(11), np.arange(11))) plt.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], point3_point4_x_1[:,0], point3_point4_x_1[:,1], point3_point4_x_2[:,0], point3_point4_x_2[:,1]) plt.plot(points[:,0], points[:,1], 'o', markersize=5) plt.legend(["$x_1 = 4$", "$x_1 = 0$", "$x_2 = 0$"], bbox_to_anchor=(1, 1)) x_1_region = np.linspace(0,4, 100) plt.fill_between(x_1_region, 0, 10, color="plum") plt.title("Región factible no acotada") plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Se observa en la gráfica anterior que se tiene una región factible no acotada y como el objetivo es maximizar podemos elegir el valor $x_1 = 4$ y arbitrariamente un valor cada vez más grande de $x_2$ y obtendremos una mejor solución dentro de la región factible. ```{sidebar} Un poco de historia ... El método símplex pertenece a una clase general de algoritmos de optimización con restricciones conocida como métodos de conjuntos activos en los que la tarea fundamental es determinar cuáles restricciones son activas y cuáles inactivas en la solución. Mantiene estimaciones de conjuntos de índices de restricciones activas e inactivas que son actualizadas y realiza cambios modestos a tales conjuntos en cada paso del algoritmo. ``` (METODOSIMPLEX)= Método símplex Para comprender sus conceptos fundamentales se considera un PL en una forma no estándar y se utiliza el mismo PL del ejemplo prototipo: $$\displaystyle \max_{x \in \mathbb{R}^2} 3x_1 + 5x_2$$ $$\text{sujeto a: }$$ $$x_1 \leq 4$$ $$2x_2 \leq 12$$ $$3x_1 + 2x_2 \leq 18$$ $$x_1 \geq 0, x_2 \geq 0$$ (SOLFEVNFEV)= Soluciones FEV y NFEV
fig, ax = plt.subplots() ax.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], label = "_nolegend_") ax.plot(point3_point4_x_1[:,0], point3_point4_x_1[:,1], label = "_nolegend_") ax.plot(point1_point2_x_2[:,0], point1_point2_x_2[:,1], label = "_nolegend_") ax.plot(point3_point4_x_2[:,0], point3_point4_x_2[:,1], label = "_nolegend_") ax.plot(x_1, x_2, label = "_nolegend_") ax.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum", label = "_nolegend_") x_1_region_2 = np.linspace(0,2, 100) ax.fill_between(x_1_region_2, 0, 6, color="plum", label = "_nolegend_") point_FEV_1 = (0,0) point_FEV_2 = (0,6) point_FEV_3 = (2,6) point_FEV_4 = (4,3) point_FEV_5 = (4,0) array_FEV = np.row_stack((point_FEV_1, point_FEV_2, point_FEV_3, point_FEV_4, point_FEV_5)) point_NFEV_1 = (0, 9) point_NFEV_2 = (4, 6) point_NFEV_3 = (6, 0) array_NFEV = np.row_stack((point_NFEV_1, point_NFEV_2, point_NFEV_3)) ax.plot(array_FEV[:,0], array_FEV[:,1], 'o', color="orangered", markersize=10, label="FEV") ax.plot(array_NFEV[:,0], array_NFEV[:,1], '*', color="darkmagenta", markersize=10, label="NFEV") ax.legend() plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Los puntos en la gráfica con etiqueta "FEV" son soluciones factibles en un vértice: $(0, 0), (0, 6), (2, 6), (4, 3), (4, 0)$ y están definidos por las restricciones de desigualdad tomando sólo la igualdad, esto es, por las rectas: $x_1 = 4, 2x_2 = 12, 3x_1 + 2 x_2 = 18, x_1 = 0, x_2 = 0$. ```{admonition} Definiciones A las rectas que se forman a partir de una desigualdad tomando únicamente la igualdad se les nombra ecuaciones de frontera de restricción o sólo ecuaciones de frontera. Las ecuaciones de frontera que definen a las FEV se les nombra ecuaciones de definición. ``` Análogamente los puntos con etiqueta "NFEV" son soluciones no factibles en un vértice: $(0, 9), (4, 6), (6,0)$ y también están definidos por las ecuaciones de frontera. ```{admonition} Observación :class: tip Aunque las soluciones en un vértice también pueden ser no factibles (NFEV) el método símplex no las revisa. ``` ```{margin} En más de dos dimensiones cada ecuación de definición genera un hiperplano en un espacio $n$ dimensional. Y la intersección de las $n$ ecuaciones de frontera es una solución simultánea de un sistema de $n$ ecuaciones lineales de definición. ``` ```{admonition} Comentarios En general para un PL con $n$ variables de decisión se cumple que cada solución FEV se define por la intersección de $n$ ecuaciones de frontera. Podría ser que se tengan más de $n$ fronteras de restricción que pasen por el vértice pero $n$ de ellas definen a la solución FEV y éstas son las ecuaciones de definición. Cada solución FEV es la solución simultánea de $n$ ecuaciones elegidas entre $m + n$ restricciones. El número de combinaciones de las $m + n$ ecuaciones tomadas $n$ a la vez es la cota superior del número de soluciones FEV. Para el ejemplo prototipo $m = 3, n=2$ por lo que $C^{m+n}_n = C^5_2 = 10$ y sólo $5$ conducen a soluciones FEV. ```
fig, ax = plt.subplots() ax.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], label = "_nolegend_") ax.plot(point3_point4_x_1[:,0], point3_point4_x_1[:,1], label = "_nolegend_") ax.plot(point1_point2_x_2[:,0], point1_point2_x_2[:,1], label = "_nolegend_") ax.plot(point3_point4_x_2[:,0], point3_point4_x_2[:,1], label = "_nolegend_") ax.plot(x_1, x_2, label = "_nolegend_") ax.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum", label = "_nolegend_") x_1_region_2 = np.linspace(0,2, 100) ax.fill_between(x_1_region_2, 0, 6, color="plum", label = "_nolegend_") ax.plot(array_FEV[:,0], array_FEV[:,1], 'o', color="orangered", markersize=10, label="FEV") ax.plot(array_NFEV[:,0], array_NFEV[:,1], '*', color="darkmagenta", markersize=10, label="NFEV") ax.legend() plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
|Solución FEV| Ecuaciones de definición| |:---:|:---:| |(0,0)| $x_1 = 0, x_2 = 0$| |(0,6)| $x_1 = 0, 2x_2 = 12$| |(2,6)| $2x_2 = 12, 3x_1 + 2x_2 = 18$| |(4,3)| $3x_1 + 2x_2 = 18, x_1 = 4$| |(4,0)| $x_1 = 4, x_2 = 0$| FEV adyacentes ```{admonition} Definición En un PL con $n$ variables de decisión nombramos soluciones FEV adyacentes a dos soluciones FEV que comparten $n-1$ fronteras de restricción. Las soluciones FEV adyacentes están conectadas por una arista (segmento de recta) ```
fig, ax = plt.subplots() ax.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], label = "_nolegend_") ax.plot(point3_point4_x_1[:,0], point3_point4_x_1[:,1], label = "_nolegend_") ax.plot(point1_point2_x_2[:,0], point1_point2_x_2[:,1], label = "_nolegend_") ax.plot(point3_point4_x_2[:,0], point3_point4_x_2[:,1], label = "_nolegend_") ax.plot(x_1, x_2, label = "_nolegend_") ax.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum", label = "_nolegend_") x_1_region_2 = np.linspace(0,2, 100) ax.fill_between(x_1_region_2, 0, 6, color="plum", label = "_nolegend_") ax.plot(array_FEV[:,0], array_FEV[:,1], 'o', color="orangered", markersize=10, label="FEV") ax.plot(array_NFEV[:,0], array_NFEV[:,1], '*', color="darkmagenta", markersize=10, label="NFEV") ax.legend() plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
En el ejemplo prototipo $(0,0)$ y $(0,6)$ son adyacentes pues comparten una arista formada por la ecuación de frontera $x_1=0$ y de cada solución FEV salen dos aristas, esto es tienen dos soluciones FEV adyacentes. ```{admonition} Comentario Una razón para analizar las soluciones FEV adyacentes es la siguiente propiedad: si un PL tiene al menos una solución óptima y una solución FEV no tiene soluciones FEV adyacentes que sean mejores entonces ésa debe ser una solución óptima. ``` ```{admonition} Observación :class: tip En el ejemplo prototipo $(2, 6)$ es un punto óptimo pues sus soluciones FEV adyacentes, $(0, 6)$, $(4,3)$ tienen un valor de la función objetivo menor (recuérdese es un problema de maximización). ``` Pasos que sigue el método símplex Para el ejemplo prototipo el método símplex a grandes rasgos realiza lo siguiente: Paso inicial: se elige $(0,0)$ como la solución FEV inicial para examinarla (esto siempre se puede hacer para problemas con restricciones de no negatividad). ```{margin} En el ejemplo numérico se entenderá la frase "solución FEV adyacente que es mejor" ``` Prueba de optimalidad: revisar condición de optimalidad para $(0,0)$. Concluir que $(0,0)$ no es una solución óptima (existe una solución FEV adyacente que es mejor). Iteración 1: moverse a una solución FEV adyacente mejor, para esto se realizan los pasos: 1.Entre las dos aristas de la región factible que salen de $(0,0)$ se elige desplazarse a lo largo de la arista que aumenta el valor de $x_2$ (con una función objetivo $f_o(x) = 3x_1 + 5x_2$ si $x_2$ aumenta entonces el valor de $f_o$ crece más que con $x_1$). 2.Detenerse al llegar a la primera ecuación de frontera en esa dirección: $2x_2 = 12$ para mantener factibilidad. 3.Obtener la intersección del nuevo conjunto de ecuaciones de frontera: $(0,6)$. ```{margin} En el ejemplo numérico se entenderá la frase "solución FEV adyacente que es mejor" ``` Prueba de optimalidad: revisar condición de optimalidad para $(0,6)$. Concluir que $(0,6)$ no es una solución óptima (existe una solución FEV adyacente que es mejor). Iteración 2: moverse a una solución FEV adyacente mejor: 1.De las dos aristas que salen de $(0,6)$ moverse a lo largo de la arista que aumenta el valor de $x_1$ (para que la $f_o$ continue mejorando no podemos ir hacia abajo pues esto implicaría disminuir el valor de $x_2$ y por tanto $f_o$). 2.Detenerse al llegar a la primera ecuación de frontera en esa dirección: $3x_1+2x_2 = 12$ para manterner factibilidad. 3.Obtener la intersección del nuevo conjunto de ecuaciones de frontera: $(2,6)$. ```{margin} En el ejemplo numérico se entenderá la frase "ninguna solución FEV adyacente es mejor" ``` Prueba de optimalidad: revisar condición de optimalidad para $(2,6)$. Concluir que $(2,6)$ es una solución óptima (ninguna solución FEV adyacente es mejor). (FORMAAUMENTADAPL)= Forma aumentada de un PL El método símplex inicia con un sistema de ecuaciones lineales con lado derecho igual a $b$ (que es el lado derecho de las restricciones funcionales) y una matriz del sistema con menos renglones que columnas. Asume que las entradas de $b$ son no negativas y que el rank de $A$ es completo. Para revisar los pasos del método símplex descritos anteriormente en esta sección continuaremos con el ejemplo prototipo de PL: $$\displaystyle \max_{x \in \mathbb{R}^2} 3x_1 + 5x_2$$ $$\text{sujeto a: }$$ $$x_1 \leq 4$$ $$2x_2 \leq 12$$ $$3x_1 + 2x_2 \leq 18$$ $$x_1 \geq 0, x_2 \geq 0$$ Y vamos a nombrar a las desigualdades $x_1 \leq4, 2x_2 \leq 12, 3x_1 + 2x_2 \leq 18$ restricciones funcionales y a las desigualdades $x_1 \geq 0, x_2 \geq 0$ restricciones de no negatividad. ```{admonition} Observación :class: tip Aunque hay diversas formas de PL en las que podríamos tener lados derechos negativos o desigualdades del tipo $\geq$, es sencillo transformar de forma algebraica tales PL a una forma similar descrita en esta sección. ``` En el ejemplo prototipo tenemos desigualdades por lo que se introducen variables de holgura, slack variables, no negativas para obtener la forma aumentada: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2$$ $$\text{sujeto a: }$$ $$x_1 + x_3 = 4$$ $$2x_2 + x_4 = 12$$ $$3x_1 + 2x_2 + x_5 = 18$$ $$x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0$$ ```{margin} Forma estándar de un PL: $$ \displaystyle \min_{x \in \mathbb{R}^n} c^Tx\ \text{sujeto a:} \ Ax=b\ x \geq 0 $$ ``` ```{admonition} Comentarios La forma aumentada que se obtuvo para el ejemplo prototipo no es la forma estándar de un PL salvo porque en la estándar se usa una minimización, ver {ref}forma estándar de un PL &lt;FORMAESTPL&gt;. Sin embargo, la forma estándar del PL se puede obtener considerando que maximizar $3x_1 + 5x_2$ sujeto a las restricciones dadas tiene mismo conjunto óptimo al problema minimizar $-3x_1 - 5 x_2$ sujeto a las mismas restricciones (los valores óptimos entre el problema de maximización y minimización son iguales salvo una multiplicación por $-1$). Las variables de holgura al iniciar el método tienen un coeficiente de $0$ en la función objetivo $f_o(x) = 3x_1 + 5x_2 = 3x_1 + 5x_2 + 0x_3 + 0x_4 + 0x_5$ ``` Y en notación matricial el sistema de ecuaciones lineales es: $$ Ax = \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left[ \begin{array}{c} 4 \ 12 \ 18 \end{array} \right ] = b $$ ```{admonition} Observación :class: tip Obsérvese que en la matriz de la forma aumentada se tiene una matriz identidad. ``` ```{admonition} Comentario Interpretación de algunos valores de las variables en la forma aumentada: Si una variable de holgura es igual a $0$ en la solución actual, entonces esta solución se encuentra sobre la ecuación de frontera de la restricción funcional correspondiente. Un valor mayor que $0$ significa que la solución está en el lado factible de la ecuación de frontera, mientras que un valor menor que $0$ señala que está en el lado no factible de esta ecuación de frontera. ```
fig, ax = plt.subplots() ax.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], label = "_nolegend_") ax.plot(point3_point4_x_1[:,0], point3_point4_x_1[:,1], label = "_nolegend_") ax.plot(point1_point2_x_2[:,0], point1_point2_x_2[:,1], label = "_nolegend_") ax.plot(point3_point4_x_2[:,0], point3_point4_x_2[:,1], label = "_nolegend_") ax.plot(x_1, x_2, label = "_nolegend_") ax.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum", label = "_nolegend_") x_1_region_2 = np.linspace(0,2, 100) ax.fill_between(x_1_region_2, 0, 6, color="plum", label = "_nolegend_") ax.plot(array_FEV[:,0], array_FEV[:,1], 'o', color="orangered", markersize=10, label="FEV") ax.plot(array_NFEV[:,0], array_NFEV[:,1], '*', color="darkmagenta", markersize=10, label="NFEV") ax.legend() plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{admonition} Definiciones Una solución aumentada es una solución de las variables originales que se aumentó con los valores correspondientes de las variables de holgura. Una solución básica es una solución FEV o NFEV aumentada. Una solución básica factible (BF) es una solución FEV aumentada. ``` ```{margin} $$ \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left[ \begin{array}{c} 4 \ 12 \ 18 \end{array} \right ] $$ ``` En el ejemplo prototipo: $\left [ \begin{array}{c} x_1 \ x_2 \end{array} \right ] = \left [ \begin{array}{c} 3 \ 2 \end{array} \right ]$ es solución (de hecho factible) y $\left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left [ \begin{array}{c} 3 \ 2 \ 1 \ 8 \ 5 \end{array} \right ]$ es solución aumentada (factible). $\left [ \begin{array}{c} x_1 \ x_2 \end{array} \right ] = \left [ \begin{array}{c} 4 \ 6 \end{array} \right ]$ es solución NFEV y $\left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left [ \begin{array}{c} 4 \ 6 \ 0 \ 0 \ -6 \end{array} \right ]$ es solución básica. $\left [ \begin{array}{c} x_1 \ x_2 \end{array} \right ] = \left [ \begin{array}{c} 0 \ 6 \end{array} \right ]$ es solución FEV y $\left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left [ \begin{array}{c} 0 \ 6 \ 4 \ 0 \ 6 \end{array} \right ]$ es solución BF. Soluciones BF adyacentes ```{admonition} Definición Dos soluciones BF son adyacentes si sus correspondientes soluciones FEV lo son. ```
fig, ax = plt.subplots() ax.plot(point1_point2_x_1[:,0], point1_point2_x_1[:,1], label = "_nolegend_") ax.plot(point3_point4_x_1[:,0], point3_point4_x_1[:,1], label = "_nolegend_") ax.plot(point1_point2_x_2[:,0], point1_point2_x_2[:,1], label = "_nolegend_") ax.plot(point3_point4_x_2[:,0], point3_point4_x_2[:,1], label = "_nolegend_") ax.plot(x_1, x_2, label = "_nolegend_") ax.fill_between(x_1_region_1, 0, x_2_region_1, where=x_2_region_1<=6, color="plum", label = "_nolegend_") x_1_region_2 = np.linspace(0,2, 100) ax.fill_between(x_1_region_2, 0, 6, color="plum", label = "_nolegend_") ax.plot(array_FEV[:,0], array_FEV[:,1], 'o', color="orangered", markersize=10, label="FEV") ax.plot(array_NFEV[:,0], array_NFEV[:,1], '*', color="darkmagenta", markersize=10, label="NFEV") ax.legend() plt.show()
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} $$ \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left[ \begin{array}{c} 4 \ 12 \ 18 \end{array} \right ] $$ ``` En el ejemplo prototipo $\left [ \begin{array}{c} 0 \ 0 \ 4 \ 12 \ 18 \end{array} \right ]$ y $\left [ \begin{array}{c} 0 \ 6 \ 4 \ 0 \ 6 \end{array} \right ]$ son soluciones BF adyacentes. (VARBASICASNOBASICAS)= Variables básicas y no básicas ```{admonition} Definición Dada la matriz $A \in \mathbb{R}^{m \times n}$ de la forma aumentada aquellas variables de decisión que corresponden a columnas linealmente independientes se les nombra variables básicas. Las restantes son variables no básicas. ``` Al inicio del método símplex la matriz de la forma aumentada es: $$\left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] $$ Por lo que las variables básicas son $x_3, x_4, x_5$ y las no básicas son $x_1, x_2$. ```{admonition} Definición La matriz que se forma a partir de las columnas de $A$ que corresponden a las variables básicas se denota como $B \in \mathbb{R}^{m \times m}$ es no singular y se nombra basis matrix. La matriz que se forma con las columnas de las variables no básicas se denota con $N$ y su nombre es nonbasis matrix. ``` ```{margin} $$ \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left[ \begin{array}{c} 4 \ 12 \ 18 \end{array} \right ] $$ ``` En el ejemplo prototipo la basis matrix y la nonbasis matrix al inicio del método son: $$B =\left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 1 \ \end{array} \right ] $$ $$N \left [ \begin{array}{ccccc} 1 & 0 \ 0 & 2 \ 3 & 2 \ \end{array} \right ] $$ ```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` ```{admonition} Comentarios Obsérvese en el ejemplo prototipo que al tener 5 variables y tres ecuaciones si se le asigna un valor arbitrario a $x_1, x_2$ entonces quedan determinadas las variables $x_3, x_4, x_5$. En el método símplex las variables no básicas se igualan a $0$ por lo que se tiene: $\left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5\end{array} \right ] = \left [ \begin{array}{c} 0 \ 0 \ 4 \ 12 \ 18 \end{array} \right ]$ Una forma de distinguir si dos soluciones BF son adyacentes es comparar qué variables no básicas (análogamente sus básicas) tienen. Si difieren en sólo una entonces son soluciones BF adyacentes. Por ejemplo: $\left [ \begin{array}{c} 0 \ 0 \ 4 \ 12 \ 18 \end{array} \right]$ y $\left [ \begin{array}{c} 0 \ 6 \ 4 \ 0 \ 6 \end{array} \right ]$ son BF adyacentes pues tienen como variables no básicas $x_1, x_2$ y $x_1, x_4$ respectivamente. Esto también se puede describir como: $x_2$ "pasa de ser no básica a básica" (análogamente $x_4$ pasa de básica a no básica). Lo anterior ayuda a identificar soluciones BF adyacentes en PL's con más de dos variables en los que resulta más complicado graficar. El método símplex al considerar variables no básicas con valor de $0$ indica que la restricción no negativa $x_j \geq 0$ es activa para $j$ en los índices de las variables no básicas. En el método símplex se puede verificar que una solución es BF si las variables básicas son no negativas (recuérdese que las no básicas en el método son igualadas a cero). ``` Variables básicas no degeneradas y degeneradas Considerando un problema con $n$ variables al que se le añadieron $m$ variables de holgura denotemos a $\mathcal{B}$ como el conjunto de índices en el conjunto ${1, 2, \dots, m+n}$ que representan a las variables básicas y $\mathcal{N}$ al conjunto de índices de las no básicas. El ejemplo prototipo en su forma aumentada $\mathcal{B} = {3, 4, 5}$, $\mathcal{N} = {1, 2}$ con $m=3, n=2, m+n=5$. El método símplex en sus iteraciones elige algún índice de $\mathcal{N}$ y lo sustituye por un índice del conjunto $\mathcal{B}$. ```{margin} En el ejemplo numérico se entenderá la frase "mejoren la función objetivo $f_o$". ``` ```{admonition} Comentarios El quitar y añadir variables a los conjuntos de índices $\mathcal{N}, \mathcal{B}$ y realizar los ajustes necesarios (recalcular valores de las variables básicas) en los valores de todas las variables básicas y no básicas se le conoce con el nombre de pivoteo. La interpretación geométrica de quitar, añadir variables de las matrices $N, B$ y realizar los ajustes necesarios (recalcular valores de las variables básicas) en una solución BF es equivalente en dos dimensiones a moverse por una arista y detenerse hasta encontrar una solución FEV. La elección de cuál variable no básica sustituir por una variable básica depende de la existencia de soluciones BF que mejoren la función objetivo $f_o$ y para ello se utiliza un criterio de optimalidad. ``` En el método símplex al recalcular los valores de las variables básicas algunas pueden tener valor igual a cero lo que da lugar a la siguiente definición. ```{admonition} Definición Una solución BF para un PL con restricciones de no negatividad en la que todas sus variables básicas son positivas se nombra no degenerada y degenerada si existe al menos una con valor igual a cero. ``` (EJMETSIMPLEXAPLICADOEJPROTOTIPO)= Ejemplo del método símplex aplicado al ejemplo prototipo ```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` Continuemos con el ejemplo prototipo en su forma aumentada. En notación matricial el sistema de ecuaciones lineales es: $$ Ax = \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left[ \begin{array}{c} 4 \ 12 \ 18 \end{array} \right ] = b $$ Defínanse al vector $x$ que contiene las variables "originales" y a las de holgura: $x = \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ]$ y $c = \left [ \begin{array}{c} -3 \ -5 \ 0 \ 0 \ 0 \end{array}\right]$ al vector de costos unitarios o equivalentemente $-c$ el vector de ganancias unitarias. Así, la función objetivo es: $f_o(x) = (-c)^Tx$ y se busca maximizar la ganancia total. También defínanse a los vectores de variables básicas y no básicas como: $x_B = [x_j]{j \in \mathcal{B}}$, $x_N = [x_j]{j \in \mathcal{N}}$. ```{margin} Siendo rigurosos la forma estándar de un PL es: $$ \displaystyle \min_{x \in \mathbb{R}^n} c^Tx\ \text{sujeto a:} \ Ax=b\ x \geq 0 $$ por lo que aunque maximizar $(-c)^Tx$ sujeto a las restricciones dadas tiene el mismo conjunto óptimo que el problema de minimizar $c^Tx$ sujeto a las mismas restricciones (los valores óptimos entre el problema de maximización y minimización son iguales salvo una multiplicación por $-1$), el problema debe escribirse explícitamente como minimización para considerarse en forma estándar. ``` Entonces el PL con esta notación que se debe resolver es: $$\displaystyle \max_{x \in \mathbb{R}^5} (-c)^Tx$$ $$\text{sujeto a: }$$ $$Ax = b$$ $$x \geq 0$$ con $x=\left [ \begin{array}{c} x_B \ x_N\end{array} \right ] \in \mathbb{R}^5$, $x_B \in \mathbb{R}^{3}, x_N \in \mathbb{R}^2$, $A \in \mathbb{R}^{3 \times 5}$. Paso inicial del ejemplo prototipo ```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` Se tiene la siguiente situación: $$(-c)^Tx= 3x_1 + 5x_2 + 0x_3 + 0x_4 + 0x_5$$ $$ A = \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] $$ Como $A = [ N \quad B ]$, $x=\left [ \begin{array}{c} x_N \ x_B\end{array} \right ]$ y $Ax = b$ entonces $Ax = B x_B + N x_N = b$. Se designa $x_N$ como un vector de ceros: $$x_N = \left [ \begin{array}{c} x_1 \ x_2 \end{array} \right ] = \left [ \begin{array}{c} 0 \ 0 \end{array} \right ]$$ Por tanto: $$Ax = Bx_B + N x_N = B x_B = b$$ y se tiene: $$x_B = B^{-1}b.$$ En este paso inicial para el ejemplo prototipo $x_B = b$ pues $B$ es la identidad: $$\therefore x_B = \left [ \begin{array}{c} x_3 \ x_4 \ x_5\end{array}\right ] = B^{-1}b = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 1 \end{array} \right ]^{-1} \left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ]=\left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ]$$ El vector de costos $c$ lo dividimos en $c = \left [ \begin{array}{c} c_N\ c_B \end{array} \right ]$, con $c_B = \left [ \begin{array}{c} c_{B_3} \ c_{B_4} \ c_{B_5} \end{array} \right ] = \left [ \begin{array}{c} 0 \ 0 \ 0 \end{array} \right ]$ contiene los costos de las variables básicas. El vector $c_N=\left [ \begin{array}{c} c_{N_1} \ c_{N_2} \end{array} \right ]=\left [ \begin{array}{c}-3 \ -5 \end{array} \right ]$ contiene los costos de las variables no básicas. Las variables básicas son $x_3, x_4, x_5$ y las no básicas son $x_1, x_2$. ```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` ```{admonition} Comentario La solución BF en el paso inicial $x = \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left [ \begin{array}{c} 0 \ 0 \ 4 \ 12 \ 18 \end{array} \right ]$ tiene como variables no básicas $x_1, x_2$ e indican que las restricciones $x_1 \geq 0, x_2 \geq 0$ son restricciones activas. ```
B = np.eye(3) b = np.array([4, 12, 18]) x_B = b A = np.array([[1, 0, 1, 0, 0], [0, 2, 0, 1, 0], [3, 2, 0, 0, 1]]) c_B = np.array([0,0,0]) c_N = np.array([-3, -5]) #list of indexes of nonbasic variables correspond to x1, x2 N_list_idx = [0, 1] #list of indexes of basic variables correspond to x3, x4, x5 B_list_idx = [2, 3, 4]
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Prueba de optimalidad Para revisar tanto en el paso inicial como en las iteraciones posteriores la condición de optimalidad para encontrar soluciones FEV adyacentes mejores, realicemos algunas reescrituras de la función objetivo. 1.Obsérvese que la función objetivo se puede escribir como: ```{margin} Recuérdese que la función objetivo es: $(-c)^Tx= 3x_1 + 5x_2 + 0x_3 + 0x_4 + 0x_5$. ``` $$f_o(x) = (-c)^Tx = [-c_B \quad -c_N] ^T \left [ \begin{array}{c} x_B \ x_N\end{array} \right ] = -c_B^Tx_B - c_N^T x_N = -c_B^T B^{-1}b = [0 \quad 0 \quad 0]^T \left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ]=0$$ 2.Obsérvese que las restricciones en su forma igualadas a cero pueden ser restadas de la función objetivo sin modificar su valor. Por ejemplo si tomamos la primer restricción con lado derecho igual a cero: $x_1 + x_3 - 4 = 0$ entonces: $$f_o(x) = f_o(x) - 0 = f_o(x) - (x_1 + x_3 - 4) = f_o(x) -x_1 -x_3 + 4$$ ```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` Y esto podemos hacer para todas las restricciones con lado derecho igual a cero: $$ \begin{eqnarray} f_o(x) &=& f_o(x) - (x_1 + x_3 - 4) - (2x_2 + x_4 - 12) - (3x_1 + 2x_2 + x_5 - 18) \nonumber \ &=& f_o(x) + (-4x_1 - 4x_2) + (-x_3 - x_4 - x_5) + (4 + 12 + 18) \nonumber \ &=& f_o(x) - 4 \displaystyle \sum_{j \in \mathcal{B}} x_{B_j} - \sum_{j \in \mathcal{N}}x_{N_j} + \sum_{i = 1}^3 b(i) \end{eqnarray} $$ con $x_{B_j}$ $j$-ésima componente del vector $x_B$, $x_{N_j}$ $j$-ésima componente del vector $x_N$ y $b(i)$ $i$-ésima componente de $b$. ```{margin} No es coincidencia que se elijan las cantidades $\lambda, \nu$ para representar esta igualdad, ver {ref}la función Lagrangiana &lt;FUNLAGRANGIANA&gt;. ``` En el método símplex no solamente se restan de la $f_o$ las restricciones con lado derecho igual a cero sino se multiplican por una cantidad $\nu_i$ y se suman a $f_o$. También si $\lambda$ es un vector tal que $\lambda ^T x = 0$ entonces: $$f_o(x) = f_o(x) + \lambda^Tx + \sum_{i = 1}^3 \nu_i h_i(x) = f_o(x) + \displaystyle \sum_{j \in \mathcal{B}} \lambda_{B_j} x_{B_j} + \sum_{j \in \mathcal{N}}\lambda_{N_j}x_{N_j} + \sum_{i = 1}^3 \nu_i h_i(x)$$ con $\lambda_{B_j}$, $\lambda_{N_j}$ coeficientes asociados a $x_{B_j}$ y $x_{N_j}$ respectivamente y $h_i(x)$ $i$-ésima restricción de igualdad con lado derecho igual a cero. Los coeficientes $\lambda_{B_j}, \lambda_{N_j}$ de la expresión anterior en el método de símplex se escriben como: $$\lambda_{B_j} = -c_{B_j} + \nu^Ta_j \quad j \in \mathcal{B}$$ $$\lambda_{N_j} = -c_{N_j} + \nu^Ta_j \quad j \in \mathcal{N}$$ con $a_j$ $j$-ésima columna de $A \in \mathbb{R}^{3 \times 5}$ y $\nu \in \mathbb{R}^{3}$. En el método símplex se mantiene en cada iteración $\lambda_{B_j} = 0 \forall j \in \mathcal{B}$ y se busca que $\lambda_{N_j} \forall j \in \mathcal{N}$ sea no negativo para problemas de minimización o no positivo para problemas de maximización. Si la búsqueda anterior no se logra, se continúa iterando hasta llegar a una solución o mostrar un mensaje si no fue posible encontrar una solución. Por lo anterior el vector $\nu$ se obtiene resolviendo la ecuación: $\nu ^T B = c_B^T$ y por tanto $\nu = B^{-T} c_B $. ```{admonition} Comentarios La justificación del por qué $\lambda = -c + A^T \nu$ se realizará más adelante, por lo pronto considérese que esto se obtiene de las {ref}condiciones KKT de optimalidad &lt;PRIMERAFORMULACIONCONDKKT&gt;. Por la definición de $\nu$ se cumple: $f_o(x) = (-c)^Tx = -c_B^Tx_B - c_N^T x_N = -c_B^T B^{-1}b = - \nu^Tb = b^T(-\nu)$. No se recomienda aprenderse fórmulas o expresiones pues este problema se planteó como maximizar $(-c)^Tx$, si se hubiera elegido maximizar $c^Tx$ (sin signo negativo) se modificarían un poco las expresiones anteriores para $\lambda, \nu, f_o(x)$. ``` La prueba de optimalidad consiste en revisar los $\lambda_{N_j}$, $j \in \mathcal{N}$. Se selecciona(n) aquella(s) variable(s) no básica(s) que tenga(n) la tasa más alta de mejoramiento (esto depende si es un problema de maximización o minimización) del valor en la función objetivo. ```{margin} $c_B = \left [ \begin{array}{c} c_{B_3} \ c_{B_4} \ c_{B_5} \end{array} \right ] = \left [ \begin{array}{c} 0 \ 0 \ 0 \end{array} \right ]$ ``` El vector $\nu$ es: $$\nu = B^{-T}c_B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 1 \end{array} \right ] ^{-T} \left [ \begin{array}{c} 0 \ 0 \ 0 \end{array}\right ] = \left [ \begin{array}{c} 0 \ 0 \ 0 \end{array}\right ]$$ ```{margin} Resolviendo un sólo sistema de ecuaciones lineales nos ayuda a evitar calcular la inversa de una matriz que implica resolver un sistema de ecuaciones lineales más grande. ``` Para el cálculo de $\nu$ resolvemos el sistema de ecuaciones lineales para el vector de incógnitas $\nu$: $$B^T \nu = c_B$$ Como $B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 1 \end{array} \right ]$ entonces directamente $\nu = c_B$. Por tanto:
nu = np.array([0, 0, 0])
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Valor de la función objetivo en la solución BF actual: $f_o(x) = (-c)^Tx = b^T(-\nu) = 0$ ```{margin} $ \begin{eqnarray} f_o(x) &=& (-c)^Tx \nonumber\ &=& -c_B^Tx_B - c_N^T x_N \nonumber\ &=& -c_B^T x_B \quad \text{pues } x_N=0\ \end{eqnarray}$ ```
print(np.dot(-c_B, x_B))
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} $f_o(x) = b^T(-\nu)$. ```
print(np.dot(b, -nu))
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} $c_N= \left [ \begin{array}{c}-3 \ -5 \end{array} \right ]$ ```
lambda_N_1 = -c_N[0] + np.dot(nu, A[:, N_list_idx[0]]) lambda_N_2 = -c_N[1] + np.dot(nu, A[:, N_list_idx[1]]) print(lambda_N_1) print(lambda_N_2)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
$\lambda_{N_1} = -c_{N_1} + \nu^Ta_1 = 3 + [0 \quad 0 \quad 0] \left [ \begin{array}{c} 1 \ 0 \ 3 \end{array}\right ] = 3$ $\lambda_{N_2} = -c_{N_2} + \nu^Ta_2 = 5 + [0 \quad 0 \quad 0] \left [ \begin{array}{c} 0 \ 2 \ 2 \end{array}\right ] = 5$ ```{margin} "tasa más alta de mejoramiento" se refiere a mejorar $f_o$ por un incremento de una unidad en la variable $x_2$. ``` ```{margin} Incrementar una variable no básica equivale geométricamente a moverse por una arista desde una solución FEV. ``` Como tenemos un problema de maximización la tasa más alta de mejoramiento de $f_o$ la da la variable $x_2$ por lo que es la variable no básica que sustituye a una variable básica. ¿Cuál variable básica se debe elegir?
#index for nonbasic variables, in this case value 1 correspond to x2 idx_x_N = 1
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Prueba del cociente mínimo El objetivo de esta prueba es determinar qué variable(s) básica(s) llega(n) a cero cuando crece la variable entrante. Tal variable(s) básica(s) en la siguiente iteración será no básica y la que aumenta pasa de ser no básica a básica. En el paso inicial las variables básicas son $x_3$, $x_4$ y $x_5$, por lo que hay que determinar de éstas cuál(es) es(son) la(s) que sale(n) al incrementar la variable no básica $x_2$. Esta prueba del cociente mínimo primero se explicará de forma detallada para posteriormente representarla de forma matricial. Las ecuaciones de $Ax = b$ son: ```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` $$\begin{eqnarray} x_1 + x_3 &=& 4 \nonumber \ 2x_2 + x_4 &=& 12 \nonumber \ 3x_1 + 2x_2 + x_5 &=& 18 \end{eqnarray} $$ Despejamos cada variable básica de las ecuaciones anteriores: $$\begin{eqnarray} x_3 &=& 4 - x_1 \nonumber \ x_4 &=& 12 - 2x_2 \nonumber \ x_5 &=& 18 - 3x_1 - 2x_2 \end{eqnarray} $$ Y se debe cumplir por las restricciones de no negatividad que al aumentar $x_2$: $$\begin{eqnarray} x_3 &=& 4 - x_1 \geq 0 \nonumber \ x_4 &=& 12 - 2x_2 \geq 0 \nonumber \ x_5 &=& 18 - 3x_1 - 2x_2 \geq 0 \end{eqnarray} $$ En la primera ecuación $x_3 = 4 - x_1$ no tenemos contribución alguna de $x_2$ por lo que no la tomamos en cuenta. La segunda y tercer ecuación sí aparece $x_2$ y como $x_1$ es variable no básica con valor $0$ se debe cumplir: $$\begin{eqnarray} x_2 \leq \frac{12}{2} = 6 \nonumber \ x_2 \leq \frac{18}{2} = 9 \end{eqnarray} $$ Entonces se toma el mínimo de las cantidades anteriores y como es igual a $6$ y esa desigualdad la obtuvimos de despejar $x_4$ entonces se elige $x_4$ como variable básica que se vuelve no básica. Tomamos el mínimo pues el valor de $6$ es lo máximo que podemos incrementar $x_2$ sin que $x_4$ se haga no negativa. ```{admonition} Comentario Es importante en la prueba del cociente mínimo que el lado derecho, el vector $b$, tenga entradas no negativas. ``` Prueba del cociente mínimo: forma general y con notación matricial y vectorial El procedimiento de la prueba del cociente mínimo entonces consiste en: 1.Elegir la columna de $A$ correspondiente a la variable no básica que sustituye a la variable básica, que por lo anterior es $x_2$ y corresponde a la segunda columna de $A$, $a_2$: $$ A = \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] $$ 2.Hacer la multiplicación $d = B^{-1}a_2$ (ver siguiente paso para el cálculo de $d$). Esto en general se realiza, en el paso inicial para el ejemplo prototipo $B^{-1}$ es la identidad por lo que en este paso inicial no tuvo efecto hacer la multiplicación. 3.Para las entradas estrictamente positivas de tal multiplicación anterior se divide el lado derecho entre tales entradas y se toma el mínimo. Como el lado derecho en cada iteración es $x_B = B^{-1}b$ entonces se dividen los valores de las variables básicas entre las entradas estrictamente positivas. Esto es, si se denota como $x_2^{+}$ al mínimo: $$x_2^{+} = \min {\frac{x_{B_i}}{d_i} : d_i > 0, i = 1, 2, \dots, m }$$ con $d_i$ $i$-ésima componente del vector $d$ que es solución del sistema de ecuaciones: $Bd = a_2$ y $x_{B_i}$ $i$-ésima entrada del vector $x_B$ de la iteración actual. 4.El índice donde ocurre el mínimo es el de la variable básica que será sustituida. En el ejemplo prototipo se tienen las siguientes asignaciones en el paso inicial: {margin} $ B = \left [ \begin{array}{ccccc} 1 &amp; 0 &amp; 0 \\ 0 &amp; 1 &amp; 0 \\ 0 &amp; 0 &amp; 1 \\ \end{array} \right ] $ ```{margin} La segunda columna de $A$ se elige pues $x_2$ es la variable no básica a la que se le aumentará su valor y sustituirá a una variable básica. ``` Se resuelve la ecuación: $Bd = a_2$ para $d$ vector de incógnitas y $a_2$ segunda columna de $A$.
d = np.linalg.solve(B, A[:,idx_x_N]) print(d)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
En esta iteración: $x_B = \left [ \begin{array}{c} x_3 \ x_4 \ x_5\end{array}\right ] = \left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ]$ pues $B$ es la matriz identidad por lo que $x_B = b$.
print(x_B)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Se hace la división únicamente entre las entradas estrictamente positivas ```
idx_positive = d >0 print(x_B[idx_positive]/d[idx_positive])
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Hacer cero una variable básica y convertirla en no básica equivale geométricamente a detener el movimiento por una arista hasta encontrar una solución FEV. ``` Entonces el mínimo ocurre en la segunda posición de $x_B$ que corresponde a la variable básica $x_4$. Se elige $x_4$ como variable básica que se vuelve no básica. $x_4$ será sustituida por $x_2$ en la próxima iteración.
#index for basic variables, in this case value 1 correspond to x4 idx_x_B = 1
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Actualización del vector $x_B$ La actualización de las variables básicas después del paso inicial se realiza con la expresión computacional: $$x_B = x_B - dx_{nb}^{+}$$ donde: $nb$ es el índice de la variable no básica que se volverá básica en la iteración actual. El superíndice $+$ se utiliza para señalar que se actualizará tal variable no básica (variable que entra). Después de incrementarla, la variable básica con índice $ba$ pasa a estar en $x_N$ con valor de $0$ (variable que sale). Posterior a la actualización de $x_B$ se intercambian las columnas de $B$ correspondientes a las variables $x_{nb}$ y $x_{ba}$. La justificación de la expresión anterior es la siguiente: Como $Ax = b$ y $Bx_B + Nx_N = b$ pero será incrementada la variable $x_{nb}$ y disminuida $x_{ba}$ a cero entonces si $x^+$ denota el nuevo valor de $x$ se tiene: $$b = Ax ^+ = Bx_B^+ + a_{nb}x_{nb}^+ = B x_B = Ax = b$$ recordando que $Nx_N = 0$ pues $x_N=0$ donde: $a_{nb}$ es la ${nb}$-ésima columna de $A$. Por tanto: $$Bx_B^+ = Bx_B - a_{nb}x_{nb}^+$$ Y premultiplicando por la inversa: $$x_B^+ = x_B - B^{-1}a_{nb}x_{nb}^+ = x_B - d x_{nb}^+.$$ La interpretación geométrica de esta actualización es: un movimiento a lo largo de una arista del poliedro que mantiene factibilidad y mejora la función objetivo. Nos movemos a lo largo de esta arista hasta encontrar una solución FEV. En esta nueva solución FEV una nueva restricción no negativa se vuelve activa, la que corresponde a la variable $x_{ba}$. Después de la actualización se remueve el índice $ba$ del conjunto $\mathcal{B}$ y se sustituye por el índice $nb$. Iteración 1 La matriz $B$ del paso inicial era: $$B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 1 \end{array} \right ]$$ y correspondía cada columna a las variables $x_3, x_4, x_5$ en ese orden. Se realiza la actualización descrita para $x_B$: $$x_B = x_B - dx_2^{+}$$ con $x_2$ es la variable no básica que se volverá básica en la iteración actual.
x_2_plus = np.min(x_B[idx_positive]/d[idx_positive]) print(x_2_plus) x_B = x_B - d*x_2_plus print(x_B)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Aquí el valor de la variable $x_4$ se hace cero y tenemos que intercambiar tal entrada con la de $x_2^+$ para el vector $x_B$:
x_B[idx_x_B] = x_2_plus print(x_B)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Antes de hacer el intercambio de columnas: $B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 1 \end{array} \right ]$ y la matriz original $A = \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 2 & 0 & 1 & 0 \ 3 & 2 & 0 & 0 & 1 \ \end{array} \right ] $ ``` Como $x_4$ se intercambia por $x_2$ entonces se intercambia la columna $2$ de $A$, $a_2$, por la $2$ de $B$, $b_2$ por lo que al final de la iteración 1: $$B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 2 & 0 \ 0 & 2 & 1 \end{array} \right ]$$
B[:,idx_x_B] = A[:,idx_x_N]
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
$x_B = \left [ \begin{array}{c} x_3 \ x_2 \ x_5 \end{array}\right ] = \left [ \begin{array}{c} 4 \ 6 \ 6 \end{array}\right ]$, $x_N = \left [ \begin{array}{c} x_1 \ x_4\end{array}\right ] = \left [ \begin{array}{c} 0 \ 0\end{array}\right ]$.
aux = B_list_idx[idx_x_B] B_list_idx[idx_x_B] = N_list_idx[idx_x_N] N_list_idx[idx_x_N] = aux
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{admonition} Observación :class: tip La actualización de $x_B$ anterior se puede verificar que es equivalente a: $$x_B = \left [ \begin{array}{c} x_3 \ x_2 \ x_5\end{array}\right ] = B^{-1}b = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 2 & 0 \ 0 & 2 & 1 \end{array} \right ]^{-1} \left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ] = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & \frac{1}{2} & 0 \ 0 & -1 & 1 \end{array} \right ]\left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ] = \left [ \begin{array}{c} 4 \ 6 \ 6 \end{array}\right ] $$ ``` ```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` ```{admonition} Comentario En este punto, la solución BF obtenida en esta iteración $x = \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left [ \begin{array}{c} 0 \ 6 \ 4 \ 0 \ 6 \end{array} \right ]$ tiene como variables no básicas $x_1, x_4$ e indican que las restricciones $x_1 \geq 0, x_4 \geq 0$ son restricciones activas. Además como $x_4$ es variable de holgura la restricción funcional asociada $2x_2 + x_4 \leq 12$ indica que la solución BF se encuentra sobre la ecuación de frontera. ``` Prueba de optimalidad Se recalcula el vector $\nu$ considerando que $c_B = \left [ \begin{array}{c} c_{B_3} \ c_{B_2} \ c_{B_5} \end{array}\right ]$ tomando ahora $x_3, x_2, x_5$ como variables básicas. ```{margin} $B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 2 & 0 \ 0 & 2 & 1 \end{array} \right ]$ ``` ```{margin} $c_B = \left [ \begin{array}{c} c_{B_3} \ c_{B_2} \ c_{B_5} \end{array} \right ] = \left [ \begin{array}{c} 0 \ -5 \ 0 \end{array} \right ]$ ``` El vector $\nu$ es: $$\nu = B^{-T}c_B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & \frac{1}{2} & 0 \ 0 & -1 & 1 \end{array} \right ] ^T \left [ \begin{array}{c} 0 \ -5 \ 0 \end{array}\right ] = \left [ \begin{array}{c} 0 \ -\frac{5}{2} \ 0 \end{array}\right ]$$ ```{margin} Resolviendo un sólo sistema de ecuaciones lineales nos ayuda a evitar calcular la inversa de una matriz que implica resolver un sistema de ecuaciones lineales más grande. ``` Para el cálculo de $\nu$ resolvemos el sistema de ecuaciones lineales para el vector de incógnitas $\nu$: $$B^T \nu = c_B$$
aux = c_B[idx_x_B] c_B[idx_x_B] = c_N[idx_x_N] c_N[idx_x_N] = aux nu = np.linalg.solve(B.T, c_B) print(nu)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Por tanto: ```{margin} $c_N= \left [ \begin{array}{c}-3 \ 0 \end{array} \right ]$ ```
lambda_N_1 = -c_N[0] + np.dot(nu, A[:,N_list_idx[0]]) lambda_N_4 = -c_N[1] + np.dot(nu, A[:,N_list_idx[1]]) print(lambda_N_1) print(lambda_N_4)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
$\lambda_{N_1} = -c_{N_1} + \nu^Ta_1 = 3 + [0 \quad -\frac{5}{2} \quad 0] \left [ \begin{array}{c} 1 \ 0 \ 3 \end{array}\right ] = 3$ $\lambda_{N_4} = -c_{N_4} + \nu^Ta_4 = 0 + [0 \quad -\frac{5}{2} \quad 0]\left [ \begin{array}{c} 0 \ 1 \ 0 \end{array}\right ] = -2.5$ Como tenemos un problema de maximización la tasa más alta de mejoramiento de $f_o$ la da la variable $x_1$ por lo que es la variable no básica que sustituye a una variable básica.
#index for nonbasic variables, in this case value 0 correspond to x1 idx_x_N = 0
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Valor de la función objetivo en la solución BF actual: $f_o(x) = (-c)^Tx = b^T(-\nu) = 30$ ```{margin} $ \begin{eqnarray} f_o(x) &=& (-c)^Tx \nonumber\ &=& -c_B^Tx_B - c_N^T x_N \nonumber\ &=& -c_B^T x_B \quad \text{pues } x_N=0\ \end{eqnarray}$ ```
print(np.dot(-c_B, x_B ))
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Prueba del cociente mínimo ```{margin} $B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 2 & 0 \ 0 & 2 & 1 \end{array} \right ]$ ``` ```{margin} La primer columna de $A$ se elige pues $x_1$ es la variable no básica a la que se le aumentará su valor y sustituirá a una variable básica. ``` Se resuelve la ecuación: $Bd = a_1$ para $d$ vector de incógnitas y $a_1$ primera columna de $A$.
d = np.linalg.solve(B, A[:, idx_x_N]) print(d)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
En esta iteración: $x_B = \left [ \begin{array}{c} x_3 \ x_2 \ x_5\end{array}\right ] = \left [ \begin{array}{c} 4 \ 6 \ 6 \end{array}\right ]$.
print(x_B)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Se hace la división únicamente entre las entradas estrictamente positivas ``` $$x_1^{+} = \min {\frac{x_{B_i}}{d_i} : d_i > 0, i = 1, 2, \dots, m }$$
idx_positive = d >0 print(x_B[idx_positive]/d[idx_positive])
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Entonces el mínimo ocurre en la tercera posición de $x_B$ que corresponde a la variable básica $x_5$. Se elige $x_5$ como variable básica que se vuelve no básica. $x_5$ será sustituida por $x_1$ en la próxima iteración.
#index for basic variables, in this case value 2 correspond to x5 idx_x_B = 2
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Iteración 2 La matriz $B$ de la iteración anterior era: $$B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 2 & 0 \ 0 & 2 & 1 \end{array} \right ]$$ y correspondía cada columna a las variables $x_3, x_2, x_5$ en ese orden. Se realiza la actualización descrita para $x_B$: $$x_B = x_B - dx_1^{+}$$ con $x_1$ es la variable no básica que se volverá básica en la iteración actual.
x_1_plus = np.min(x_B[idx_positive]/d[idx_positive]) print(x_1_plus) x_B = x_B - d*x_1_plus print(x_B)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Aquí el valor de la variable $x_5$ se hace cero y tenemos que intercambiar tal entrada con la de $x_1^+$ para el vector $x_B$:
x_B[idx_x_B] = x_1_plus print(x_B)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{admonition} Observación :class: tip La actualización de $x_B$ anterior se puede verificar que es equivalente a: $$x_B = \left [ \begin{array}{c} x_3 \ x_2 \ x_1\end{array}\right ] = B^{-1}b = \left [ \begin{array}{ccc} 1 & 0 & 1 \ 0 & 2 & 0 \ 0 & 2 & 3 \end{array} \right ]^{-1} \left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ] = \left [ \begin{array}{ccc} 1 & \frac{1}{3} & -\frac{1}{3} \ 0 & \frac{1}{2} & 0 \ 0 & -\frac{1}{3} & \frac{1}{3} \end{array} \right ]\left [ \begin{array}{c} 4 \ 12 \ 18 \end{array}\right ] = \left [ \begin{array}{c} 2 \ 6 \ 2 \end{array}\right ]$$ ``` ```{margin} Antes de hacer el intercambio de columnas: $B = \left [ \begin{array}{ccc} 1 & 0 & 0 \ 0 & 2 & 0 \ 0 & 2 & 1 \end{array} \right ]$ y la matriz original $ A = \left [ \begin{array}{ccccc} 1 & 0 & 1 & 0 & 0 \ 0 & 1 & 0 & 1 & 0 \ 3 & 0 & 0 & 0 & 1 \ \end{array} \right ] $ ``` Como $x_5$ se intercambia por $x_1$ entonces se intercambia la columna $1$ de $A$, $a_1$, por la $3$ de $B$, $b_3$ por lo que al final de la iteración $2$: $$B = \left [ \begin{array}{ccc} 1 & 0 & 1 \ 0 & 2 & 0 \ 0 & 2 & 3 \end{array} \right ]$$
B[:,idx_x_B] = A[:,idx_x_N]
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
$x_B = \left [ \begin{array}{c} x_3 \ x_2 \ x_1 \end{array}\right ] = \left [ \begin{array}{c} 2 \ 6 \ 2 \end{array}\right ]$, $x_N = \left [ \begin{array}{c} x_5 \ x_4\end{array}\right ] = \left [ \begin{array}{c} 0 \ 0\end{array}\right ]$.
aux = B_list_idx[idx_x_B] B_list_idx[idx_x_B] = N_list_idx[idx_x_N] N_list_idx[idx_x_N] = aux
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} La forma aumentada recuérdese es: $$\displaystyle \max_{x \in \mathbb{R}^5} 3x_1 + 5x_2 \ \text{sujeto a: }\ x_1 + x_3 = 4 \ 2x_2 + x_4 = 12 \ 3x_1 + 2x_2 + x_5 = 18 \ x_1 \geq 0, x_2 \geq 0, x_3 \geq 0, x_4 \geq 0, x_5 \geq 0 $$ ``` ```{admonition} Comentario En este punto, la solución BF obtenida en esta iteración $x = \left [ \begin{array}{c} x_1 \ x_2 \ x_3 \ x_4 \ x_5 \end{array} \right ] = \left [ \begin{array}{c} 2 \ 6 \ 2 \ 0 \ 0 \end{array} \right ]$ tiene como variables no básicas $x_4, x_5$ e indican que las restricciones $x_4 \geq 0, x_5 \geq 0$ son restricciones activas. Además como $x_4$ y $x_5$ son variables de holgura las restricciones funcionales asociadas $2x_2 + x_4 \leq 12$, $3x_1 + 2x_2 + x_5 \leq 18$ indican que la solución BF se encuentra sobre sus ecuaciones de frontera respectivas. ``` Prueba de optimalidad Se recalcula el vector $\nu$ considerando que $c_B = \left [ \begin{array}{c} c_{B_3} \ c_{B_2} \ c_{B_1} \end{array}\right ]$ tomando ahora $x_1$ como básica. ```{margin} $B = \left [ \begin{array}{ccc} 1 & 0 & 1 \ 0 & 2 & 0 \ 0 & 2 & 3 \end{array} \right ]$ ``` ```{margin} $c_B = \left [ \begin{array}{c} c_{B_3} \ c_{B_2} \ c_{B_1} \end{array} \right ] = \left [ \begin{array}{c} 0 \ -5 \ -3 \end{array} \right ]$ ``` El vector $\nu$ es: $$\nu = B^{-T}c_B = \left [ \begin{array}{ccc} 1 & \frac{1}{3} & -\frac{1}{3} \ 0 & \frac{1}{2} & 0 \ 0 & -\frac{1}{3}& \frac{1}{3} \end{array} \right ] ^T \left [ \begin{array}{c} 0 \ -5 \ -3 \end{array}\right ] = \left [ \begin{array}{c} 0 \ -\frac{3}{2} \ -1 \end{array}\right ]$$ ```{margin} Resolviendo un sólo sistema de ecuaciones lineales nos ayuda a evitar calcular la inversa de una matriz que implica resolver un sistema de ecuaciones lineales más grande. ``` Para el cálculo de $\nu$ resolvemos el sistema de ecuaciones lineales para el vector de incógnitas $\nu$: $$B^T \nu = c_B$$ ```{margin} $B = \left [ \begin{array}{ccc} 1 & 0 & 1 \ 0 & 2 & 0 \ 0 & 2 & 3 \end{array} \right ]$ ```
aux = c_B[idx_x_B] c_B[idx_x_B] = c_N[idx_x_N] c_N[idx_x_N] = aux nu = np.linalg.solve(B.T, c_B) print(nu)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Por tanto: ```{margin} $c_N= \left [ \begin{array}{c}0 \ 0 \end{array} \right ]$ ```
lambda_N_5 = -c_N[0] + np.dot(nu, A[:,N_list_idx[0]]) lambda_N_4 = -c_N[1] + np.dot(nu, A[:,N_list_idx[1]]) print(lambda_N_5) print(lambda_N_4)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
$\lambda_{N_5} = -c_{N_5} + \nu^Ta_5 = 0 + [0 \quad -\frac{3}{2} \quad -1]\left [ \begin{array}{c} 0 \ 0 \ 1 \end{array}\right ] = -1$ $\lambda_{N_4} = -c_{N_4} + \nu^Ta_4 = 0 + [0 \quad -\frac{3}{2} \quad -1] \left [ \begin{array}{c} 0 \ 1 \ 0 \end{array}\right ] = -1.5$ Índices de las variables básicas:
print(B_list_idx)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Índices de las variables no básicas:
print(N_list_idx)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
Valores de $\nu$:
print(nu)
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
```{margin} Recuérdese que en el método símplex se mantiene en cada iteración $\lambda_{B_j} = 0 \forall j \in \mathcal{B}$ y se busca que $\lambda_{N_j} \forall j \in \mathcal{N}$ sea no negativo para problemas de minimización o no positivo para problemas de maximización. ``` ```{admonition} Comentario Entonces al finalizar el método símplex aplicado al ejemplo prototipo: $\lambda_{B_1} = \lambda_{B_2} = \lambda_{B_3} = 0$ para los índices de las variables básicas $x_1, x_2, x_3$, $\mathcal{B} = {1, 2, 3}$. $\lambda_{N_4} = -1.5$, $\lambda_{N_5} = -1$ para los índices de las variables no básicas $x_4, x_5$, $\mathcal{N} = {4, 5}$. $\nu_{1} = 0, \nu_{2} = -1.5, \nu_{3} = -1$. ``` Como tenemos un problema de maximización la tasa más alta de mejoramiento de $f_o$ no la da ninguna de las variables no básicas por lo que la solución BF actual $x = \left [ \begin{array}{c} x_1\ x_2\ x_3\ x_4 \ x_5 \end{array} \right ]= \left [ \begin{array}{c} 2\ 6\ 2\ 0 \ 0 \end{array}\right ]$ es la solución óptima. Valor de la función objetivo en la solución BF actual: $f_o(x) = (-c)^Tx = b^T(-\nu) = 36$ ```{margin} $ \begin{eqnarray} f_o(x) &=& (-c)^Tx \nonumber\ &=& -c_B^Tx_B - c_N^T x_N \nonumber\ &=& -c_B^T x_B \quad \text{pues } x_N=0\ \end{eqnarray}$ ```
print(np.dot(-c_B, x_B))
libro_optimizacion/temas/4.optimizacion_en_redes_y_prog_lineal/4.1/Programacion_lineal_y_metodo_simplex.ipynb
ITAM-DS/analisis-numerico-computo-cientifico
apache-2.0
1. Training a Probability Distribution Let's start off simple with training a multivariate Gaussian distribution in an out-of-core manner. First, we'll generate some random data.
X = numpy.random.normal([5, 7], [1.5, 0.4], size=(1000, 2))
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
Then we can make a blank distribution with 2 dimensions. This is equivalent to filling in the mean and standard deviation with dummy values that will be overwritten, and don't effect the calculation.
d1 = MultivariateGaussianDistribution.blank(2) d1
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
Now let's summarize through a few batches of data.
d1.summarize(X[:250]) d1.summarize(X[250:500]) d1.summarize(X[500:750]) d1.summarize(X[750:]) d1.summaries
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
Now that we've seen the entire data set let's use the from_summaries method to update the parameters.
d1.from_summaries() d1
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
And what do we get if we learn directly from the data?
MultivariateGaussianDistribution.from_samples(X)
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
The exact same model. 2. Training a Mixture Model This summarization option enables a variety of different training strategies that can be written by hand. This notebook focuses on out-of-core learning, so let's make a data set and "read it in" one batch at a time to train a mixture model with a custom training function. We'll make another data set here, but one could easily have a function that read through some number of lines in a CSV, or loaded up a chunk from a numpy memory map, or whatever other massive data store you had.
X = numpy.concatenate([numpy.random.normal(0, 1, size=(5000, 10)), numpy.random.normal(1, 1, size=(7500, 10))]) n = X.shape[0] idx = numpy.arange(n) numpy.random.shuffle(idx) X = X[idx]
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
First we have to initialize our model. We can do that either by hand to some value we think is good, or by fitting to the first chunk of data, anticipating that it will be a decent representation of the remainder. We can also calculate the log probability of the data set now to see how much we improved.
# First we initialize our model on some small chunk of data. model = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X[:200], max_iterations=1, init='first-k') # The base performance on the data set. base_logp = model.log_probability(X).sum() from tqdm import tqdm_notebook as tqdm # Now we write our own iterator. This outer loop will be the number of times we iterate---hard coded to 5 in this case. for iteration in tqdm(range(5)): # This internal loop goes over chunks from the data set. We're just loading chunks of a fixed size iteratively # until we've seen the entire data set. for i in range(10): model.summarize(X[i * (n // 10):(i+1) * (n //10)]) # Now we've seen the entire data set and summarized it. We can update the parameters now. model.from_summaries()
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
How we does did our model do on the data originally, and how well does it do now?
base_logp, model.log_probability(X).sum()
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
Looks like a decent improvement. Now, let's compare to having fit our model to the entire loaded data set for five epochs.
model = GeneralMixtureModel.from_samples(MultivariateGaussianDistribution, 2, X[:200], max_iterations=1, init='first-k') base_logp = model.log_probability(X).sum() model.fit(X, max_iterations=5) base_logp, model.log_probability(X).sum()
tutorials/C_Feature_Tutorial_2_Out_Of_Core_Learning.ipynb
jmschrei/pomegranate
mit
Affine layer: foward Open the file cs231n/layers.py and implement the affine_forward function. Once you are done you can test your implementaion by running the following:
# Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around 1e-9. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Affine layer: backward Now implement the affine_backward function and test your implementation using numeric gradient checking.
# Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around 1e-10 print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
ReLU layer: forward Implement the forward pass for the ReLU activation function in the relu_forward function and test your implementation using the following:
# Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be around 5e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
ReLU layer: backward Now implement the backward pass for the ReLU activation function in the relu_backward function and test your implementation using numeric gradient checking:
np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 3e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
"Sandwich" layers There are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file cs231n/layer_utils.py. For now take a look at the affine_relu_forward and affine_relu_backward functions, and run the following to numerically gradient check the backward pass:
from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) print('Testing affine_relu_forward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Loss layers: Softmax and SVM You implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in cs231n/layers.py. You can make sure that the implementations are correct by running the following:
np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be 1e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Two-layer network In the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations. Open the file cs231n/classifiers/fc_net.py and complete the implementation of the TwoLayerNet class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation.
np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' for reg in [0.0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Solver In the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class. Open the file cs231n/solver.py and read through it to familiarize yourself with the API. After doing so, use a Solver instance to train a TwoLayerNet that achieves at least 50% accuracy on the validation set.
model = TwoLayerNet(reg=1e-2, hidden_dim=200) optim_config = { 'learning_rate': 1e-3 } solver = Solver(model, data, num_train_samples=20000, num_epochs=15, batch_size=500, num_val_samples=1000, optim_config=optim_config, print_every=30000, lr_decay=0.95) solver.train() ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## pass ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show()
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Multilayer network Next you will implement a fully-connected network with an arbitrary number of hidden layers. Read through the FullyConnectedNet class in the file cs231n/classifiers/fc_net.py. Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable? For gradient checking, you should expect to see errors around 1e-6 or less.
np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs.
# TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-1 learning_rate = 1e-3 model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=1000, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show()
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs.
# TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 1e-3 weight_scale = 1e-1 model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10000, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show()
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Inline question: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? Answer: 5 layer net is far more sensitive.... Update rules So far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+Momentum Stochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent. Open the file cs231n/optim.py and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function sgd_momentum and run the following to check your implementation. You should see errors less than 1e-8.
from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity']))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster.
num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show()
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
RMSProp and Adam RMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients. In the file cs231n/optim.py, implement the RMSProp update rule in the rmsprop function and implement the Adam update rule in the adam function, and check your implementations using the tests below. [1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012). [2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015.
# Test RMSProp implementation; you should see errors less than 1e-7 from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation; you should see errors around 1e-7 or less from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m']))
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules:
learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show()
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0
Train a good model! Train the best fully-connected model that you can on CIFAR-10, storing your best model in the best_model variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net. If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets. You might find it useful to complete the BatchNormalization.ipynb and Dropout.ipynb notebooks before completing this part, since those techniques can help you train powerful models.
best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. # ################################################################################ update_rule = 'adam' model = FullyConnectedNet([200, 200, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, data, num_epochs=10, batch_size=300, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solver.train() best_model = solver ################################################################################ # END OF YOUR CODE # ################################################################################
MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb
ThyrixYang/LearningNotes
gpl-3.0