In [1]:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

In [82]:
class Optimizer():
    def __init__(self):
        self.sess = tf.Session()
        init_op = tf.global_variables_initializer()
        self.sess.run(init_op);
        
        self.variables = tf.global_variables()
        self.generateInitialPoblation()
        
    def printData(self):
        iterator = self.data.make_initializable_iterator()
        self.sess.run(iterator.initializer)
        next_element = iterator.get_next()
        item =  next_element
        while True:
            try: 
                item =self.sess.run(next_element)
                print(item)
            except tf.errors.OutOfRangeError:
                break
        
    def setFunction(self,model):
        self.model = model 
    
    def evaluationSurvival(self,function = None , poblation = None ):
        poblation = self.data
        function = self.evaluationTensor
        def temporal(*x):
            return {"people":x,"survive":self.evaluationTensor(x)}
        self.data = poblation.map(temporal)
        return self.data
    
    def evaluationTensor(self,x):
        i= 0
        print(x)
        print(self.variables)
        for variable in x:
            print(self.variables[i])
            print(self.sess.run(self.variables[i]))
            print(variable)
            
            #self.sess.run(self.variables[i].assign(variable ) )
            i +=1
        return self.sess.run(self.model)
            

    def generateInitialPoblation(self,cant = 30):
        rows = []
        for variable in self.variables:
            col = []
            for i in range(cant):
                col.append(self.sess.run(tf.random.uniform(variable.shape)))
            rows.append(col)
        self.data = tf.data.Dataset.from_tensor_slices(tuple(rows))
    
    def interation(self,dataset = None):
        dataset = self.data
        dataset = self.evaluationSurvival(poblation=dataset)
        iterator = dataset.make_initializable_iterator()
        sess.run(iterator.initializer)
        next_element = iterator.get_next()
        item =  next_element
        while True:
            try: 
                compare= tf.less(item["survive"],sess.run(next_element)["survive"])
                if sess.run(compare):
                    item =sess.run(next_element)
                    print(item)
            except tf.errors.OutOfRangeError:
                break
        self.data = self.fixFunction()
    
    def fixFunction(self,poblation = None):
        poblation = self.data
        function = self.evaluationTensor
        def temporal(*x):
            x = list(x)
            newpeople = tuple(np.array(x[0]["people"]) + np.array(x[0]["people"]) / 2) #put some function
            return {"people":newpeople,"survive":-1 * self.evaluationTensor(newpeople)}
        self.data = poblation.map(temporal)
        return self.data

In [51]:
features, labels = (np.random.sample((100,1)), np.random.sample((100,1)))
dataset = tf.data.Dataset.from_tensor_slices((features,labels))
sess = tf.Session()
def functionDummy(*x):
    total = 0
    print(x)
    for i in x:
        total = pow(i,2)
    return {"people":x,"survive":-total}

dataset = dataset.map(functionDummy)
#maxi = tf.math.argmax(dataset)
#print(maxi)
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()

item =  next_element
while True:
    try: 
        compare= tf.less(item["survive"],sess.run(next_element)["survive"])
        if sess.run(compare):
            item =sess.run(next_element)
    except tf.errors.OutOfRangeError:
        break

def fixFunction(*x):
    p
    newpeople = x["people"] + x["people"] / 2
    return {"people":newpeople,"survive":functionDummy(newpeople)}
    
#dataset = dataset.map(fixFunction)


(<tf.Tensor 'arg0:0' shape=(1,) dtype=float64>, <tf.Tensor 'arg1:0' shape=(1,) dtype=float64>)

In [76]:
dicc = dict()

In [77]:
dicc["amarillo"] = 1

In [79]:
dicc["amarillo"] = 3
print(dicc)


{'amarillo': 3}

In [88]:
- pow(0.1205712,2) + pow(0.04627164,2)


Out[88]:
-0.0123963496011504

In [91]:
pow(0.53631437,2) +  pow(0.14657798,2)


Out[91]:
0.30911820768937737

In [99]:
functionDummy(0.6784184, 0.14471732)


(0.6784184, 0.14471732)
Out[99]:
{'people': (0.6784184, 0.14471732), 'survive': -0.020943102707982404}

In [4]:
x = tf.Variable(-0.5, np.float32)
y = tf.Variable(+3.5, np.float32)

f = tf.add(tf.multiply(tf.constant(100.),
                       tf.pow(tf.subtract(tf.pow(x, 2), y), 2)),
           tf.pow(tf.subtract(tf.constant(1.0), x), 2))
#with tf.name_scope("inner"):
#    c_3 = tf.Variable(+3.0, np.float32,name="c")


WARNING:tensorflow:From /home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.

In [7]:
type(f)


Out[7]:
tensorflow.python.framework.ops.Tensor

In [42]:
sess = tf.Session() 
init_op = tf.initialize_all_variables()

rows = []
for variable in tf.global_variables():
    col = []
    for i in range(30):
        col.append( tf.random.uniform(variable.shape))
    rows.append(col)
data = tf.data.Dataset.from_tensor_slices(tuple(rows))


sess = tf.Session() 
iterator = data.make_initializable_iterator()
sess.run(iterator.initializer)
next_element = iterator.get_next()
sess.run(init_op)
item =  next_element
#while True:
#    try: 
item =sess.run(next_element)
print(item)
i = 0
variables = tf.global_variables()
for a in item:
    print(a)
          #print(sess.run(a))
            #rand = tf.random.uniform(varibles[1].shape)
    sess.run(variables[i].assign(a))
    i = 1 + i
    print(sess.run(f))
    sess.run(f)   
        
#    except tf.errors.OutOfRangeError:
#        break
        
# Later, when launching the model


(0.65712154, 0.37932134)
0.65712154
941.4973
0.37932134
0.39305806

In [62]:
sess = tf.Session()
rows = []
for variable in tf.global_variables():
    col = []
    for i in range(30):
        col.append( tf.random.uniform(variable.shape))
    rows.append(col)
data = tf.data.Dataset.from_tensor_slices(tuple(rows))

iterator = data.make_initializable_iterator()
sess.run(iterator.initializer)
next_element = iterator.get_next()

item =  next_element
while True:
    try: 
        item =sess.run(next_element)
        print(item)
    except tf.errors.OutOfRangeError:
        break


(0.92750037, 0.82687163)
(0.36523414, 0.2737589)
(0.4472506, 0.21987486)
(0.69192314, 0.75151336)
(0.38783383, 0.43798935)
(0.38869834, 0.37299967)
(0.69539905, 0.17148936)
(0.7522017, 0.7181438)
(0.24272037, 0.6994096)
(0.8398237, 0.27900386)
(0.90505564, 0.8372905)
(0.13382292, 0.4928975)
(0.84191275, 0.8937607)
(0.7669823, 0.7687621)
(0.8292725, 0.8917409)
(0.49633276, 0.39680684)
(0.6721927, 0.040336728)
(0.5383545, 0.89951587)
(0.60225534, 0.020318508)
(0.99506915, 0.7353401)
(0.3362385, 4.351139e-05)
(0.868721, 0.7624389)
(0.89533806, 0.14473999)
(0.281438, 0.6008606)
(0.96899045, 0.9836314)
(0.8960818, 0.23692787)
(0.59748137, 0.18399608)
(0.77152646, 0.07108486)
(0.12673962, 0.100614786)
(0.6253387, 0.8152827)

In [83]:
optimizer = Optimizer()
print(optimizer.variables)
optimizer.setFunction(f)
print(optimizer.model)
optimizer.printData()
print("ejecucion")
optimizer.interation()
optimizer.printData()


[<tf.Variable 'Variable:0' shape=() dtype=float32_ref>, <tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>]
Tensor("Add:0", shape=(), dtype=float32)
(0.60540533, 0.4732709)
(0.37734032, 0.8071979)
(0.95910096, 0.8282131)
(0.54336286, 0.31462848)
(0.302274, 0.0023195744)
(0.07816541, 0.60397863)
(0.001139164, 0.42052138)
(0.95471656, 0.45610714)
(0.6735506, 0.25371826)
(0.71018887, 0.33508396)
(0.87423015, 0.48684394)
(0.77844775, 0.36384428)
(0.35760427, 0.22908044)
(0.55290973, 0.6763756)
(0.60404444, 0.41138542)
(0.39809358, 0.0777514)
(0.41345024, 0.6378765)
(0.34348905, 0.16179764)
(0.2402184, 0.0574975)
(0.776163, 0.7669704)
(0.6966953, 0.94779384)
(0.56800413, 0.5053092)
(0.66295743, 0.5272845)
(0.709371, 0.21822238)
(0.4762125, 0.19627428)
(0.31355798, 0.8342862)
(0.3162216, 0.8531381)
(0.09320986, 0.8141458)
(0.9451724, 0.034667373)
(0.48276138, 0.8812784)
ejecucion
(<tf.Tensor 'arg0:0' shape=() dtype=float32>, <tf.Tensor 'arg1:0' shape=() dtype=float32>)
[<tf.Variable 'Variable:0' shape=() dtype=float32_ref>, <tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>]
<tf.Variable 'Variable:0' shape=() dtype=float32_ref>
-0.5
Tensor("arg0:0", shape=(), dtype=float32)
<tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>
3.5
Tensor("arg1:0", shape=(), dtype=float32)
(<tf.Tensor 'add:0' shape=() dtype=float32>, <tf.Tensor 'add_1:0' shape=() dtype=float32>)
[<tf.Variable 'Variable:0' shape=() dtype=float32_ref>, <tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>]
<tf.Variable 'Variable:0' shape=() dtype=float32_ref>
-0.5
Tensor("add:0", shape=(), dtype=float32)
<tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>
3.5
Tensor("add_1:0", shape=(), dtype=float32)
{'people': (0.908108, 0.70990634), 'survive': 1058.5}
{'people': (0.5660105, 1.2107968), 'survive': 1058.5}
{'people': (1.4386514, 1.2423196), 'survive': 1058.5}
{'people': (0.8150443, 0.47194272), 'survive': 1058.5}
{'people': (0.45341098, 0.0034793615), 'survive': 1058.5}
{'people': (0.11724812, 0.90596795), 'survive': 1058.5}
{'people': (0.001708746, 0.63078207), 'survive': 1058.5}
{'people': (1.4320748, 0.6841607), 'survive': 1058.5}
{'people': (1.0103259, 0.3805774), 'survive': 1058.5}
{'people': (1.0652833, 0.50262594), 'survive': 1058.5}
{'people': (1.3113452, 0.7302659), 'survive': 1058.5}
{'people': (1.1676717, 0.5457664), 'survive': 1058.5}
{'people': (0.5364064, 0.34362066), 'survive': 1058.5}
{'people': (0.8293646, 1.0145634), 'survive': 1058.5}
{'people': (0.90606666, 0.6170781), 'survive': 1058.5}
{'people': (0.5971404, 0.1166271), 'survive': 1058.5}
{'people': (0.62017536, 0.95681477), 'survive': 1058.5}
{'people': (0.5152336, 0.24269646), 'survive': 1058.5}
{'people': (0.3603276, 0.08624625), 'survive': 1058.5}
{'people': (1.1642444, 1.1504556), 'survive': 1058.5}
{'people': (1.045043, 1.4216907), 'survive': 1058.5}
{'people': (0.8520062, 0.75796384), 'survive': 1058.5}
{'people': (0.99443614, 0.79092675), 'survive': 1058.5}
{'people': (1.0640564, 0.32733357), 'survive': 1058.5}
{'people': (0.71431875, 0.29441142), 'survive': 1058.5}
{'people': (0.47033697, 1.2514293), 'survive': 1058.5}
{'people': (0.4743324, 1.2797072), 'survive': 1058.5}
{'people': (0.1398148, 1.2212187), 'survive': 1058.5}
{'people': (1.4177587, 0.05200106), 'survive': 1058.5}
{'people': (0.7241421, 1.3219175), 'survive': 1058.5}

In [18]:
type(sess.run(tf.random.uniform([1,2])))


Out[18]:
numpy.ndarray

In [74]:
np.array((1, 2)) / 2


Out[74]:
array([0.5, 1. ])

In [2]:
x = tf.Variable(-20, np.float32)
y = tf.Variable(-30, np.float32)
f = tf.pow(tf.add(x,y), 2)


WARNING:tensorflow:From /home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.

In [25]:
T = 1000
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op);
    #T = tf.Variable(T0,trainable=False)
    f_old = f.eval()
    x_old = x.eval()
    y_old = y.eval()
    
    #w= tf.assign(f,2)
    x_update = x.assign(x.eval() - 1)
    y_update = y.assign(y.eval() )
    #x_reupdate = x.assign(x.eval() - 1)
    #ejecutar session
    with tf.control_dependencies([x_update,y_update]):
    #print(sess.run([ y_update, x_update]))
        x_update_err = x_update
        y_update_err = y_update
        delta = f.eval() - f_old
        if delta > 0 :
            print("delta")
            next
        elif pow(np.e, -delta/ T) >= np.random.uniform():
            print("probablidad" + str(pow(np.e, -delta/ T)))
            next
        else:
            x_update_err = x.assign(x_old)
            y_update_err = y.assign(y_old)
    #print(type(x_update_err))
    sess.run([y_update_err, x_update_err])
    
    print(x.eval(), y.eval())


probablidad1.0
<class 'tensorflow.python.framework.ops.Tensor'>
-21 -30

In [4]:
class OptimizadorN():#tf.Operation):
    def set_objetive(self,obj):
        self.obj= obj
    
    def __init__(self, T = 100):
        self.variables = tf.global_variables()
        self.T = T
        #self._graph = tf.get_default_graph()
        #self._c_op = None
    def method(self):
        f_old = self.obj.eval()
        var = []
        dependencies = []
        for variable in self.variables:
            var.append (variable.assign(variable.eval()))
            dependencies.append (variable.assign(variable.eval() - np.random.uniform()))
        with tf.control_dependencies(dependencies):
        #print(sess.run([ y_update, x_update]))
            nodes = dependencies
            delta = f.eval() - f_old
            if delta > 0 :
                next
            elif pow(np.e, -delta/ self.T) >= np.random.uniform():
                #print("probablidad" + str(pow(np.e, -delta/ self.T)))
                next
            else:
                nodes = var
        self.operaciones = nodes
        
    def eval(self):
        self.method()
        return(self.operaciones)

# bloque principal

opt =OptimizadorN()
opt.set_objetive(f)
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op);
    #la funcion solo returna los nodos del grafo que deben ser ejecutados, a la final yo los encadeno en evaluar el assign del 
    #valor en el que deben terminar las variables  
    print(sess.run(opt.eval()))
    #Vea que si se necesita que sea un tensor para mandarlo directo
    print(sess.run(opt))


probablidad1.0
[-20, -30]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    299         self._unique_fetches.append(ops.get_default_graph().as_graph_element(
--> 300             fetch, allow_tensor=True, allow_operation=True))
    301       except TypeError as e:

/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3477     with self._lock:
-> 3478       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3479 

/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3566       raise TypeError("Can not convert a %s into a %s." % (type(obj).__name__,
-> 3567                                                            types_str))
   3568 

TypeError: Can not convert a OptimizadorN into a Tensor or Operation.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-c95eb16425b5> in <module>()
     43     print(sess.run(opt.eval()))
     44     #Vea que si se necesita que sea un tensor para mandarlo directo
---> 45     print(sess.run(opt))

/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1135     # Create a fetch handler to take care of the structure of fetches.
   1136     fetch_handler = _FetchHandler(
-> 1137         self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
   1138 
   1139     # Run request and get response.

/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, graph, fetches, feeds, feed_handles)
    469     """
    470     with graph.as_default():
--> 471       self._fetch_mapper = _FetchMapper.for_fetch(fetches)
    472     self._fetches = []
    473     self._targets = []

/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in for_fetch(fetch)
    269         if isinstance(fetch, tensor_type):
    270           fetches, contraction_fn = fetch_fn(fetch)
--> 271           return _ElementFetchMapper(fetches, contraction_fn)
    272     # Did not find anything.
    273     raise TypeError('Fetch argument %r has invalid type %r' % (fetch,

/home/alesgaco/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py in __init__(self, fetches, contraction_fn)
    302         raise TypeError('Fetch argument %r has invalid type %r, '
    303                         'must be a string or Tensor. (%s)' %
--> 304                         (fetch, type(fetch), str(e)))
    305       except ValueError as e:
    306         raise ValueError('Fetch argument %r cannot be interpreted as a '

TypeError: Fetch argument <__main__.OptimizadorN object at 0x7fdc040e2518> has invalid type <class '__main__.OptimizadorN'>, must be a string or Tensor. (Can not convert a OptimizadorN into a Tensor or Operation.)

In [5]:
[1,2,3,4,5,10][0]


Out[5]:
1

In [6]:
np.random.uniform()


Out[6]:
0.5564745307026296

In [ ]: