Foros del Web » Programando para Internet » Python »

[SOLUCIONADO] Duda con kwargs.pop()

Estas en el tema de Duda con kwargs.pop() en el foro de Python en Foros del Web. En la línea 15 quiero que los limites sean 0 < umbral < 1, como se usa kwargs.pop(), para evitar ValueError: cannot convert float NaN ...
  #1 (permalink)  
Antiguo 31/03/2013, 12:36
 
Fecha de Ingreso: julio-2011
Mensajes: 62
Antigüedad: 12 años, 9 meses
Puntos: 0
Pregunta Duda con kwargs.pop()

En la línea 15 quiero que los limites sean 0 < umbral < 1, como se usa kwargs.pop(), para evitar ValueError: cannot convert float NaN to integer debido a log(0.0). log(-0.1), ..., log(-0.9999), el intervalo actual seria -0.9999 < umbral < 0.9999.
Código:
from __future__ import unicode_literals

import numpy as np
from numpy import ma
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
from matplotlib.ticker import Formatter, FixedLocator

class EscalaAcumuladaGumbel(mscale.ScaleBase):

    name = 'gumbel'

    def __init__(self, axis, **kwargs):
        mscale.ScaleBase.__init__(self)
        umbral = kwargs.pop("umbral", 0.9999)
        if umbral >= 1.0:
            raise ValueError("umbral debe ser mayor que 0.0 o menor que 1.0")
        self.umbral = umbral

    def get_transform(self):
        return self.TransformacionAcumuladaGumbel(self.umbral)

    def set_default_locators_and_formatters(self, axis):
        class TresDecimales(Formatter):
            def __call__(self, x, pos=None):
                return '%.3f' % x
        axis.set_major_locator(FixedLocator(np.arange(0.0, 1.0, 0.05)))
        axis.set_major_formatter(TresDecimales())
        axis.set_minor_formatter(TresDecimales())

    def limit_range_for_scale(self, vmin, vmax, minpos):
        return max(vmin, -self.umbral), min(vmax, self.umbral)

    class TransformacionAcumuladaGumbel(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, umbral):
            mtransforms.Transform.__init__(self)
            self.umbral = umbral

        def transform(self, a):
            masked = ma.masked_where((a < -self.umbral) | (a > self.umbral), a)
            if masked.mask.any():
                return 0.156516164484 + (0.0915834783405*(-ma.log(-ma.log(a))))
            else:
                return 0.156516164484 + (0.0915834783405*(-np.log(-np.log(a))))

        def inverted(self):
            return EscalaAcumuladaGumbel.TransformacionInversaAcumuladaGumbel(self.umbral)

    class TransformacionInversaAcumuladaGumbel(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, umbral):
            mtransforms.Transform.__init__(self)
            self.umbral = umbral

        def transform(self, a):
            return np.exp(-np.exp(-a))

        def inverted(self):
            return EscalaAcumuladaGumbel.TransformacionAcumuladaGumbel(self.umbral)

mscale.register_scale(EscalaAcumuladaGumbel)


if __name__ == '__main__':
    import matplotlib.pyplot as plt

    Datos = np.array([ 2690.0, 2700.0, 2700.667, 2701.333, 2702.0, 3196.0, 2372.0, 2395.0, 2128.0, 2727.0, 2431.0, 2850.0, 2216.0, 2057.0, 2269.0, 2208.0, 2628.0, 2729.0, 2588.0, 3448.0, 2508.0, 3081.0, 2417.0, 2770.0, 2283.0, 2455.0, 1963.0, 2786.0, 2885.0, 2357.0, 3422.0, 2423.0, 2148.0, 1305.0, 2472.0, 2186.0, 2720.0, 2430.0, 2304.0, 2556.0, 2625.0, 2164.0, 2585.0, ])
    DatosOrdenados = np.sort(Datos)
    mu = 2353.157
    sigma = 297.961

    y1 = ( DatosOrdenados - mu) / sigma
    x1 = np.exp(-np.exp(-y1))

    plt.plot(x1, y1, 'ro', lw=2)
    plt.gca().set_xscale('gumbel')

    plt.xlabel('F(z)')
    plt.ylabel('z')
    plt.title('Papel de probabilidad de Gumbel')
    plt.xticks(rotation='vertical', fontsize=7)
    plt.grid(True)

    plt.show()

Última edición por Bael_Balzac; 31/03/2013 a las 13:15
  #2 (permalink)  
Antiguo 31/03/2013, 13:50
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Duda con kwargs.pop()

1.- Tu error no esta en la linea 15
2.- El método pop de los diccionarios no esta relacionado a tu problema.
3.- Tu problema esta en la linea 48 falla cuando el array esta lleno de ceros, no validas bien ese caso.

Código Python:
Ver original
  1. from __future__ import unicode_literals
  2.  
  3. import numpy as np
  4. from numpy import ma
  5. from matplotlib import scale as mscale
  6. from matplotlib import transforms as mtransforms
  7. from matplotlib.ticker import Formatter, FixedLocator
  8.  
  9. class EscalaAcumuladaGumbel(mscale.ScaleBase):
  10.  
  11.     name = 'gumbel'
  12.  
  13.     def __init__(self, axis, **kwargs):
  14.         mscale.ScaleBase.__init__(self)
  15.         umbral = kwargs.pop("umbral", 0.9999)
  16.         if not (0 < umbral < 1.0):
  17.             raise ValueError("umbral debe ser mayor que 0.0 o menor que 1.0")
  18.         self.umbral = umbral
  19.  
  20.     def get_transform(self):
  21.         return self.TransformacionAcumuladaGumbel(self.umbral)
  22.  
  23.     def set_default_locators_and_formatters(self, axis):
  24.         class TresDecimales(Formatter):
  25.             def __call__(self, x, pos=None):
  26.                 return '%.3f' % x
  27.         axis.set_major_locator(FixedLocator(np.arange(0.0, 1.0, 0.05)))
  28.         axis.set_major_formatter(TresDecimales())
  29.         axis.set_minor_formatter(TresDecimales())
  30.  
  31.     def limit_range_for_scale(self, vmin, vmax, minpos):
  32.         return max(vmin, -self.umbral), min(vmax, self.umbral)
  33.  
  34.     class TransformacionAcumuladaGumbel(mtransforms.Transform):
  35.         input_dims = 1
  36.         output_dims = 1
  37.         is_separable = True
  38.  
  39.         def __init__(self, umbral):
  40.             mtransforms.Transform.__init__(self)
  41.             self.umbral = umbral
  42.  
  43.         def transform(self, a):
  44.             masked = ma.masked_where((a < -self.umbral) | (a > self.umbral), a)
  45.             if masked.mask.any():
  46.                 return 0.156516164484 + (0.0915834783405*(-ma.log(-ma.log(a))))
  47.             else:
  48.                 if not np.all(a):
  49.                     a = np.empty(a.size)
  50.                     a.fill(.9999)
  51.                 return 0.156516164484 + (0.0915834783405*(-np.log(-np.log(a))))
  52.  
  53.         def inverted(self):
  54.             return EscalaAcumuladaGumbel.TransformacionInversaAcumuladaGumbel(self.umbral)
  55.  
  56.     class TransformacionInversaAcumuladaGumbel(mtransforms.Transform):
  57.         input_dims = 1
  58.         output_dims = 1
  59.         is_separable = True
  60.  
  61.         def __init__(self, umbral):
  62.             mtransforms.Transform.__init__(self)
  63.             self.umbral = umbral
  64.  
  65.         def transform(self, a):
  66.             return np.exp(-np.exp(-a))
  67.  
  68.         def inverted(self):
  69.             return EscalaAcumuladaGumbel.TransformacionAcumuladaGumbel(self.umbral)
  70.  
  71. mscale.register_scale(EscalaAcumuladaGumbel)
  72.  
  73.  
  74. if __name__ == '__main__':
  75.     import matplotlib.pyplot as plt
  76.  
  77.     Datos = np.array([ 2690.0, 2700.0, 2700.667, 2701.333, 2702.0, 3196.0, 2372.0, 2395.0, 2128.0, 2727.0, 2431.0, 2850.0, 2216.0, 2057.0, 2269.0, 2208.0, 2628.0, 2729.0, 2588.0, 3448.0, 2508.0, 3081.0, 2417.0, 2770.0, 2283.0, 2455.0, 1963.0, 2786.0, 2885.0, 2357.0, 3422.0, 2423.0, 2148.0, 1305.0, 2472.0, 2186.0, 2720.0, 2430.0, 2304.0, 2556.0, 2625.0, 2164.0, 2585.0, ])
  78.     DatosOrdenados = np.sort(Datos)
  79.     mu = 2353.157
  80.     sigma = 297.961
  81.  
  82.     y1 = ( DatosOrdenados - mu) / sigma
  83.     x1 = np.exp(-np.exp(-y1))
  84.  
  85.     plt.plot(x1, y1, 'ro', lw=2)
  86.     plt.gca().set_xscale('gumbel')
  87.  
  88.     plt.xlabel('F(z)')
  89.     plt.ylabel('z')
  90.     plt.title('Papel de probabilidad de Gumbel')
  91.     plt.xticks(rotation='vertical', fontsize=7)
  92.     plt.grid(True)
  93.  
  94.     plt.show()
  #3 (permalink)  
Antiguo 31/03/2013, 16:59
 
Fecha de Ingreso: julio-2011
Mensajes: 62
Antigüedad: 12 años, 9 meses
Puntos: 0
Respuesta: Duda con kwargs.pop()

Muchas gracias razpeitia, como supiste que el array contenia ceros, que IDE utilizas para depurar código python.
  #4 (permalink)  
Antiguo 31/03/2013, 17:18
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Duda con kwargs.pop()

No, al ejecutar el script me imprimió la linea donde estaba el problema, seguido de un error de ZeroDivision entonces supe que había un problema en esa parte.

Para ver los valores solo añadi un print para ver que contenía esa variable y después de algunas pruebas puse un fix temporal.

Espero haberte ayudado, si es así no olvides marcar el tema como solucionado.

Etiquetas: mac
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:55.