Python анализ данных

Вопросы написания собственного программного кода (на любых языках)

Модератор: Olej

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 12 ноя 2017, 16:07

Olej писал(а):... и другие.
В конечном итоге, все оптимизационные алгоритмы сводятся к вызову:

Код: Выделить всё

minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)
Minimization of scalar function of one or more variables.
 
.. versionadded:: 0.11.0
 
Parameters
----------
fun : callable
    Objective function.
x0 : ndarray
    Initial guess.
args : tuple, optional
    Extra arguments passed to the objective function and its
    derivatives (Jacobian, Hessian).
method : str or callable, optional
    Type of solver.  Should be one of
 
        - 'Nelder-Mead'
        - 'Powell'
        - 'CG'
        - 'BFGS'
        - 'Newton-CG'
        - 'Anneal (deprecated as of scipy version 0.14.0)'
        - 'L-BFGS-B'
        - 'TNC'
        - 'COBYLA'
        - 'SLSQP'
        - 'dogleg'
        - 'trust-ncg'
        - custom - a callable object (added in version 0.14.0)
 
    If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``,
    depending if the problem has constraints or bounds.
jac : bool or callable, optional
    Jacobian (gradient) of objective function. Only for CG, BFGS,
    Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg.
    If `jac` is a Boolean and is True, `fun` is assumed to return the
    gradient along with the objective function. If False, the
    gradient will be estimated numerically.
    `jac` can also be a callable returning the gradient of the
    objective. In this case, it must accept the same arguments as `fun`.
hess, hessp : callable, optional
    Hessian (matrix of second-order derivatives) of objective function or
    Hessian of objective function times an arbitrary vector p.  Only for
    Newton-CG, dogleg, trust-ncg.
    Only one of `hessp` or `hess` needs to be given.  If `hess` is
    provided, then `hessp` will be ignored.  If neither `hess` nor
    `hessp` is provided, then the Hessian product will be approximated
    using finite differences on `jac`. `hessp` must compute the Hessian
    times an arbitrary vector.
bounds : sequence, optional
    Bounds for variables (only for L-BFGS-B, TNC and SLSQP).
    ``(min, max)`` pairs for each element in ``x``, defining
    the bounds on that parameter. Use None for one of ``min`` or
    ``max`` when there is no bound in that direction.
constraints : dict or sequence of dict, optional
    Constraints definition (only for COBYLA and SLSQP).
    Each constraint is defined in a dictionary with fields:
        type : str
            Constraint type: 'eq' for equality, 'ineq' for inequality.
        fun : callable
            The function defining the constraint.
        jac : callable, optional
            The Jacobian of `fun` (only for SLSQP).
        args : sequence, optional
            Extra arguments to be passed to the function and Jacobian.
    Equality constraint means that the constraint function result is to
    be zero whereas inequality means that it is to be non-negative.
    Note that COBYLA only supports inequality constraints.
tol : float, optional
    Tolerance for termination. For detailed control, use solver-specific
    options.
options : dict, optional
    A dictionary of solver options. All methods accept the following
    generic options:
        maxiter : int
            Maximum number of iterations to perform.
        disp : bool
            Set to True to print convergence messages.
    For method-specific options, see :func:`show_options()`.
callback : callable, optional
    Called after each iteration, as ``callback(xk)``, where ``xk`` is the
    current parameter vector.
 
Returns
-------
res : OptimizeResult
    The optimization result represented as a ``OptimizeResult`` object.
    Important attributes are: ``x`` the solution array, ``success`` a
    Boolean flag indicating if the optimizer exited successfully and
    ``message`` which describes the cause of the termination. See
    `OptimizeResult` for a description of other attributes.
 
 
See also
--------
minimize_scalar : Interface to minimization algorithms for scalar
    univariate functions
show_options : Additional options accepted by the solvers
 
Notes
-----
This section describes the available solvers that can be selected by the
'method' parameter. The default method is *BFGS*.
 
**Unconstrained minimization**
 
Method *Nelder-Mead* uses the Simplex algorithm [1]_, [2]_. This
algorithm has been successful in many applications but other algorithms
using the first and/or second derivatives information might be preferred
for their better performances and robustness in general.
 
Method *Powell* is a modification of Powell's method [3]_, [4]_ which
is a conjugate direction method. It performs sequential one-dimensional
minimizations along each vector of the directions set (`direc` field in
`options` and `info`), which is updated at each iteration of the main
minimization loop. The function need not be differentiable, and no
derivatives are taken.
 
Method *CG* uses a nonlinear conjugate gradient algorithm by Polak and
Ribiere, a variant of the Fletcher-Reeves method described in [5]_ pp.
120-122. Only the first derivatives are used.
 
Method *BFGS* uses the quasi-Newton method of Broyden, Fletcher,
Goldfarb, and Shanno (BFGS) [5]_ pp. 136. It uses the first derivatives
only. BFGS has proven good performance even for non-smooth
optimizations. This method also returns an approximation of the Hessian
inverse, stored as `hess_inv` in the OptimizeResult object.
 
Method *Newton-CG* uses a Newton-CG algorithm [5]_ pp. 168 (also known
as the truncated Newton method). It uses a CG method to the compute the
search direction. See also *TNC* method for a box-constrained
minimization with a similar algorithm.
 
Method *Anneal* uses simulated annealing, which is a probabilistic
metaheuristic algorithm for global optimization. It uses no derivative
information from the function being optimized.
 
Method *dogleg* uses the dog-leg trust-region algorithm [5]_
for unconstrained minimization. This algorithm requires the gradient
and Hessian; furthermore the Hessian is required to be positive definite.
 
Method *trust-ncg* uses the Newton conjugate gradient trust-region
algorithm [5]_ for unconstrained minimization. This algorithm requires
the gradient and either the Hessian or a function that computes the
product of the Hessian with a given vector.
 
**Constrained minimization**
 
Method *L-BFGS-B* uses the L-BFGS-B algorithm [6]_, [7]_ for bound
constrained minimization.
 
Method *TNC* uses a truncated Newton algorithm [5]_, [8]_ to minimize a
function with variables subject to bounds. This algorithm uses
gradient information; it is also called Newton Conjugate-Gradient. It
differs from the *Newton-CG* method described above as it wraps a C
implementation and allows each variable to be given upper and lower
bounds.
 
Method *COBYLA* uses the Constrained Optimization BY Linear
Approximation (COBYLA) method [9]_, [10]_, [11]_. The algorithm is
based on linear approximations to the objective function and each
constraint. The method wraps a FORTRAN implementation of the algorithm.
 
Method *SLSQP* uses Sequential Least SQuares Programming to minimize a
function of several variables with any combination of bounds, equality
and inequality constraints. The method wraps the SLSQP Optimization
subroutine originally implemented by Dieter Kraft [12]_. Note that the
wrapper handles infinite values in bounds by converting them into large
floating values.
 
**Custom minimizers**
 
It may be useful to pass a custom minimization method, for example
when using a frontend to this method such as `scipy.optimize.basinhopping`
or a different library.  You can simply pass a callable as the ``method``
parameter.
 
The callable is called as ``method(fun, x0, args, **kwargs, **options)``
where ``kwargs`` corresponds to any other parameters passed to `minimize`
(such as `callback`, `hess`, etc.), except the `options` dict, which has
its contents also passed as `method` parameters pair by pair.  Also, if
`jac` has been passed as a bool type, `jac` and `fun` are mangled so that
`fun` returns just the function values and `jac` is converted to a function
returning the Jacobian.  The method shall return an ``OptimizeResult``
object.
 
The provided `method` callable must be able to accept (and possibly ignore)
arbitrary parameters; the set of parameters accepted by `minimize` may
expand in future versions and then these parameters will be passed to
the method.  You can find an example in the scipy.optimize tutorial.
 
References
----------
.. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function
    Minimization. The Computer Journal 7: 308-13.
.. [2] Wright M H. 1996. Direct search methods: Once scorned, now
    respectable, in Numerical Analysis 1995: Proceedings of the 1995
    Dundee Biennial Conference in Numerical Analysis (Eds. D F
    Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK.
    191-208.
.. [3] Powell, M J D. 1964. An efficient method for finding the minimum of
   a function of several variables without calculating derivatives. The
   Computer Journal 7: 155-162.
.. [4] Press W, S A Teukolsky, W T Vetterling and B P Flannery.
   Numerical Recipes (any edition), Cambridge University Press.
.. [5] Nocedal, J, and S J Wright. 2006. Numerical Optimization.
   Springer New York.
.. [6] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory
   Algorithm for Bound Constrained Optimization. SIAM Journal on
   Scientific and Statistical Computing 16 (5): 1190-1208.
.. [7] Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm
   778: L-BFGS-B, FORTRAN routines for large scale bound constrained
   optimization. ACM Transactions on Mathematical Software 23 (4):
   550-560.
.. [8] Nash, S G. Newton-Type Minimization Via the Lanczos Method.
   1984. SIAM Journal of Numerical Analysis 21: 770-778.
.. [9] Powell, M J D. A direct search optimization method that models
   the objective and constraint functions by linear interpolation.
   1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez
   and J-P Hennart, Kluwer Academic (Dordrecht), 51-67.
.. [10] Powell M J D. Direct search algorithms for optimization
   calculations. 1998. Acta Numerica 7: 287-336.
.. [11] Powell M J D. A view of algorithms for optimization without
   derivatives. 2007.Cambridge University Technical Report DAMTP
   2007/NA03
.. [12] Kraft, D. A software package for sequential quadratic
   programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace
   Center -- Institute for Flight Mechanics, Koln, Germany.

Код: Выделить всё

Examples
--------
Let us consider the problem of minimizing the Rosenbrock function. This
function (and its respective derivatives) is implemented in `rosen`
(resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`.
 
>>> from scipy.optimize import minimize, rosen, rosen_der
 
A simple application of the *Nelder-Mead* method is:
 
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
>>> res = minimize(rosen, x0, method='Nelder-Mead')
>>> res.x
[ 1.  1.  1.  1.  1.]
 
Now using the *BFGS* algorithm, using the first derivative and a few
options:
 
>>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der,
...                options={'gtol': 1e-6, 'disp': True})
Optimization terminated successfully.
         Current function value: 0.000000
         Iterations: 52
         Function evaluations: 64
         Gradient evaluations: 64
>>> res.x
[ 1.  1.  1.  1.  1.]
>>> print res.message
Optimization terminated successfully.
>>> res.hess
[[ 0.00749589  0.01255155  0.02396251  0.04750988  0.09495377]
 [ 0.01255155  0.02510441  0.04794055  0.09502834  0.18996269]
 [ 0.02396251  0.04794055  0.09631614  0.19092151  0.38165151]
 [ 0.04750988  0.09502834  0.19092151  0.38341252  0.7664427 ]
 [ 0.09495377  0.18996269  0.38165151  0.7664427   1.53713523]]
 
 
Next, consider a minimization problem with several constraints (namely
Example 16.4 from [5]_). The objective function is:
 
>>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2
 
There are three constraints defined as:
 
>>> cons = ({'type': 'ineq', 'fun': lambda x:  x[0] - 2 * x[1] + 2},
...         {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
...         {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})
 
And variables must be positive, hence the following bounds:
 
>>> bnds = ((0, None), (0, None))
 
The optimization problem is solved using the SLSQP method as:
 
>>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds,
...                constraints=cons)
 
It should converge to the theoretical solution (1.4 ,1.7).

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 12 ноя 2017, 16:37

Olej писал(а): В конечном итоге, все оптимизационные алгоритмы сводятся к вызову:

Код: Выделить всё

minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)
Minimization of scalar function of one or more variables.
... 
 
Returns
-------
res : OptimizeResult
    The optimization result represented as a ``OptimizeResult`` object.
    Important attributes are: ``x`` the solution array, ``success`` a
    Boolean flag indicating if the optimizer exited successfully and
    ``message`` which describes the cause of the termination. See
    `OptimizeResult` for a description of other attributes.
...
И, наконец, возвращаемое значение - объект класса:

Код: Выделить всё

class OptimizeResult(__builtin__.dict)
   	Represents the optimization result.
 
Attributes
----------
x : ndarray
    The solution of the optimization.
success : bool
    Whether or not the optimizer exited successfully.
status : int
    Termination status of the optimizer. Its value depends on the
    underlying solver. Refer to `message` for details.
message : str
    Description of the cause of the termination.
fun, jac, hess, hess_inv : ndarray
    Values of objective function, Jacobian, Hessian or its inverse (if
    available). The Hessians may be approximations, see the documentation
    of the function in question.
nfev, njev, nhev : int
    Number of evaluations of the objective functions and of its
    Jacobian and Hessian.
nit : int
    Number of iterations performed by the optimizer.
maxcv : float
    The maximum constraint violation.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 12 ноя 2017, 16:51

Olej писал(а): И, наконец, возвращаемое значение - объект класса:
Теперь, связывая всё это вместе, проверяем как это работает на простейшем примере (из экзамплов в документации):

Код: Выделить всё

[olej@dell ~]$ python
Python 2.7.11 (default, Sep 29 2016, 13:33:00) 
[GCC 5.3.1 20160406 (Red Hat 5.3.1-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from scipy.optimize import minimize, rosen, rosen_der
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
>>> print( rosen )
<function rosen at 0x7f0dc53fc050>
>>> res = minimize(rosen, x0, method='Nelder-Mead')
>>> res.x
array([ 0.99910115,  0.99820923,  0.99646346,  0.99297555,  0.98600385])
>>> res.fun
6.6174817088845322e-05
>>> res.nfev
243
>>> res.nit
141
>>> rosen
<function rosen at 0x7f0dc53fc050>
>>> 

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 12 ноя 2017, 19:03

Olej писал(а): Теперь, связывая всё это вместе, проверяем как это работает на простейшем примере (из экзамплов в документации):
А теперь пишем собственный код, разыскивающий минимум достаточно непростой функции:
Olej писал(а): f( x1, x2 ) = sin( pi / 2 * x1 ^ 2 ) * sin( pi / 2 * x2 ^ 2 )
- которая на интервалах x1=[0...2] и x2=[0...2] имеет 4 максимума.
На самом деле, я хотел сказать: имеет 4 экстремума ... см. картинку.
sin2.jpg
sin2.jpg (17.35 КБ) 2711 просмотров
Код:

Код: Выделить всё

# -*- coding: utf-8 -*-
from math import pi, sin
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

sin2 = lambda x: sin( pi / 2 * x[ 0 ] ** 2 ) * sin( pi / 2 * x[ 1 ] ** 2 );

X = [ ( 1, 1 ), ( 1, 1.7 ), ( 1.7, 1 ), ( 1.7, 1.7 ) ]
print( X )
Y = [ sin2( x ) for x in X ]
print( Y )
res = minimize( sin2, ( 1.4, 1.4 ), method='Nelder-Mead' )
print(  res.x )
print( res.fun )
print( '{} -> {}'.format( res.nit, res.nfev ) )
Выполнение:

Код: Выделить всё

[olej@dell 12.analis]$ python min.py
[(1, 1), (1, 1.7), (1.7, 1), (1.7, 1.7)]
[1.0, -0.9851093261547738, -0.9851093261547738, 0.9704403844771124]
[ 1.73201465  1.00003747]
-0.999999973722
36 -> 71
И читается это так:
- метод Нелдера-Мида (деформируемого симплекса) находит минимум функции при значениях 2-х аргументов x1= 1.73201465 и X2=1.00003747 (что мы видим и на картинке) ...
- значение функции в минимуме найдено как -0.999999973722 ...
- при этом алгоритм симплекса делал 36 циклов итераций ...
- которые потребовали 71 вычислений значений функции в вершинах симплекса.

Этот простейший пример очень важен в моих дальнейших целях.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 13 ноя 2017, 01:05

Olej писал(а):Этот простейший пример очень важен в моих дальнейших целях.
Объясняю почему эта техника очень важна:
- в любом физическом эксперименте, измерениях параметров среды ... т.е. фактически в любом реальном измерительном эксперименте, мы можем предполагать или знать характер наблюдаемых зависимостей в виде функции N переменных Y=F(X1, X2, X3, ... Xn) ...
- и в эту формулу, описывающую зависимости, входит M параметров - констант среды эксперимента, которые и есть искомые параметры всего эксперимента Y=F( ... A1, A2, ... Am)
- но при нелинейном характере функции F() восстановление A1, A2, ... Am по наборам {Xi} и откликам на них {Yi} становится невозможным.

Вот тут и приходит на помощь численная оптимизация.
1. формируем новую функцию Delta() - суммы среднеквадратичных отклонений набора предсказываемых {Yi}=F({Xi}) от наблюдаемых, измеряемых {Yi} ...
2. ... как функцию от вектора искомых параметров {A}
3. и просто минимизируем Delta() как функцию от M параметров {A}

Это в точности то, что мы имеем при классической линейной, квадратичной ... или любой другой регрессии. Но там мы предварительно решаем задачу аналитически и только просчитываем результат. Но в случае более сложной зависимости Y=F() аналитическое решение невозможно. Но мы можем "проломить" минимизацию расхождений численными методами "в лоб".

Непонятно?
Чуть позже я нарисую это на примерах.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 13 ноя 2017, 12:35

Olej писал(а): Вот моя исходная таблица и её регрессионная обработка:
Вот всё та же таблица данных (2 переменных), которая плохо аппроксимируется линейной регрессией (плоскостью).
(Это реальные данные из некоторой ведомственной производственной методички, таблица, которой пользуются в таком виде >40 лет ... но природа её не так важна)
Теперь её же представим нелинейным приближением, используя оптимизацию многомерных функций ("из пушки по воробьям").
В ведомстве, использующем эти табличные данные, они же предлагают аппроксимирующую нелинейную формулу для данных (как они её получали и какая её природа - это тайна великая есть ... лет 30-40 назад):

Код: Выделить всё

H1 = 0.2246 * X1 ^ 0.0899 * X3 ^ 0.2949
Фокус в том, что эта аппроксимация даёт тоже весьма плохое приближение - на краях таблицы расхождение данных до 30% :cry:
Это среднеквадратичное расхождение и будет диагностироваться в начале выполнения будущей программы - это весьма много:

Код: Выделить всё

начальное расхождение = 2.08910527622
Но именно их закономерность (показательную форму) возьмём за основу, а их численные значения - за начальную точку оптимизации отклонения.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 13 ноя 2017, 12:39

Olej писал(а): Но именно их закономерность (показательную форму) возьмём за основу, а их численные значения - за начальную точку оптимизации отклонения.
Вот код (весь код то теперь умещается в 10 строк):

Код: Выделить всё

# -*- coding: utf-8 -*-
import math
import sys
from scipy.optimize import minimize

X13 = [ (   75,  50 ), (   75,  150 ), (   75,  300 ), (   75,  500 ),
        (  175,  50 ), (  175,  150 ), (  175,  300 ), (  175,  500 ), (  175,  700 ),
                (  325,  150 ), (  325,  300 ), (  325,  500 ), (  325,  700 ), (  325,  900 ),
                (  325, 1100 ), (  325, 1300 ), (  325, 1500 ), (  325, 1700 ), (  325, 1900 ),
                        (  475,  500 ), (  475,  700 ), (  475,  900 ), (  475, 1100 ), (  475, 1300 ),
                        (  475, 1500 ), (  475, 1700 ), (  475, 1900 ), (  475, 2100 ), (  475, 2350 ),
                        (  625,  500 ), (  625,  700 ), (  625,  900 ), (  625, 1100 ), (  625, 1300 ),
                        (  625, 1500 ), (  625, 1700 ), (  625, 1900 ), (  625, 2100 ), (  625, 2350 ),
                        (  625, 2750 ),
                                (  850, 1100 ), (  850, 1300 ), (  850, 1500 ), (  850, 1700 ), (  850, 1900 ),
                                (  850, 2100 ), (  850, 2350 ), (  850, 2750 ), (  850, 3250 ), (  850, 3750 ),
                                        ( 1150, 1500 ), ( 1150, 1700 ), ( 1150, 1900 ), ( 1150, 2100 ), ( 1150, 2350 ),
                                        ( 1150, 2750 ), ( 1150, 3250 ), ( 1150, 3750 ), ( 1150, 4250 ),
                                                ( 1450, 1700 ), ( 1450, 1900 ), ( 1450, 2100 ), ( 1450, 2350 ), ( 1450, 2750 ),
                                                ( 1450, 3250 ), ( 1450, 3750 ), ( 1450, 4250 ), ( 1450, 4750 ), ( 1450, 5250 ),
                                                        ( 1750, 2100 ), ( 1750, 2350 ), ( 1750, 2750 ), ( 1750, 3250 ), ( 1750, 3750 ),
                                                        ( 1750, 4250 ), ( 1750, 4750 ), ( 1750, 5250 ),
                                                                ( 2050, 2350 ), ( 2050, 2750 ), ( 2050, 3250 ), ( 2050, 3750 ), ( 2050, 4250 ), 
                                                                ( 2050, 4750 ), ( 2050, 5250 ),
                                                                        ( 2400, 2350 ),( 2400, 2750 ),( 2400, 3250 ),( 2400, 3750 ),( 2400, 4250 ),  
                                                                        ( 2400, 4750 ),( 2400, 5250 ), 
                                                                                ( 2900, 2350 ), ( 2900, 2750), ( 2900, 3250 ), ( 2900, 3750 ), ( 2900, 4250 ), 
                                                                                ( 2900, 4750 ), ( 2900, 5250 ),
                                                                                        ( 3500, 2750 ), ( 3500, 3250 ), ( 3500, 3750 ), ( 3500, 4250 ), ( 3500, 4750 ), 
                                                                                        ( 3500, 5250 ),  
     ]

H1 = [  1.3, 1.6, 2.0, 2.2,             
        1.4, 1.7, 2.1, 2.4, 2.6,
             1.8, 2.3, 2.5, 2.7, 2.9, 3.1, 3.2, 3.4, 3.5, 3.6,
                       2.6, 2.8, 3.0, 3.2, 3.3, 3.5, 3.6, 3.7, 3.8, 4.0,
                       2.7, 2.9, 3.1, 3.3, 3.4, 3.6, 3.7, 3.8, 3.9, 4.1, 4.3,
                                      3.4, 3.5, 3.7, 3.8, 3.9, 4.0, 4.3, 4.4, 4.6, 4.8,
                                                3.8, 3.9, 4.0, 4.1, 4.4, 4.5, 4.8, 4.9, 5.1, 
                                                     4.0, 4.1, 4.2, 4.4, 4.6, 4.8, 5.0, 5.2, 5.4, 5.5,
                                                               4.3, 4.5, 4.7, 4.9, 5.1, 5.3, 5.5, 5.6,
                                                                    4.6, 4.8, 5.0, 5.2, 5.4, 5.6, 5.7,
                                                                    4.6, 4.8, 5.1, 5.3, 5.4, 5.6, 5.8,
                                                                    4.7, 4.9, 5.2, 5.4, 5.5, 5.7, 5.9,
                                                                         5.0, 5.2, 5.4, 5.6, 5.8, 6.0,
     ]

#H1 = A[ 0 ] * X1 ^ A[ 1 ] * X3 ^ A[ 2 ] + A[ 3 ]

def Delt( A ) :
   global PX
   F = lambda A, x: A[ 0 ] * ( x[ 0 ] ** A[ 1 ] ) * ( x[ 1 ] ** A[ 2 ] ) + A[ 3 ];
   PX = [ F( A, x ) for x in X13 ]
   sum = 0.0
   for i in range( 0, len( H1 ) ) :
      sum += ( PX[ i ] - H1[ i ] ) ** 2   
   return sum

debug = len( sys.argv ) > 1
A = [ 0.2246, 0.0899, 0.2949, 0 ]    # начальная точка 
print( 'размерность данных = {}/{}'.format( len( X13 ), len( H1 ) ) )
print( 'начальные параметры {}'.format( A ) )
if debug :
   print( 'исходные значения H1:\n{}'.format(  H1 ) )
print( 'начальное расхождение = ' + str( Delt( A ) ) )

if debug :
   print( 'восстановленные значения H1:\n{}'.format( PX ) )

res = minimize( Delt, A, method='Nelder-Mead' )
print( 'оптимизированные параметры {}'.format( res.x ) )
print( 'H1 = {} * X1 ^ {} * X3 ^ {} + {}'.format( res.x[ 0 ], res.x[ 1 ], res.x[ 2 ], res.x[ 3 ] ) )
print( 'оптимизированное расхождение = {}'.format( res.fun ) )
print( 'итераций {} -> вычислений функции {}'.format( res.nit, res.nfev ) ) 
if debug :
   print( 'оптимизироанные значения H1:\n{}'.format( PX ) )
Вот результат выполнения (краткий итог, без отладочной диагностики):

Код: Выделить всё

$ python H1m.py 
размерность данных = 104/104
начальные параметры [0.2246, 0.0899, 0.2949, 0]
начальное расхождение = 2.08910527622
оптимизированные параметры [ 0.2621557   0.09303522  0.27634978 -0.0004099 ]
H1 = 0.262155704281 * X1 ^ 0.0930352239592 * X3 ^ 0.276349778648 + -0.000409904556093
оптимизированное расхождение = 0.220044229688
итераций 84 -> вычислений функции 153
Вложения
H1m.py
(5.18 КБ) 80 скачиваний

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 13 ноя 2017, 12:43

Olej писал(а): Вот результат выполнения (краткий итог, без отладочной диагностики):
А вот результат с детализацией того, какая была итоговая таблица результатов и какая она стала:

Код: Выделить всё

$ python H1m.py D
размерность данных = 104/104
исходные значения H1:
[1.3, 1.6, 2.0, 2.2, 1.4, 1.7, 2.1, 2.4, 2.6, 1.8, 2.3, 2.5, 2.7, 2.9, 3.1, 3.2, 3.4, 3.5, 3.6, 2.6, 2.8, 3.0, 3.2, 3.3, 3.5, 3.6, 3.7, 3.8, 4.0, 2.7, 2.9, 3.1, 3.3, 3.4, 3.6, 3.7, 3.8, 3.9, 4.1, 4.3, 3.4, 3.5, 3.7, 3.8, 3.9, 4.0, 4.3, 4.4, 4.6, 4.8, 3.8, 3.9, 4.0, 4.1, 4.4, 4.5, 4.8, 4.9, 5.1, 4.0, 4.1, 4.2, 4.4, 4.6, 4.8, 5.0, 5.2, 5.4, 5.5, 4.3, 4.5, 4.7, 4.9, 5.1, 5.3, 5.5, 5.6, 4.6, 4.8, 5.0, 5.2, 5.4, 5.6, 5.7, 4.6, 4.8, 5.1, 5.3, 5.4, 5.6, 5.8, 4.7, 4.9, 5.2, 5.4, 5.5, 5.7, 5.9, 5.0, 5.2, 5.4, 5.6, 5.8, 6.0]
начальное расхождение = 2.08910527622
восстановленные значения H1:
[1.0495521286490923, 1.4511325100005878, 1.780249274771047, 2.069683864093468, 1.1326223486623102, 1.5659871166309796, 1.9211528991807751, 2.233495731322346, 2.466483897484063, 1.6556074743061737, 2.0310991485111836, 2.361317144526409, 2.6076390620094156, 2.808239748160736, 2.979440856930643, 3.129896386272905, 3.264805988488138, 3.387563563706976, 3.5005195138808003, 2.4432660575628646, 2.6981365147630285, 2.9056989968859632, 3.0828415967456424, 3.238518647101506, 3.3781102528694373, 3.5051280986239353, 3.6220041564204064, 3.7304994255329387, 3.856314274884917, 2.5042957689639143, 2.7655325694443897, 2.9782797011647095, 3.1598471002445985, 3.3194127674072873, 3.4624911958188904, 3.5926817875153154, 3.712477262153408, 3.8236826065530014, 3.9526401525106767, 4.14017383985719, 3.2484128231195832, 3.4124508739799517, 3.5595395737869997, 3.69337921035785, 3.8165323705015655, 3.9308546320815974, 4.063426662511335, 4.2562166347527635, 4.4711466694562425, 4.663868901817614, 3.657596558407778, 3.7951231637319824, 3.9216689052137848, 4.039140477544038, 4.175364557144608, 4.37346544192156, 4.594316296065471, 4.792347574887207, 4.972541120835541, 3.8750393966693712, 4.004249889337681, 4.124195132516769, 4.263287765997508, 4.465560182440212, 4.6910616282889865, 4.893262973041242, 5.077250964853532, 5.246548365838214, 5.403706020076272, 4.194511046928294, 4.335975155423391, 4.541696237476085, 4.77104239480346, 4.976691193421173, 5.16381610855288, 5.335999964027524, 5.495837094820266, 4.398092271972862, 4.606760511232988, 4.8393922782500445, 5.047987198543758, 5.2377928624680425, 5.412443421333521, 5.574570376520199, 4.460860632907593, 4.672506927776275, 4.908458751266466, 5.120030680780652, 5.31254519883621, 5.489688322349815, 5.654129108764013, 4.537401857715176, 4.7526796640719615, 4.992680042998361, 5.207882208010258, 5.4036999669015655, 5.58388258273644, 5.751144909708891, 4.833710994003321, 5.077803285548081, 5.2966745633274215, 5.495830938441298, 5.679085597423112, 5.849199681669349]
параметры [ 0.2621557   0.09303522  0.27634978 -0.0004099 ]
H1 = 0.262155704281 * X1 ^ 0.0930352239592 * X3 ^ 0.276349778648 + -0.000409904556093
оптимизированное расхождение = 0.220044229688
итераций 84 -> вычислений функции 153
оптимизироанные значения H1:
[1.1545000570702368, 1.5642153694152541, 1.8945766937243846, 2.1819108816023141, 1.2491806552038933, 1.6924848276221536, 2.0499294948317965, 2.3608196190882116, 2.5909258221219003, 1.7927992191760593, 2.1714246811149387, 2.5007369571315867, 2.7444783677917521, 2.9419038624614426, 3.1096927376024084, 3.2566488066345269, 3.3880428609277073, 3.5073050243406545, 3.616804739147323, 2.5905789810874151, 2.8430756658783745, 3.047592751269391, 3.2214086597075626, 3.3736434405764397, 3.5097572138594191, 3.633303314627466, 3.7467362963245638, 3.8518295454204678, 3.9734593892374033, 2.6575545300005636, 2.9165781079421413, 3.1263818416110478, 3.304690790673467, 3.4608607525106074, 3.6004929880469865, 3.7272326840083969, 3.8435978426245931, 3.9514076913790954, 4.0761815962563839, 4.257177592311236, 3.4005617108277644, 3.5612616890804976, 3.7049442318058183, 3.83536026152859, 3.9551008200778677, 4.0660379052027658, 4.1944311222107773, 4.3806772625548369, 4.5876888807851106, 4.7727788602885957, 3.81058061076053, 3.9447146870321381, 4.0678689438163351, 4.1819687478751204, 4.3140223428167754, 4.5055781971646454, 4.7184915349486127, 4.908858267325038, 5.0816480367495167, 4.0306795936264779, 4.1565174020690083, 4.2731034597611863, 4.4080345244139822, 4.6037644125632129, 4.821317167250915, 5.0158320222639405, 5.1923869093903159, 5.3544895346891863, 5.5046741752122177, 4.3484947639961335, 4.4858062190614278, 4.6849890818862008, 4.9063798000021457, 5.1043261946473022, 5.2839957800952009, 5.4489581437063368, 5.6017922710567749, 4.5523038721452549, 4.7544391550390799, 4.9791114727364238, 5.1799919597018684, 5.362324726521658, 5.5297322713399355, 5.6848318071618982, 4.6195315362518583, 4.8246516508728083, 5.0526415935412547, 5.2564883832830906, 5.4415135678713495, 5.6113931370882382, 5.7687829510286761, 4.7015545642288536, 4.9103164078837356, 5.142354113469997, 5.3498200254712396, 5.5381301711076585, 5.7110258041593029, 5.8712099372045801, 4.9969491234003192, 5.2330803291093053, 5.4442062572018681, 5.6358384819043845, 5.8117842584373536, 5.9747942846564284]
И это вполне прилично!
Теперь все отклонения данных не превышают 10%.
Но и это связано не с ограничениями метода, а ... с приблизительностью составления таблицы, которая составлялась ещё в годы зарождения машинных вычислений и в эпоху ЭВМ ЕС-1020 :lol:
Тогда о многомерной оптимизации думать было ещё смешно ... даже не в силу машинных мощностей, а потому что (именно из-за ограниченности этих мощностей) сами алгоритмы многомерной оптимизации были обстоятельно проработаны только к середине 90-х годов (см. перечень источников в документации пакета, цитируемой выше) - не существовало адекватного программного обеспечения.

Если за исходные данные взять достаточно точно вычисленные числа, или достаточно тщательно проведенные реальные измерения, то сходимость методами многомерной оптимизации может быть приведена практически до нуля! Или до теоретически достижмой, в принципе, степени приближения для данного набора данных и в данной форме записи модели.

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 13 ноя 2017, 13:05

Olej писал(а): Вот результат выполнения (краткий итог, без отладочной диагностики):

Код: Выделить всё

$ python H1m.py 
размерность данных = 104/104
начальные параметры [0.2246, 0.0899, 0.2949, 0]
начальное расхождение = 2.08910527622
оптимизированные параметры [ 0.2621557   0.09303522  0.27634978 -0.0004099 ]
H1 = 0.262155704281 * X1 ^ 0.0930352239592 * X3 ^ 0.276349778648 + -0.000409904556093
оптимизированное расхождение = 0.220044229688
итераций 84 -> вычислений функции 153
Ещё раз остановлюсь на полученных данных...

1. Вместо старой (и неважной :cry: ) формулы приближения H1 = 0.2246 * X1 ^ 0.0899 * X3 ^ 0.2949 мы нашли оптимизированные коэффициенты такого приближения H1 = 0.262155704281 * X1 ^ 0.0930352239592 * X3 ^ 0.276349778648 + -0.000409904556093. Лучше приблизить эти данные формулой такого вида - невозможно.

2. Среднеквадратичная невязка, расхождение с исходными данными, улучшилась в 2.08910527622 / 0.220044229688 = 9.5 раз! ... на порядок. И то, достижимый результат, в принципе, ограничивается только "чистотой" данных.

3. Оптимизация параметров потребовала 84 итераций (перестроения деформируемого многомерного симплекса), для чего оптимизируемая функция вызывалась на вычисление 153 раза. И это для простейшей задачи!

Это и есть то, почему я назвал "из пушки по воробьям". Но в эпоху развитых и дешёвых машинных вычислений - это нормально и запросто. Это напоминает методы конечных элементов в теории динамики и прочности ... вместо приближённых методов сопромата, потребовавших 300 лет на своё развитие и представляющих ночной кошмар для студентов механических специальностей.
Логика та же: вместо спецфункций Бесселя и Якоби, моментов инерции ... и прочих приближений аналитических решений - тысячи миллиардов точных численных вычислений "в лоб".

Аватара пользователя
Olej
Писатель
Сообщения: 21338
Зарегистрирован: 24 сен 2011, 14:22
Откуда: Харьков
Контактная информация:

Re: Python анализ данных

Непрочитанное сообщение Olej » 28 дек 2017, 20:26

Задали такой вопрос: где описаны методы многомерной нелинейной оптимизации.
Одна из самых старых книг, очень обстоятельных ... по которой я сам изучал эти техники - это вот:
Изображение
Д. ХИММЕЛЬБЛАУ. ПРИКЛАДНОЕ НЕЛИНЕЙНОЕ ПРОГРАММИРОВАНИЕ
М.: "Мир", 1975
Ставшая классической в среде специалистов по автоматическому управлению книга Химмельблау раскрывает многие секреты методов оптимального управления системами с нелинейными целевыми функциями. Сильной стороной книги является описание методов нелинейного программирования как при отсутствии ограничений на управляющие переменные, так и при их наличии. Уделено место и вопросам точности решений и времени оптимизации. Анализ наиболее популярных методов нелинейного программирования дополняется программами решения на языке ФОРТРАН. В каждой главе присутствует качественно разработанные примеры, не только дополняющие теорию, но и иллюстрирующие важные вычислительные процедуры.
Есть ряд новых изданий русскоязычных авторов:

1. Mexalib - скачать книги бесплатно (ссылки с кирилицей форум не отображает ... но просто скопируйте адрес).
Здесь вы можете скачать 4 учебных курса разных университетов по оптимизации.

2.
Изображение
Название: Методы оптимизации
Автор: Васильев Ф.П.
Издательство: Факториал Пресс
Год издания: 2002
Число страниц: 824
Формат: PDF
Размер: 65.6 Mb
Качество: Хорошее
Язык: Русский
3.
Изображение
Методы оптимизации, Габасов Р., 2011.

Ответить

Вернуться в «Программирование»

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 9 гостей