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(... | 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... | 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_vali... | 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)... | 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: 如下打印... | 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.se... | 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 cos... | 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... | !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.sol... | 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 p... | #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... | 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 val... | 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 = "_nolege... | 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... | 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],... | 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 óptim... | 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_po... | 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... | #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, ... | 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$"... | 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 pe... | 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], labe... | 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} Definicione... | 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], labe... | 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 F... | 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], labe... | 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 propieda... | 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], labe... | 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... | 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], labe... | 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... | 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 t... | 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 ... | 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$ po... | #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... | 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 vue... | #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 actua... | 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... | 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 ... | 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 ... | #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_... | 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 n... | 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 ... | 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 ... | 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 fin... | 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 functio... | 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 writ... | 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.p... | 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... | 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... | 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... | 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_rel... | 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_g... | 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 followin... | 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 ... | 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 com... | 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(mode... | 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 do... | 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,
... | 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 ... | 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.float6... | 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],
... | 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],... | 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 ... | 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.a... | 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]... | 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 i... | # 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}
ne... | 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=upd... | 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... | 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. ... | MOOC/stanford_cnn_cs231n/assignment2/FullyConnectedNets.ipynb | ThyrixYang/LearningNotes | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.