[R-es] optimizacion costos

Javier Marcuzzi j@v|er@ruben@m@rcuzz| @end|ng |rom gm@||@com
Jue Ene 17 12:55:37 CET 2019


Estimados

Encontré un ejemplo que se aproxima a mi pregunta, lo copio y pego para
compartirlo. Lo primero como para comentar es la facilidad de R respecto a
python y tensorflow, aunque estos podrían utilizar una cantidad de 1000
computadoras con GPU gratuitas para entrenamiento del modelo.

Lo segundo, es sobre la función para optimizar, este ejemplo utiliza
algoritmo genético, pienso que debe haber una forma más simple, pienso en
la forma que optimizan la regresión, en utilizar esos algoritmos.

Leí que R es mejor que tensorflow para la investigación, pero tensorflow
tiene mejores prestaciones para producción, quiero probar como especifica
RStudio, jugar un poco con R y sus alternativas.

Lógicamente que lo siguiente prefiero realizarlo en R, la función optimize
de tensorflow es la que me interesa usar en R en un problema genérico de
optimización de costos, según el siguiente ejemplo de tensorflow en R: model
%>% compile <http://www.rdocumentation.org/packages/generics/topics/compile>
(
  loss = 'categorical_crossentropy',
  optimizer = optimizer_rmsprop
<https://keras.rstudio.com/reference/optimizer_rmsprop.html>(),
  metrics = c('accuracy')
)

# Implementing a Genetic Algorithm
# -------------------------------
#
# Genetic Algorithm Optimization in TensorFlow
#
# We are going to implement a genetic algorithm
#   to optimize to a ground truth array.  The ground
#   truth will be an array of 50 floating point
#   numbers which are generated by:
#   f(x)=sin(2*pi*x/50) where 0<x<50
#
# Each individual will be an array of 50 floating
# point numbers and the fitness will be the average
#   mean squared error from the ground truth.
#
# We will use TensorFlow's update function to run the
#   different parts of the genetic algorithm.
#
# While TensorFlow isn't really the best for GA's,
# this example shows that we can implement different
#   procedural algorithms with TensorFlow operations.

import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()


# Genetic Algorithm Parameters
pop_size = 100
features = 50
selection = 0.2
mutation = 1./pop_size
generations = 200
num_parents = int(pop_size*selection)
num_children = pop_size - num_parents

# Start a graph session
sess = tf.Session()

# Create ground truth
truth = np.sin(2*np.pi*(np.arange(features, dtype=np.float32))/features)

# Initialize population array
population = tf.Variable(np.random.randn(pop_size, features), dtype=
tf.float32)

# Initialize placeholders
truth_ph = tf.placeholder(tf.float32, [1, features])
crossover_mat_ph = tf.placeholder(tf.float32, [num_children, features])
mutation_val_ph = tf.placeholder(tf.float32, [num_children, features])

# Calculate fitness (MSE)
fitness = -tf.reduce_mean(tf.square(tf.subtract(population, truth_ph)), 1)
top_vals, top_ind = tf.nn.top_k(fitness, k=pop_size)

# Get best fit individual
best_val = tf.reduce_min(top_vals)
best_ind = tf.argmin(top_vals, 0)
best_individual = tf.gather(population, best_ind)

# Get parents
population_sorted = tf.gather(population, top_ind)
parents = tf.slice(population_sorted, [0, 0], [num_parents, features])


# Get offspring
# Indices to shuffle-gather parents
rand_parent1_ix = np.random.choice(num_parents, num_children)
rand_parent2_ix = np.random.choice(num_parents, num_children)
# Gather parents by shuffled indices, expand back out to pop_size too
rand_parent1 = tf.gather(parents, rand_parent1_ix)
rand_parent2 = tf.gather(parents, rand_parent2_ix)
rand_parent1_sel = tf.multiply(rand_parent1, crossover_mat_ph)
rand_parent2_sel = tf.multiply(rand_parent2, tf.subtract(1.,
crossover_mat_ph))
children_after_sel = tf.add(rand_parent1_sel, rand_parent2_sel)

# Mutate Children
mutated_children = tf.add(children_after_sel, mutation_val_ph)

# Combine children and parents into new population
new_population = tf.concat(axis=0, values=[parents, mutated_children])

step = tf.group(population.assign(new_population))

init = tf.global_variables_initializer()
sess.run(init)

# Run through generations
for i in range(generations):
    # Create cross-over matrices for plugging in.
    crossover_mat = np.ones(shape=[num_children, features])
    crossover_point = np.random.choice(np.arange(1, features-1, step=1),
num_children)
    for pop_ix in range(num_children):
        crossover_mat[pop_ix,0:crossover_point[pop_ix]]=0.
    # Generate mutation probability matrices
    mutation_prob_mat = np.random.uniform(size=[num_children, features])
    mutation_values = np.random.normal(size=[num_children, features])
    mutation_values[mutation_prob_mat >= mutation] = 0

    # Run GA step
    feed_dict = {truth_ph: truth.reshape([1, features]),
                 crossover_mat_ph: crossover_mat,
                 mutation_val_ph: mutation_values}
    step.run(feed_dict, session=sess)
    best_individual_val = sess.run(best_individual, feed_dict=feed_dict)

    if i % 5 == 0:
         best_fit = sess.run(best_val, feed_dict = feed_dict)
         print('Generation: {}, Best Fitness (lowest MSE): {:.2}'.format(i,
-best_fit))

plt.plot(truth, label="True Values")
plt.plot(np.squeeze(best_individual_val), label="Best Individual")
plt.axis((0, features, -1.25, 1.25))
plt.legend(loc='upper right')
plt.show()



El mié., 16 ene. 2019 a las 9:57, Javier Marcuzzi (<
javier.ruben.marcuzzi using gmail.com>) escribió:

> Estimado Jesús Para Fernández
>
> En teoría es ese material, lo vi muy rápido y en la parte genética tiene
> cosas que biológicamente no son así, hay un libro de Falconer, Introducción
> a la genética cuantitativa, que tiene escrita la parte matemática, hay un
> abismo entre la biología y los ingenieros que se inspiran en la biología.
>
> Yo pensaba en la resolución de un problema real, aunque relativamente
> simple como puede ser el de mínimos costos, donde se utilice tensorflow, en
> otras palabras, R tiene paquetes para la optimización, entonces me hago una
> pregunta, ¿que pasa si tomo uno de esos ejemplos y lo corro con la librería
> R del paquete y con Keras como documenta Rstudio utilizando tensorflow? Los
> ejemplos son de reconocimiento de imágenes, regresión, clasificación, pero
> ¿optimización?
>
> Javier Rubén Marcuzzi
>
> El mié., 16 ene. 2019 a las 3:45, Jesús Para Fernández (<
> j.para.fernandez using hotmail.com>) escribió:
>
>> Buenas Javier,
>>
>>
>> Sobre temas de optimización hay unos apuntes de la universidad de Granada
>> que son realmente buenos. TE aconsejo que les eches un vistazo (basan su
>> código en matlab)
>>
>> https://elvex.ugr.es/decsai/iaio/
>>
>>
>> Un saludo
>> Jesús
>> ------------------------------
>> *De:* R-help-es <r-help-es-bounces using r-project.org> en nombre de Javier
>> Marcuzzi <javier.ruben.marcuzzi using gmail.com>
>> *Enviado:* miércoles, 16 de enero de 2019 4:14
>> *Para:* r-help-es
>> *Asunto:* [R-es] optimizacion costos
>>
>> Estimados.
>>
>> Hace un tiempo que tengo una duda, estaba pensando en los problemas como
>> optimización de costos, donde hay varias alternativas y librerías, pasando
>> por soluciones inspiradas en energía, genética o algo matemático como
>> matrices y álgebra.
>>
>> Luego aparecen tensorflow, cntk, y otros tantos, de los cuáles
>> https://keras.rstudio.com/ ofrece alternativas para mezclar los mundos
>> por
>> decirlo de alguna forma.
>>
>> De estos si miro https://keras.rstudio.com/ observo en la documentación
>> lo
>> que aparece siempre, la optimización. En este caso sería lo siguiente:
>>
>> model %>% compile
>> <http://www.rdocumentation.org/packages/generics/topics/compile>(
>>   loss = 'categorical_crossentropy',
>>   optimizer = optimizer_rmsprop
>> <https://keras.rstudio.com/reference/optimizer_rmsprop.html>(),
>>   metrics = c('accuracy')
>> )
>>
>> Ahora mi pregunta, es posible con esos optimizadores, tomar un problema
>> para producir a mínimo costo, o al contrario, para maximizar las
>> ganancias?
>>
>> Alguno de ustedes vio un ejemplo al respecto? No me refiero a los muchos
>> desarrollados en el R clásico, sino en R que conecta por ejemplo a
>> tensorflow con keras, o en su defecto python que conecta muy simple con
>> tensorflow.
>>
>> Con R lo resuelvo, pero me crea la duda estos optimizadores y no he
>> explorado esa alternativa pero me intriga y lo intentaría de puro gusto o
>> desafío personal.
>>
>> Agradezco comentarios.
>>
>> Javier Rubén Marcuzzi
>>
>>         [[alternative HTML version deleted]]
>>
>> _______________________________________________
>> R-help-es mailing list
>> R-help-es using r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-help-es
>>
>

	[[alternative HTML version deleted]]



Más información sobre la lista de distribución R-help-es