Código de Python - ESTOCÁSTICO

Imágen de perfil

ESTOCÁSTICOgráfica de visualizaciones


Python

Publicado el 15 de Septiembre del 2023 por Hilario (122 códigos)
208 visualizaciones desde el 15 de Septiembre del 2023
"""
Hilario Iglesias Martínez.
*****************************************
Ejercicio:
CuadernoEstocas-Aula-48-15-SEP-RV-2.py
-----------------------------------------
Ejecución:python3 CuadernoEstocas-Aula-48-15-SEP-RV-2.py
******************************************
Se prueba con los valores con pareamétros mínimos,
con el fin de apreciar su funcionamiento:

learning_rate = 0.01
n_iterations = 4
np.random.seed(0)
X = 2 * np.random.rand(4, 1)
y = 4 + 3 * X + np.random.randn(4, 1)

-------------------------------------------
Creado bajo plataforma Linux.
Ubuntu 20.04.6 LTS
Editado con Sublime Text.
Ejecutado bajo consola linux:
python3 CuadernoEstocas-Aula-48-15-SEP-RV-2.py

"""

Requerimientos

Creado bajo plataforma Linux.
Ubuntu 20.04.6 LTS
Editado con Sublime Text.
Ejecutado bajo consola linux:
python3 CuadernoEstocas-Aula-48-15-SEP-RV-2.py

V.0

Publicado el 15 de Septiembre del 2023gráfica de visualizaciones de la versión: V.0
209 visualizaciones desde el 15 de Septiembre del 2023
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

descarga
descarga-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
"""
Hilario Iglesias Martínez.
*****************************************
Ejercicio:
CuadernoEstocas-Aula-48-15-SEP-RV-2.py
-----------------------------------------
Ejecución:python3 CuadernoEstocas-Aula-48-15-SEP-RV-2.py
******************************************
Se prueba con los valores con pareamétros  mínimos,
con el fin de apreciar su funcionamiento:
learning_rate = 0.01
n_iterations = 4
np.random.seed(0)
X = 2 * np.random.rand(4, 1)
y = 4 + 3 * X + np.random.randn(4, 1)
-------------------------------------------
Creado bajo plataforma Linux.
Ubuntu 20.04.6 LTS
Editado con Sublime Text.
Ejecutado bajo consola linux:
python3 CuadernoEstocas-Aula-48-15-SEP-RV-2.py
"""
 
import numpy as np
import matplotlib.pyplot as plt
 
# Genera datos de ejemplo
np.random.seed(0)
X = 2 * np.random.rand(4, 1)
y = 4 + 3 * X + np.random.randn(4, 1)
 
# Inicialización de parámetros
theta = np.random.randn(2, 1)  # Inicialización aleatoria de los parámetros (intercepto y pendiente)
learning_rate = 0.01
n_iterations = 4
m = len(X)
 
# Función de costo (error cuadrático medio)
def mse_cost(y_true, y_pred):
    return ((y_true - y_pred) ** 2).mean()
 
# Historia de costos para trazar
cost_history = []
 
# Descenso de gradiente estocástico
for iteration in range(n_iterations):
    for i in range(m):
        random_index = np.random.randint(m)  # Elije una muestra aleatoria
        xi = np.vstack([1, X[random_index]])  # Agrega un 1 para el término de intercepto
        yi = y[random_index:random_index+1]
        y_pred = xi.T.dot(theta)#y_pred=theta0*1+theta1*xi[1]
        gradients = -2 * xi.dot(yi - y_pred)#Derivada,gradiente
        theta = theta - learning_rate * gradients#Adecuación de pendiente y ordenada cuando x es cero. Peso, sesgo.
        print("*****************************")
        print("random_index\n:",random_index)
        print("*****************************")
        print("xi\n:",xi)
        print("*****************************")
        print("yi\n:",yi)
        print("*****************************")
        print("y_pred:\n",y_pred)
        print("*****************************")
        print("gradients:\n",gradients)
        print("*****************************")
        print("theta:\n",theta)
        print("*****************************")
    # Calcular el costo después de cada iteración completa
    y_pred = X.dot(theta[1:]) + theta[0]  # Actualizar y_pred
    cost = mse_cost(y, y_pred)#Llamamos a la función mse_cost(y_true, y_pred)
    cost_history.append(cost)#Almacenamos en cost_history
 
# Trazar la convergencia
plt.figure(figsize=(10, 5))
plt.plot(cost_history, marker='o')
plt.xlabel('Iteraciones')
plt.ylabel('Error Cuadrático Medio')
plt.title('Convergencia de SGD')
plt.show()
plt.figure(figsize=(10, 5))
plt.scatter(X,y, label='Datos')
x_line = np.array([0, 2])
y_line = theta[0] + theta[1] * x_line
plt.plot(x_line, y_line, c='red', label='Línea ajustada')
plt.xlabel('Eje X')
plt.ylabel('Eje y')
plt.legend()
plt.show()
 
 
# Mostrar los parámetros finales
print("Parámetros finales (theta):", theta)
 
"""
SEGUIMIENTO.
--------------------------
*****************************
random_index
: 2
*****************************
xi
: [[1.        ]
 [1.20552675]]
*****************************
yi
: [[8.56666867]]
*****************************
y_pred:
 [[0.39176863]]
*****************************
gradients:
 [[-16.34980009]
 [-19.71012141]]
*****************************
theta:
 [[0.06027915]
 [0.60769972]]
*****************************
*****************************
random_index
: 3
*****************************
xi
: [[1.        ]
 [1.08976637]]
*****************************
yi
: [[7.11794189]]
*****************************
y_pred:
 [[0.72252986]]
*****************************
gradients:
 [[-12.79082406]
 [-13.93900985]]
*****************************
theta:
 [[0.18818739]
 [0.74708981]]
*****************************
*****************************
random_index
: 3
*****************************
xi
: [[1.        ]
 [1.08976637]]
*****************************
yi
: [[7.11794189]]
*****************************
y_pred:
 [[1.00234074]]
*****************************
gradients:
 [[-12.2312023 ]
 [-13.32915288]]
*****************************
theta:
 [[0.31049941]
 [0.88038134]]
*****************************
*****************************
random_index
: 2
*****************************
xi
: [[1.        ]
 [1.20552675]]
*****************************
yi
: [[8.56666867]]
*****************************
y_pred:
 [[1.37182267]]
*****************************
gradients:
 [[-14.389692  ]
 [-17.34715866]]
*****************************
theta:
 [[0.45439633]
 [1.05385293]]
*****************************
*****************************
random_index
: 0
*****************************
xi
: [[1.        ]
 [1.09762701]]
*****************************
yi
: [[9.16043901]]
*****************************
y_pred:
 [[1.61113377]]
*****************************
gradients:
 [[-15.09861049]
 [-16.57264265]]
*****************************
theta:
 [[0.60538244]
 [1.21957936]]
*****************************
*****************************
random_index
: 1
*****************************
xi
: [[1.        ]
 [1.43037873]]
*****************************
yi
: [[7.31385832]]
*****************************
y_pred:
 [[2.34984281]]
*****************************
gradients:
 [[ -9.92803101]
 [-14.20084442]]
*****************************
theta:
 [[0.70466275]
 [1.3615878 ]]
*****************************
*****************************
random_index
: 1
*****************************
xi
: [[1.        ]
 [1.43037873]]
*****************************
yi
: [[7.31385832]]
*****************************
y_pred:
 [[2.65224898]]
*****************************
gradients:
 [[ -9.32321868]
 [-13.33573371]]
*****************************
theta:
 [[0.79789493]
 [1.49494514]]
*****************************
*****************************
random_index
: 1
*****************************
xi
: [[1.        ]
 [1.43037873]]
*****************************
yi
: [[7.31385832]]
*****************************
y_pred:
 [[2.93623267]]
*****************************
gradients:
 [[ -8.7552513 ]
 [-12.52332527]]
*****************************
theta:
 [[0.88544745]
 [1.62017839]]
*****************************
*****************************
random_index
: 1
*****************************
xi
: [[1.        ]
 [1.43037873]]
*****************************
yi
: [[7.31385832]]
*****************************
y_pred:
 [[3.20291616]]
*****************************
gradients:
 [[ -8.22188432]
 [-11.76040847]]
*****************************
theta:
 [[0.96766629]
 [1.73778248]]
*****************************
*****************************
random_index
: 0
*****************************
xi
: [[1.        ]
 [1.09762701]]
*****************************
yi
: [[9.16043901]]
*****************************
y_pred:
 [[2.87510327]]
*****************************
gradients:
 [[-12.57067149]
 [-13.79790853]]
*****************************
theta:
 [[1.09337301]
 [1.87576156]]
*****************************
*****************************
random_index
: 1
*****************************
xi
: [[1.        ]
 [1.43037873]]
*****************************
yi
: [[7.31385832]]
*****************************
y_pred:
 [[3.77642245]]
*****************************
gradients:
 [[ -7.07487174]
 [-10.11974607]]
*****************************
theta:
 [[1.16412172]
 [1.97695902]]
*****************************
*****************************
random_index
: 0
*****************************
xi
: [[1.        ]
 [1.09762701]]
*****************************
yi
: [[9.16043901]]
*****************************
y_pred:
 [[3.33408534]]
*****************************
gradients:
 [[-11.65270735]
 [-12.7903263 ]]
*****************************
theta:
 [[1.2806488 ]
 [2.10486228]]
*****************************
*****************************
random_index
: 3
*****************************
xi
: [[1.        ]
 [1.08976637]]
*****************************
yi
: [[7.11794189]]
*****************************
y_pred:
 [[3.57445692]]
*****************************
gradients:
 [[-7.08696994]
 [-7.72314148]]
*****************************
theta:
 [[1.3515185]
 [2.1820937]]
*****************************
*****************************
random_index
: 0
*****************************
xi
: [[1.        ]
 [1.09762701]]
*****************************
yi
: [[9.16043901]]
*****************************
y_pred:
 [[3.74664347]]
*****************************
gradients:
 [[-10.82759108]
 [-11.8846564 ]]
*****************************
theta:
 [[1.45979441]
 [2.30094026]]
*****************************
*****************************
random_index
: 3
*****************************
xi
: [[1.        ]
 [1.08976637]]
*****************************
yi
: [[7.11794189]]
*****************************
y_pred:
 [[3.96728172]]
*****************************
gradients:
 [[-6.30132035]
 [-6.86696698]]
*****************************
theta:
 [[1.52280761]
 [2.36960993]]
*****************************
*****************************
random_index
: 1
*****************************
xi
: [[1.        ]
 [1.43037873]]
*****************************
yi
: [[7.31385832]]
*****************************
y_pred:
 [[4.91224726]]
*****************************
gradients:
 [[-4.80322211]
 [-6.87042676]]
*****************************
theta:
 [[1.57083983]
 [2.4383142 ]]
*****************************
"""



Comentarios sobre la versión: V.0 (0)


No hay comentarios
 

Comentar la versión: V.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s7434