miércoles, 22 de noviembre de 2017

ISAAC NEWTON

El mejor cerebro que ha dado la humanidad, tocado por la mano de DIOS, el gran Fisico que descubrio las leyes de la naturaleza, Isaac Newton

Si he visto más allá que los demás es porque me entregué mas que nadie al estudio - Isaac Newton



domingo, 12 de noviembre de 2017

Erasmo de Rotterdam, Erasmus of Rotterdam


La verdadera amistad llega cuando el silencio entre dos parece ameno.
/: Amistad
El colmo de la estupidez es aprender lo que luego hay que olvidar.
/: Aprender
La felicidad consiste, principalmente, en conformarse con la suerte; es querer ser lo que uno es.
/: Felicidad
El que conoce el arte de vivir consigo mismo ignora el aburrimiento.
/: Aburrimiento
En el estudio no existe la saciedad.
/: Estudios 
Una buena gran parte del arte del bien hablar consiste en saber mentir con gracia.
/: Hablar
Los zorros usan muchos trucos. Los erizos, sólo uno. Pero es el mejor de todos.
/: Eficacia
La filosofía es una meditación de la muerte.
/: Filosofía
La paz más desventajosa es mejor que la guerra más justa.
/: Paz
Reírse de todo es propio de tontos, pero no reírse de nada lo es de estúpidos.
/: Reír

Erasmo de Rotterdam (1466-1536), uno de los padres del humanismo europeo, es un preclaro ejemplo de la libertad de pensamiento crítico. Su vasta obra, que influyó poderosamente en la literatura reformista y luterana, tiene en el Elogio de la Locura (o Elogio de la Estulticia) uno de sus principales focos de interés. Redactada con enorme ironía, sátira y erudición, en ella el pensador relata las ventajas de una vida estulta sobre una vida basada en la razón, ya que la estupidez o locura garantiza mucha más felicidad que la racionalidad propia de los sabios. Éstos, condenados a las preocupaciones éticas y teóricas que les torturan día y noche, no resultan útiles ni para ellos ni para los que le rodean. El retrato de todos aquellos que desprecian el trabajo filosófico por complejo y falto de humor, practicidad y vida es tan fabuloso como doloroso, porque desnuda las falacias de las comunidades de seres humanos que no permiten que aquél se manifieste -o no lo haga con toda su violencia-, como hacen las nuestras. Pobres sociedades son las que componemos, que no tienen un pensar crítico que las ampare, que las proteja de las inclemencias existenciales, que las salve de su injusticia crónica. En fin, pasen y lean: 
“Y, lo repito una vez más, los que están más lejos de la felicidad son aquellos que más cultivan el saber, mostrándose por eso doblemente necios, pues , a pesar de ser hombres, se olvidan de su condición y acumulando sus ciencias una sobre la otra pretenden emular a los dioses y declarar como los Gigantes la guerra a la Naturaleza, valiéndose de estos ardides, lo que demuestra que los menos desdichados son los que siguiendo su instinto se aproximan más a la sandez y cualidades de los brutos y no intentan nada que esté por encima de la condición humana, y voy a demostrar este aserto aunque no ciertamente valiéndome de los entimemas de los estoicos, sino con un ejemplo evidente que entre por los ojos.
Decidme, por todos los dioses del Olimpo, ¿es alguien más feliz que esos hombres a quienes todos llaman locos, necios, imbéciles y sandios, epítetos que son, a mi entender, los más honrosos? A primera vista, esta afirmación quizá parezca desatinada y absurda, y sin embargo, es verdadera, porque estos seres se ven libres del temor de la muerte, lo cual, ¡por Júpiter! , no es pequeña ventaja; no son capaces de sentir remordimientos; no sienten el terror por los aparecidos; no se espantan de fantasmas ni de duendes, no se inquietan por los futuros males, ni les anima tampoco la esperanza de venideros bienes; en una palabra, no están esclavizados por el sinnúmero de preocupaciones que atormentan la vida de los demás. Por nada se avergüenzan, no tienen respeto, ni ambición, ni envida, ni celos y, por últimos, si son tan estúpidos como los brutos, tienen el galardón de la pureza, pues según los teólogos sobre ellos no recae el pecado.
¡Oh, estulto filósofo! Medita ahora todo lo que te digo y considera los cuidados que te torturan día y noche; calcula las molestias que constantemente te inquietan y comprenderás al fin los muchísimos males que ahorro a mis amados necios. Y no solamente es que ellos se diviertan, jueguen, bromeen, canten y rían a todas horas, sino que llevan consigo el placer, la diversión, la alegría y la broma, que transmiten a los demás, como si hubieran recibido esta virtud por especial indulgencia de los dioses para disipar la tristeza de la Humanidad. De esta forma, mientras los otros hombre inspiran a los demás afectos muy distintos, los míos son muy bien recibidos, siempre con agrado, como si se tratase de antiguos camaradas, y considerándolo como amigos los buscan, los regalan, los alimentan, los festejan, los protegen y les perdonan todo lo que dicen y hacen. Nadie intenta causarles daño.
Los grandes y los reyes son tan aficionados a mis protegidos que muchos no pueden comer, ni pasear, ni vivir un sólo instante sin sus bufones, y con frecuencia los prefieren y los colocan muy por encima de esos austeros sabios que por vanidad sostienen a su costa. El motivo de esta preferencia no puede ocultarse ni sorprender a nade, ya que los sabios, engreídos con su saber, no hablan a los príncipes más que de cosas tristes y con frecuencia “con la verdad mordaz hieren los oídos delicados”, en tanto que los sandios bufones, al contrario, procuran a los príncipes lo que ellos desean sobre todas las cosas y buscan con tanto afán: los pasatiempos, las alegrías, las risas y las distracciones, y además hay que tener en cuenta la calidad de estos necios de ser siempre francos y sinceros, porque, ¿hay algo más admirable que la verdad? (…) Afirma Eurípides que “el loco no dice más que locuras”, lo cual ha quedado entre nosotros de proverbio. Es cierto que en el loco su corazón, su cara y sus labios están siempre de acuerdo. En cambio, los sabios, según las palabras del mismo Eurípides, “tienen dos lenguas: una que dice la verdad y otra que dice lo que le conviene”. Para ellos lo que hoy es es blanco mañana es negro y con la misma boca soplan lo frío que lo caliente, porque hay una gran diferencia entre lo que ellos interiormente piensan y lo que dejan traslucir sus palabras.”

Palas y Estulticia  Erasmo de Rotterdam

“Por ende, si el más torpe es el más satisfecho de sí y el rodeado de mayor admiración, ¿quién preferirá la verdadera sabiduría, que cuesta tanto trabajo adquirir, que vuelve luego más vergonzoso y más tímido, y que, en suma, complace a mucha menos gente?” (Erasmo de Rotterdam, Elogio de la Locura, capítulo XLII).


Las edades del hombre

      “¿Quién ignora que la edad más alegre del hombre es con mucho la primera, y que es la más grata a todos?” (Erasmo de Rotterdam, Elogio de la locura, capítulo XIII).
      Estulticia no sólo es la responsable del origen de la vida, sino que también está presente a lo largo de todas sus etapas, aunque de distinta manera. Durante la infancia se manifiesta con claridad, pues sólo gracias a ella los niños son capaces de soportar las lecciones de sus maestros y ganarse los beneficios de sus protectores. Por eso, siempre tenemos ganas de abrazarlos y de besarlos, siempre acabamos perdonando sus travesuras (o riéndonos con ellas).
     También durante la juventud está presente Estulticia. A ella se debe el encanto que tiene esta etapa, caracterizada por su falta de sensatez. Son los años más placenteros en la vida de cualquier persona, de los que se tiene siempre un mejor recuerdo. Es el momento en el que nos sentimos capaces casi de cualquier cosa, por muy difícil o absurda que sea.
     Sin embargo, a medida que el ser humano crece empieza a cobrar prudencia, como dice Estulticia. Entonces “descaece su hermosura, languidece su alegría, se deshiela su donaire”. Cuando llega a su edad adulta, el hombre debe organizar su vida, hacer frente a las preocupaciones que le van surgiendo… Es una etapa más dura y pesada, en la que se aleja de Estulticia y de los placeres que ésta podría proporcionarle.
     Finalmente, llega la vejez. Este es un momento molesto tanto para los que lo sufren como para los que conviven con ellos. Ningún mortal sería capaz de soportarlo si Estulticia no estuviera allí para devolverlo de nuevo a su infancia. En este sentido, hay gran parecido entre los niños y los ancianos: ambos divagan y tontean. De hecho, los dos disfrutan mucho en compañía. Así pues, la Insensatez, en la última etapa de la vida se apiada de aquellos que deben soportar el peso de los años y los libera de sus preocupaciones: “he favorecido al viejo haciéndole delirar […] gracias a mi favor el viejo es feliz, grato a sus amigos y no tiene nada de inepto para las fiestas”.

Amor, matrimonio y procreación

                             








     Estulticia debe convencer al público de lo necesaria que es. Por eso, se sitúa en la fuente misma de la vida. En este sentido, es capaz de hacer que el más sabio recurra a ella si quiere ser padre, pues es “aquella otra parte tan estulta y tan ridícula, que no puede nombrarse sin suscitar risa, la que propaga el género humano”. Y, por otra parte, “¿qué mujer permitiría el acceso de un varón si conociese o considerase los peligrosos trabajos del parto o la molestia de la educación de los hijos?” o “¿qué hombre ofrecería la cabeza al yugo del matrimonio si, como suelen hacer los sabios, meditase antes los inconvenientes que le traerá tal vida?” (capítulo XI). Así, en el matrimonio y en la procreación está presente Estulticia a través de algunos de sus acompañantes como la Demencia o el Olvido (éste hace que una mujer que haya pasado por estas incomodidades decida repetirlas).
    También al amor, tan relacionado con estos aspectos, tiene parentesco con Estulticia: “¿por qué es siempre niño Cupido? ¿Por qué si no por ser un bromista y no hacer ni pensar nada nunca a derechas?” (capítulo XV). A menudo se habla del amor como de algo irracional, que no se puede evitar ni controlar por muy perjudicial que pueda resultar. Se dice que es ciego (ajeno a todo defecto, cualquier inconveniente que pueda provocar), y a eso se refiere también la Locura cuando dice: “Cupido, padre y autor de todo afecto, que, por obra de su ceguera, toma lo feo por hermoso, hace que entre vosotros cada cual encuentre hermoso lo que ama, de suerte que el viejo quiera a la vieja como el mozo a la moza” (capítulo XIX). Pero, ¿es esto una prueba definitiva de lo irracional del amor? Si el viejo quiere a la vieja no es porque no la vea tal como es, sino por lo que ella le aporta, por la unión que hay entre los dos, porque le resulta más afín a él mismo que cualquier joven. ¿Eso no tiene nada de racional? Nos acercamos a quien despierta en nosotros estos sentimientos aunque no nos convenga si lo que recibimos a cambio –o lo que creemos que podemos recibir- es más que lo que vamos a perder –o lo que creemos que podemos perder-, si pensamos en ese momento que merece la pena. No todo en el amor puede ser impulso y ceguera, pues éstos no suelen durar mucho. En cada decisión que tomamos, en cualquier aspecto de nuestra vida, la razón y los sentimientos se entremezclan sin que podamos diferenciarlos del todo. Nunca la razón puede ser acallada del todo y nunca los sentimientos pueden olvidarse. Es posible que a veces primen más unos u otra, pero al fin y al cabo dejarse llevar por un impulso en un determinado momento no deja de ser una decisión.

domingo, 5 de noviembre de 2017

scipy python for machine learning

https://www.scipy.org/


http://pythonfiddle.com/

NumPy

NumPy is the fundamental package for scientific computing with Python. It contains among other things:
  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.
NumPy is licensed under the BSD license, enabling reuse with few restrictions.

Getting Started

SciPy library

The SciPy library is one of the core packages that make up the SciPy stack. It provides many user-friendly and efficient numerical routines such as routines for numerical integration and optimization.

Basic functions

Interaction with Numpy

Scipy builds on Numpy, and for all basic array handling needs you can use Numpy functions:
>>>
>>> import numpy as np
>>> np.some_function()
Rather than giving a detailed description of each of these functions (which is available in the Numpy Reference Guide or by using the helpinfoand source commands), this tutorial will discuss some of the more useful commands which require a little introduction to use to their full potential.
To use functions from some of the Scipy modules, you can do:
>>>
>>> from scipy import some_module
>>> some_module.some_function()
The top level of scipy also contains functions from numpy and numpy.lib.scimath. However, it is better to use them directly from the numpymodule instead.

Index Tricks

There are some class instances that make special use of the slicing functionality to provide efficient means for array construction. This part will discuss the operation of np.mgrid , np.ogrid , np.r_ , and np.c_ for quickly constructing arrays.
For example, rather than writing something like the following
>>>
>>> a = np.concatenate(([3], [0]*5, np.arange(-1, 1.002, 2/9.0)))
with the r_ command one can enter this as
>>>
>>> a = np.r_[3,[0]*5,-1:1:10j]
which can ease typing and make for more readable code. Notice how objects are concatenated, and the slicing syntax is (ab)used to construct ranges. The other term that deserves a little explanation is the use of the complex number 10j as the step size in the slicing syntax. This non-standard use allows the number to be interpreted as the number of points to produce in the range rather than as a step size (note we would have used the long integer notation, 10L, but this notation may go away in Python as the integers become unified). This non-standard usage may be unsightly to some, but it gives the user the ability to quickly construct complicated vectors in a very readable fashion. When the number of points is specified in this way, the end- point is inclusive.
The “r” stands for row concatenation because if the objects between commas are 2 dimensional arrays, they are stacked by rows (and thus must have commensurate columns). There is an equivalent command c_ that stacks 2d arrays by columns but works identically to r_ for 1d arrays.
Another very useful class instance which makes use of extended slicing notation is the function mgrid. In the simplest case, this function can be used to construct 1d ranges as a convenient substitute for arange. It also allows the use of complex-numbers in the step-size to indicate the number of points to place between the (inclusive) end-points. The real purpose of this function however is to produce N, N-d arrays which provide coordinate arrays for an N-dimensional volume. The easiest way to understand this is with an example of its usage:
>>>
>>> np.mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4]],
       [[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]]])
>>> np.mgrid[0:5:4j,0:5:4j]
array([[[ 0.    ,  0.    ,  0.    ,  0.    ],
        [ 1.6667,  1.6667,  1.6667,  1.6667],
        [ 3.3333,  3.3333,  3.3333,  3.3333],
        [ 5.    ,  5.    ,  5.    ,  5.    ]],
       [[ 0.    ,  1.6667,  3.3333,  5.    ],
        [ 0.    ,  1.6667,  3.3333,  5.    ],
        [ 0.    ,  1.6667,  3.3333,  5.    ],
        [ 0.    ,  1.6667,  3.3333,  5.    ]]])
Having meshed arrays like this is sometimes very useful. However, it is not always needed just to evaluate some N-dimensional function over a grid due to the array-broadcasting rules of Numpy and SciPy. If this is the only purpose for generating a meshgrid, you should instead use the function ogrid which generates an “open” grid using newaxis judiciously to create N, N-d arrays where only one dimension in each array has length greater than 1. This will save memory and create the same result if the only purpose for the meshgrid is to generate sample points for evaluation of an N-d function.

Shape manipulation

In this category of functions are routines for squeezing out length- one dimensions from N-dimensional arrays, ensuring that an array is at least 1-, 2-, or 3-dimensional, and stacking (concatenating) arrays by rows, columns, and “pages “(in the third dimension). Routines for splitting arrays (roughly the opposite of stacking arrays) are also available.

Polynomials

There are two (interchangeable) ways to deal with 1-d polynomials in SciPy. The first is to use the poly1d class from Numpy. This class accepts coefficients or polynomial roots to initialize a polynomial. The polynomial object can then be manipulated in algebraic expressions, integrated, differentiated, and evaluated. It even prints like a polynomial:
>>>
>>> from numpy import poly1d
>>> p = poly1d([3,4,5])
>>> print(p)
   2
3 x + 4 x + 5
>>> print(p*p)
   4      3      2
9 x + 24 x + 46 x + 40 x + 25
>>> print(p.integ(k=6))
   3     2
1 x + 2 x + 5 x + 6
>>> print(p.deriv())
6 x + 4
>>> p([4, 5])
array([ 69, 100])
The other way to handle polynomials is as an array of coefficients with the first element of the array giving the coefficient of the highest power. There are explicit functions to add, subtract, multiply, divide, integrate, differentiate, and evaluate polynomials represented as sequences of coefficients.

Vectorizing functions (vectorize)

One of the features that NumPy provides is a class vectorize to convert an ordinary Python function which accepts scalars and returns scalars into a “vectorized-function” with the same broadcasting rules as other Numpy functions (i.e. the Universal functions, or ufuncs). For example, suppose you have a Python function named addsubtract defined as:
>>>
>>> def addsubtract(a,b):
...    if a > b:
...        return a - b
...    else:
...        return a + b
which defines a function of two scalar variables and returns a scalar result. The class vectorize can be used to “vectorize “this function so that
>>>
>>> vec_addsubtract = np.vectorize(addsubtract)
returns a function which takes array arguments and returns an array result:
>>>
>>> vec_addsubtract([0,3,6,9],[1,3,5,7])
array([1, 6, 1, 2])
This particular function could have been written in vector form without the use of vectorize. However, functions that employ optimization or integration routines can likely only be vectorized using vectorize.

Type handling

Note the difference between np.iscomplex/np.isreal and np.iscomplexobj/np.isrealobj. The former command is array based and returns byte arrays of ones and zeros providing the result of the element-wise test. The latter command is object based and returns a scalar describing the result of the test on the entire object.
Often it is required to get just the real and/or imaginary part of a complex number. While complex numbers and arrays have attributes that return those values, if one is not sure whether or not the object will be complex-valued, it is better to use the functional forms np.real and np.imag . These functions succeed for anything that can be turned into a Numpy array. Consider also the function np.real_if_close which transforms a complex-valued number with tiny imaginary part into a real number.
Occasionally the need to check whether or not a number is a scalar (Python (long)int, Python float, Python complex, or rank-0 array) occurs in coding. This functionality is provided in the convenient function np.isscalar which returns a 1 or a 0.
Finally, ensuring that objects are a certain Numpy type occurs often enough that it has been given a convenient interface in SciPy through the use of the np.cast dictionary. The dictionary is keyed by the type it is desired to cast to and the dictionary stores functions to perform the casting. Thus, np.cast['f'](d) returns an array of np.float32 from d. This function is also useful as an easy way to get a scalar of a certain type:
>>>
>>> np.cast['f'](np.pi)
array(3.1415927410125732, dtype=float32)

Other useful functions

There are also several other useful functions which should be mentioned. For doing phase processing, the functions angle, and unwrap are useful. Also, the linspace and logspace functions return equally spaced samples in a linear or log scale. Finally, it’s useful to be aware of the indexing capabilities of Numpy. Mention should be made of the function select which extends the functionality of where to include multiple conditions and multiple choices. The calling convention is select(condlist,choicelist,default=0). select is a vectorized form of the multiple if-statement. It allows rapid construction of a function which returns an array of results based on a list of conditions. Each element of the return array is taken from the array in a choicelist corresponding to the first condition in condlist that is true. For example
>>>
>>> x = np.r_[-2:3]
>>> x
array([-2, -1,  0,  1,  2])
>>> np.select([x > 3, x >= 0], [0, x+2])
array([0, 0, 2, 3, 4])
Some additional useful functions can also be found in the module scipy.misc. For example the factorial and comb functions compute n! and n!/k!(nk)! using either exact integer arithmetic (thanks to Python’s Long integer object), or by using floating-point precision and the gamma function. Another function returns a common image used in image processing: lena.
Finally, two functions are provided that are useful for approximating derivatives of functions using discrete-differences. The functioncentral_diff_weights returns weighting coefficients for an equally-spaced N-point approximation to the derivative of order o. These weights must be multiplied by the function corresponding to these points and the results added to obtain the derivative approximation. This function is intended for use when only samples of the function are available. When the function is an object that can be handed to a routine and evaluated, the function derivative can be used to automatically evaluate the object at the correct points to obtain an N-point approximation to the o-th derivative at a given point.

zen consultora

Blogger Widgets

Entrada destacada

Platzy y el payaso Freddy Vega, PLATZI APESTA, PLATZI NO SIRVE, PLATZI ES UNA ESTAFA

  Platzy y los payasos fredy vega y cvander parte 1,  PLATZI ES UNA ESTAFA Hola amigos, este post va a ir creciendo conforme vaya escribiend...