├── .gitignore ├── LICENSE ├── README.md ├── conj_method.py ├── constrained_optimized.py ├── line_program ├── sample_by_cvxopt.py ├── simplex.py ├── simplex_alg.py └── simplex_orginal.py ├── line_search.py ├── newton_method.py ├── optimal_grandient.py ├── sample ├── sample_by_cvxopt.py └── sample_by_scipy.py └── uncostrained_optimize.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### optimize 2 | > 用python写了一些最优化相关的算法。包括线性规划、线搜索、无约束优化、约束优化等. 主要是为了加深对算法的理解,细节没考虑 3 | 4 | #### 1. 线性规划(line program) 5 | > 采用单纯形法解线性规划。在写的时候,部分实现有些小差异,这儿也保留下来了 6 | 7 | > 相比非线性约束的优化问题,线性规划研究得比较透,这也是单独放到一个目录下的原因 8 | 9 | > [line_program](line_program) 10 | 11 | #### 2. 线搜索法(line search) 12 | > 实现了二等分、四等分、fibonacci搜索、黄金分割等精确搜索法 13 | > 14 | > 实现了二次多项式拟合等非精确搜索 15 | > 16 | > [line_search](line_search) 17 | 18 | #### 3. 牛顿法、拟牛顿法(newton_method) 19 | > 实现了几个无约束优化的算法。包括 newton_method, DFP, bfgs, l-bfgs(没有实现) 20 | > 正定二次型直接求解也丢到这里了(solve_direct) 21 | 22 | > [newton_method.py](newton_method.py) 23 | 24 | #### 4. 最优梯度法(optimal_grandient) 25 | > 实现了最优梯度, 二次多项式直接求解等 26 | 27 | > [optimal_grandient.py](optimal_grandient.py) 28 | 29 | #### 5. 共轭方向、共轭梯度法(newton_method) 30 | > 包括 共轭方向法(Fletcher_Reeves_conj, powell_conj, 已知共轭方向的二次多项式直接求解) 31 | 32 | > [conj_method.py](conj_method.py) 33 | 34 | #### 6. 约束优化(constrained optimized) 35 | > 实现了几个约束优化的算法。 36 | 37 | > 包括几个原理性的程序,如 lagrange 等式、不等式优化, kkt 条件(不等式) 38 | 39 | > 基于梯度的算法:hemstitching, combined_direction, 可行方向法 40 | 41 | > 罚函数法(外点法) 42 | 43 | > 内点法(未实现) 44 | 45 | > [costrained_optimize.py](costrained_optimize.py) 46 | 47 | #### 7. 外部库写的小例子 48 | > 调用cvxopt,scipy实现的线性规划示例和非线性优化示例 49 | 50 | > [sample](sample) 51 | 52 | #### 8. 待补充内容 53 | > 1. 线性搜索wolf条件 54 | > 2. lagrange对偶问题 55 | > 3. 共轭梯度&共轭方向的区别? 56 | > 4. 在线梯度下降法 57 | > 5. 随机算法:模拟退火、遗传算法 58 | -------------------------------------------------------------------------------- /conj_method.py: -------------------------------------------------------------------------------- 1 | #encoding: utf8 2 | 3 | import numpy as np 4 | import pdb 5 | 6 | ''' 7 | 1. 共轭方向下降法 8 | 共轭方向法,开始用来求解 Ax=b方程组. 而在求解二次函数最优解时,其梯度函数为 Ax+b=0的解, 9 | 于是也用这个方法来求解二次函数的最优解。其它非二次的凸函数,则可以用二次函数来近似 10 | 11 | (x, Ay) = 0, 称x,y为共轭向量 (正交是共轭的特殊形式,A为单位阵) 12 | 3.1 找到n个共轭向量 ui 13 | 3.2 沿共轭向量方向进行最优搜索, 得到每次搜索的最优步长列表 lbi 14 | 3.3 得到最优点: 15 | x_star = x0 + sum(lbi * ui) 16 | 17 | 对非二次函数,可以这样逼近最优解 18 | 19 | 2. 共轭梯度法 20 | 使用梯度函数构造共轭方向 21 | ''' 22 | 23 | from newton_method import f_value 24 | from newton_method import solve_direct 25 | 26 | ''' 27 | f = 1 + x1 -x2 + x1**2 + 2x2**2 28 | u1 = [1,0] 29 | u2 = [0,1] 30 | x0 = [0,0] 31 | 32 | lambda1 = -1/2, lambda2 = 1/4 33 | ''' 34 | def f2(): 35 | c = 1. 36 | b = np.matrix('1.; -1.') 37 | A = np.matrix('2, 0; 0,4') 38 | 39 | return c, b, A 40 | 41 | from line_search import golden_section_search 42 | 43 | ''' 44 | 共轭方向法: 45 | 沿共轭方向,最多n次搜索,可以找到最优值 46 | 1. 使用黄金搜索找lambda 47 | ''' 48 | def conj_grandient_method_for_f2(): 49 | u1 = np.matrix('1.;0.') 50 | u2 = np.matrix('0.;1.') 51 | x0 = np.matrix('0.;0.') 52 | 53 | def_field = [-1,1] 54 | esplison = 0.005 55 | c,b, A = f2() 56 | 57 | ''' 58 | 线性搜索用的一次函数, 参数为k 59 | f = f(xi + kui) 60 | ''' 61 | k1 = golden_section_search(lambda k:f_value(f2, x0 + k*u1), def_field, esplison) 62 | x1 = x0 + k1[0] * x0 63 | 64 | k2 = golden_section_search(lambda k:f_value(f2, x1 + k*u2), def_field, esplison) 65 | x2 = x0 + k1[0] * u1 + k2[0] * u2 66 | 67 | return x2, f_value(f2, x2) 68 | 69 | ''' 70 | 共轭方向法: 71 | 2. 对二次函数直接求解lambda 72 | lamb_i+1 = (u(i+1), Ax0 + b) / (u(i+1), Au(u+1)) 73 | ''' 74 | def conj_grandient_method_for_f2_direct(): 75 | u1 = np.matrix('1.;0.') 76 | u2 = np.matrix('0.;1.') 77 | x0 = np.matrix('0.;0.') 78 | 79 | c,b, A = f2() 80 | lamb1 = -1. * (u1.T * (A*x0 + b))/(u1.T * (A*u1)) 81 | lamb2 = -1. * (u2.T * (A*x0 + b))/(u2.T * (A*u2)) 82 | 83 | x2 = x0 + lamb1[0,0] * u1 + lamb2[0,0] * u2 84 | 85 | return x2, f_value(f2, x2) 86 | 87 | 88 | def conj_f3(): 89 | A = np.matrix('1,1;1,2') 90 | c = 0 91 | b = np.matrix('0;0') 92 | 93 | return c,b,A 94 | 95 | ''' 96 | Fletcher_Reeves_conj 97 | 关于v0,v1,...vn共轭,最好推导一次 98 | x0, x1, ... 99 | v0, v1,.... 100 | xi = xi_1 + lambda * vi_1 101 | vi = -gi + ||gi||/||gi_1|| * vi_1 102 | 沿共轭方向求极小值: 103 | gi, 第xi点的梯度值 104 | 105 | example: 106 | 107 | f=1/2x.TAx 108 | A=[1,1;1,2] 109 | x0 = [10.;-5.] 110 | v0 = g0 111 | 112 | lamb0 = 0.75 113 | x1 = [1.25,-3.75] 114 | v1=[-4.36,3.75] 115 | lamb1 = 1.34 116 | 117 | x2 = [0.4, 0.01] 118 | 再迭代一次? 119 | 讲义上似乎算错了。有空算一下 120 | ''' 121 | def Fletcher_Reeves_conj(): 122 | f = conj_f3 123 | c,b,A = f() 124 | x0 = np.matrix('10.;-5.') 125 | g0 = A * x0 + b 126 | v0 = -g0 127 | 128 | #pdb.set_trace() 129 | lamb0, f_x0 = golden_section_search(lambda k:f_value(f, x0 + k*v0), [0,2], 0.001) 130 | 131 | x1 = x0 + lamb0 * v0 132 | g1 = A*x1 + b 133 | v1 = -g1 + np.dot(g1.T, g1)[0,0]/np.dot(g0.T, g0)[0,0] * v0 134 | lamb1, f_x1 = golden_section_search(lambda k:f_value(f, x1 + k*v1), [0,2], 0.001) 135 | x2 = x1 + lamb1 * v1 136 | return x2, f_x1 137 | 138 | ''' 139 | ''' 140 | def f_powell(): 141 | c = 0 142 | b = np.matrix('0.;0.') 143 | A = np.matrix('2,0;0,4') 144 | 145 | return c,b,A 146 | 147 | ''' 148 | 相比于fletcher算法,powell算不需要计算梯度。但需要有n个线性无关的初始向量, 149 | 150 | 1. 每一步的过程 151 | xi = xi_1 + lambda * vi_1, lambda线性搜索后的最小值 152 | vi --> vi_1 153 | xn-x0 --> vn 154 | u0 = xn-x0 155 | x0 = xn + lambda * (xn - x0), 为新的x0值 156 | 157 | 算法本身所需要的步数,并不比fletcher小 158 | 159 | 2. 重复上述步骤,直到收敛 160 | 留意下收敛条件:如 ||xi - xi_1|| < epsilon, |fi - fi_1| < esplilon, max_steps 161 | 162 | 163 | 这种产生共轭向量的方法,并没有推导,只有实现。最好去推一下 164 | 165 | 166 | 这两个算法,和DFP/BFGS关系密切。具体参考 newton算法相关内容 167 | 168 | ''' 169 | def powell_conj(): 170 | ''' 171 | u1=[-11.14, -24.46] 172 | u2=[-1.8, -0.28] 173 | ''' 174 | x0 = np.matrix('20.;20.') 175 | #v1,v2线性无关 176 | v = np.matrix('1.,1.;-1.,1.') 177 | 178 | c,b,A = f_powell() 179 | u = np.matrix('0.,0.;0.,0.') 180 | lamb = np.matrix('0.;0.') 181 | 182 | id = 0 183 | total = 0 184 | while total < 3: 185 | k,min_fk = golden_section_search(lambda k:f_value(f_powell, x0 + k*v[:,0]), [-100., 100], 0.001) 186 | x1 = x0 + k * v[:,0] 187 | 188 | k,min_fk = golden_section_search(lambda k:f_value(f_powell, x1 + k*v[:,1]), [-100., 100], 0.001) 189 | x2 = x1 + k * v[:,1] 190 | 191 | #找到u向量 192 | u[:,id] = x2 - x0 193 | k,min_fk = golden_section_search(lambda k:f_value(f_powell, x2 + k*u[:, id]), [-100., 100], 0.001) 194 | 195 | x0 = x2 + k*u[:,id] 196 | v[:,0] = v[:,1] 197 | v[:,1] = u[:,id] 198 | 199 | id = (id+1) % len(lamb) 200 | total += 1 201 | 202 | conj = u[:,0].T * A * u[:,1] 203 | #print "conj: ", conj 204 | 205 | x_star = x0 206 | 207 | return x_star, f_value(f_powell, x_star) 208 | 209 | from line_search import newton_search_for_quad 210 | 211 | from newton_method import newton_search_for_quad 212 | 213 | if __name__ == "__main__": 214 | conj_rst = conj_grandient_method_for_f2() 215 | print "\nconj_grandient_method_for_f2:", conj_rst 216 | 217 | conj_rst = conj_grandient_method_for_f2_direct() 218 | 219 | print "\nconj_grandient_method_for_f2_direct:", conj_rst 220 | 221 | frs = Fletcher_Reeves_conj() 222 | print "Fletcher_Reeves_conj.\nexpect: x2 = [0.4, 0.01]. \nReal:", frs 223 | 224 | frs = powell_conj() 225 | print "Fletcher_Reeves_conj.\nexpect: x2 = [0.4, 0.01]. \nReal:", frs 226 | -------------------------------------------------------------------------------- /constrained_optimized.py: -------------------------------------------------------------------------------- 1 | # encoding: utf8 2 | 3 | import numpy as np 4 | import pdb 5 | 6 | ''' 7 | 本文件主要包括一些算法的示例,并不是完整的实现。仅用来做为加强学习用 8 | 9 | 包括等式、不等式优化。 10 | 1. lagrange 等式、不等式优化 11 | 2. kkt 条件(不等式) 12 | 3. 梯度下降 13 | 4. 罚函数法 14 | 5. 外点法 15 | 6. 内点法(未实现) 16 | ''' 17 | 18 | # equal constrained 19 | ''' 20 | 示例1: 21 | 必要条件: lagrange_fun对应的梯度分量为0. 22 | 注: 并不是原问题有最优解,lagrange函数就能求出该最优解 23 | 比如这个函数: 24 | min sqrt(x^2 + y^2) 25 | s.t y^2 - (x-1)^3 = 0 26 | 这个最优解为 (0, 1), 但这个解并不是lagrange函数的解 27 | 28 | min x**2 + y**2 29 | s.t x + y =1 30 | 这个解是x + y = 1直线和上述出线等高线的切点 31 | 观察可得: 32 | x_star = [1/2, 1/2] 33 | 34 | L(x,lambd) = x^2 + y^2 + lambd * (x + y - 1) 35 | = x^2 + y^2 + x*lambd + y*lambd - lambd 36 | 37 | x = [x,y,lambd].T 38 | A = [2,0,1; 0,2,1; 1,1,0] 39 | b = [0,0,-1] 40 | c = 0 41 | ''' 42 | 43 | def f1(): 44 | A = np.matrix('2.,0.,1.; 0,2,1; 1,1,0') 45 | b = np.matrix('0.;0.;-1.') 46 | c = 0 47 | 48 | return c,b,A 49 | 50 | ''' 51 | min x1^2 + 4x2^2 52 | s.t x1 + 2x2 = 6 53 | 54 | x_star = [3., 3./2] 55 | 56 | L(x, lamb) = x1^2 + 4x2^2 + lamb * (x1 + 2x2 - 6) 57 | = x1^2 + 4x2^2 + x1*lamb + 2x2 * lamb - 6*lamb 58 | 59 | ''' 60 | def f2(): 61 | A = np.matrix('2.,0,1;0,8,2;1,2,0') 62 | b = np.matrix('0.; 0.; -6.') 63 | c = 0 64 | 65 | return c,b,A 66 | 67 | def equal_constrained_by_lagrange(f): 68 | c,b,A = f() 69 | #梯度方程: Ax = -b 70 | x = np.linalg.solve(A, -b) 71 | 72 | return x, 1/2. * x.T * A * x + b.T * x 73 | 74 | 75 | # inequality_constrained 76 | ''' 77 | 78 | 针对 lamb, seta 等于0分别讨论. 79 | lamb_i == 0: seta_i^2 > 0, h_i(x) > 0, 即最优解在可行域里 80 | seta_i == 0: h_i(x) = 0, 最优解在可行域边界上, 即和等式优化问题一样 81 | lamb_i,seta_i == 0: f_i' = 0, h_i = 0, 最优解在 h_i边界上,由h_i的边界穿过f_i的最小点 82 | 83 | L = f + sum(lamb_i * (h_i(x) - seta^2)) 84 | 85 | min (x-a)^2 86 | s.t x>=c 87 | 88 | l = (x-a)^2 - lamb*(x-c - seta^2) 89 | = x^2 - 2ax + a^2 - lamb*x + lamb*c + lamb * seta^2 90 | 91 | l是一个三次方程,不太好解。以下为简化解法:约束了 lamb == 0 (l1) or seta == 0 (l2) 92 | 93 | l_x = 2(x-a) - lamb 94 | l_lambda = x - c - theta^2 95 | l_theta = 2 * lamb * theta 96 | 97 | ''' 98 | 99 | def inequality_constrained_by_lagrange(a, c): 100 | # lamb == 0 101 | x = a 102 | if x >= c: #x > 0, l_lambda < 0 103 | return x, (x-a)**2 104 | 105 | #seta == 0 106 | x = c 107 | lamb = 2*(x - a) 108 | 109 | return x, (x-a)**2 110 | 111 | ''' 112 | 相比于lagrange不等式约束, 113 | KT约束不需要 theta参数,但有四个约束条件(本质上和 lagrange是一致的) 114 | 115 | min f(x) 116 | s.t. gi(x) <= 0 117 | 118 | 解法: 119 | L(x, lamb) = f(x) + sum(lamb_i * g_i(x)) 120 | 满足如下四个条件: 121 | partial_L/x = 0 122 | partial_L/lamb <= 0 (g_i(x) = 0) 123 | lamb_i >= 0 124 | lamb * g = 0 125 | 126 | min (x-a)^2 127 | s.t x>=c 128 | 129 | L(x, lamb) = (x-a)^2 - lamb * (c-x) 130 | 131 | partial_L/x = 2(x-a) - lamb * c 132 | partial_L/lamb = c-x 133 | 134 | ''' 135 | def inequality_constrained_by_KT(a, c): 136 | lamb = 0 #条件4,3 137 | x = a #条件1 138 | g = c - x 139 | if g < 0: #条件2 140 | return x, (x-a) ** 2 141 | 142 | x = c #g==0, 条件2,4 143 | lamb = 2. * (x - a) / c #条件1 144 | 145 | if lamb >= 0: 146 | return x, (x-a) ** 2 147 | 148 | return None 149 | 150 | 151 | ''' 152 | lagrange, kkt条件一般理论分析用。以下介绍工业界常用算法 153 | 154 | min f(x) 155 | s.t. g(x) >= 0 #注意是 >= 0 156 | ''' 157 | 158 | ''' 159 | min x1^2 + 2*x2^2 160 | s.t. x1 + x2 >= 4 161 | ''' 162 | def cons_f1(x, lt=False): 163 | coef = np.matrix('1.;2') 164 | 165 | f = np.sum(coef.T * np.multiply(x, x)) 166 | deriv_f = 2 * np.multiply(coef, x) 167 | deriv_f = deriv_f / np.sqrt(deriv_f.T * deriv_f) #归一化 168 | 169 | g = np.sum(x) - 4. 170 | deriv_g = np.matrix('1.;1.') 171 | if lt: 172 | g = -g 173 | deriv_g = -deriv_g 174 | 175 | deriv_g = deriv_g / np.sqrt(deriv_g.T * deriv_g) #归一化 176 | 177 | return f,deriv_f, g, deriv_g 178 | 179 | 180 | ''' 181 | hemstitching方法(绣花算法) 182 | 1. 如果在可行域里,走负梯度方向 183 | 2. 如果不在,则走约束函数梯度方向, 回走(注:约束函数 gi >= 0) 184 | 185 | 算法: 186 | 1. 求 grad(f), grad(gi) 187 | 2. 如果 x_p在可行域里,走f负梯度方向;如果在外,走 g梯度方向,拉回到可行域里 188 | 3. 如果两次差值很少,则结束 189 | ''' 190 | 191 | def hemstitching_method(f_fun, x0, epsilon): 192 | x = x0 193 | f_pre = None 194 | x_pre = None 195 | max_iter = 1000 196 | cur_iter = 0 197 | k=1 #这个步长太大,问题多多 198 | k=0.1 199 | 200 | while True: 201 | f,deriv_f, g, deriv_g = f_fun(x) 202 | #pdb.set_trace() 203 | cur_iter += 1 204 | 205 | if f_pre != None and np.abs(f - f_pre) < epsilon: 206 | break 207 | 208 | d = None 209 | if g >= 0: #可行域里 210 | d = -deriv_f 211 | #不能停。只好加一个这个限制。加一个步长应该会好一些 212 | if cur_iter > max_iter: 213 | print "max itered" 214 | break 215 | 216 | if x_pre != None: 217 | dis = np.abs(np.sum((x_pre - x).T * (x_pre - x))) 218 | if np.sqrt(dis) < epsilon: 219 | break 220 | 221 | x_pre = x 222 | else: 223 | d = deriv_g 224 | 225 | x = x + k * d 226 | 227 | f_pre = f 228 | 229 | return x, f 230 | 231 | ''' 232 | 合成方向法 233 | 如果在可行点外,d = -deriv_f + sum(deriv_gi) 234 | ''' 235 | def combined_method(f_fun, x0, epsilon): 236 | x = x0 237 | f_pre = None 238 | x_pre = None 239 | max_iter = 1000 240 | cur_iter = 0 241 | k=1 #这个步长太大,问题多多 242 | k=0.1 243 | 244 | while True: 245 | f,deriv_f, g, deriv_g = f_fun(x) 246 | #pdb.set_trace() 247 | cur_iter += 1 248 | 249 | d = None 250 | if g >= 0: #可行域里 251 | d = -deriv_f 252 | #不能停。只好加一个这个限制。加一个步长应该会好一些 253 | if cur_iter > max_iter: 254 | print "max itered" 255 | break 256 | 257 | if x_pre != None: 258 | dis = np.abs(np.sum((x_pre - x).T * (x_pre - x))) 259 | if np.sqrt(dis) < epsilon: 260 | break 261 | 262 | if f_pre != None and np.abs(f - f_pre) < epsilon: 263 | break 264 | 265 | x_pre = x 266 | f_pre = f 267 | else: 268 | #pdb.set_trace() 269 | # 用 d = -deriv_f + deriv_g, 出不来 270 | d = -deriv_f + 2 * deriv_g 271 | 272 | x = x + k * d 273 | 274 | return x, f 275 | 276 | 277 | 278 | ''' 279 | 上述两个方法,最好算一下步长。要不然一直收敛不了 280 | 281 | 可行方向法 282 | 保证方向是下降的 283 | 284 | max x0 285 | s.t. x0 + deriv_f.T * dp <= 0 #目标值下降 286 | x0 + deriv_g.T * dp - g(x0) <= 0 #在可行域内 287 | |dj| <= 1, x0 >= 0 288 | ''' 289 | 290 | from scipy.optimize import linprog 291 | 292 | def fliable_direction_method(f_fun, x0, esplison): 293 | x = x0 294 | f_pre = None 295 | x_pre = None 296 | max_iter = 1000 297 | cur_iter = 0 298 | k=1 #这个步长太大,问题多多 299 | k = 0.1 300 | k = 0.01 #这儿给的是固定步长。应该动态算一下:即在可行域里的最大k 301 | 302 | while True: 303 | f,deriv_f, g, deriv_g = f_fun(x, lt=True) 304 | 305 | if x_pre != None and np.sqrt(np.abs(np.sum((x_pre - x).T * (x_pre - x)))) < epsilon: 306 | break 307 | 308 | if f_pre != None and np.abs(f - f_pre) < epsilon: 309 | break 310 | 311 | c=np.array([-1., 0, 0]) 312 | ''' 313 | A = np.array([[1, deriv_f[0], deriv_f[1]], 314 | [1, deriv_g[0], deriv_g[1]]]) 315 | b = np.array([0., -g]) 316 | ''' 317 | A = np.array([[1, deriv_f[0], deriv_f[1]], 318 | [0, deriv_g[0], deriv_g[1]]]) 319 | b = np.array([0., -g]) 320 | 321 | x0_bounds = (0, None) 322 | d0_bounds = (-1., 1.) 323 | d1_bounds = (-1., 1.) 324 | 325 | #res = linprog(c, A_ub = A, b_ub = b, bounds=(x0_bounds, d0_bounds, d1_bounds), options={"disp":True}) 326 | res = linprog(c, A_ub = A, b_ub = b, bounds=(x0_bounds, d0_bounds, d1_bounds)) 327 | 328 | if res.success: 329 | x0, d0, d1 = res.x 330 | x[0] += d0 * k 331 | x[1] += d1 * k 332 | 333 | if x0 < esplison: 334 | f, deriv_f, g, deriv_g = f_fun(x) 335 | return x, f 336 | else: 337 | return None 338 | 339 | return None 340 | 341 | ''' 342 | 罚函数法(内点法) 343 | 1. 等式约束 344 | min x1^2 + x2^2 345 | s.t. x2 = 1 346 | 347 | 定义罚函数: 348 | P(x, K) = x1 ^2 + x2^2 + K * (x2-1)^2 349 | deriv(P) = [2x1, 2x2 + 2(x2-1)K] = 0 350 | x1 = 0 351 | x2 = 1. * K/(K+1) 352 | ''' 353 | 354 | def penity_method_1(K): 355 | x1 = 0. 356 | x2 = 1.0 * K/(K+1) 357 | 358 | return [x1,x2], x1*x1 + x2*x2 359 | 360 | 361 | if __name__ == "__main__": 362 | x_star = [1./2, 1./2] 363 | rs = equal_constrained_by_lagrange(f1) 364 | 365 | print "\nequality_constrained_by_lagrange:" 366 | print "\nexpect:", x_star 367 | print "\nreal:", rs 368 | 369 | x_star = [3., 3./2] 370 | rs = equal_constrained_by_lagrange(f2) 371 | 372 | print "\ninequality_constrained_by_lagrange:" 373 | print "\nexpect:", x_star 374 | print "\nreal:", rs 375 | 376 | a = 2 377 | c = 0 378 | rs = inequality_constrained_by_lagrange(a, c) 379 | print "\ninequality_constrained_by_lagrange:" 380 | print "a,c, expect:", a, c, a 381 | print "real:", rs 382 | 383 | a = 2 384 | c = 2 385 | rs = inequality_constrained_by_lagrange(a, c) 386 | print "\ninequality_constrained_by_lagrange:" 387 | print "a,c, expect:", a, c, a 388 | print "real:", rs 389 | 390 | a = 2 391 | c = 4 392 | rs = inequality_constrained_by_lagrange(a, c) 393 | print "\ninequality_constrained_by_lagrange:" 394 | print "a,c, expect:", a, c, c 395 | print "real:", rs 396 | 397 | a = 2 398 | c = 0 399 | rs = inequality_constrained_by_KT(a, c) 400 | print "\ninequality_constrained_by_KT:" 401 | print "a,c, expect:", a, c, a 402 | print "real:", rs 403 | 404 | a = 2 405 | c = 2 406 | rs = inequality_constrained_by_KT(a, c) 407 | print "\ninequality_constrained_by_KT:" 408 | print "a,c, expect:", a, c, a 409 | print "real:", rs 410 | 411 | a = 2 412 | c = 4 413 | rs = inequality_constrained_by_KT(a, c) 414 | print "\ninequality_constrained_by_KT:" 415 | print "a,c, expect:", a, c, c 416 | print "real:", rs 417 | 418 | x_star = [2.667,1.333] 419 | x_bar = np.matrix('1; 4.5') 420 | rst = hemstitching_method(cons_f1, x_bar, 0.001) 421 | print "\ninequality_constrained_ hemstitching_method:" 422 | print "\nexpect:", x_star 423 | print "\nreal:", rst 424 | 425 | rst = combined_method(cons_f1, x_bar, 0.001) 426 | print "\ninequality_constrained_ combined_method:" 427 | print "\nexpect:", x_star 428 | print "\nreal:", rst 429 | 430 | x_star = [2.667,1.333] 431 | x_bar = np.matrix('0.85; 3.15') 432 | rst = fliable_direction_method(cons_f1, x_bar, 0.01) 433 | print "\ninequality_constrained_ fliable_direction_method:" 434 | print "\nexpect:", x_star 435 | print "\nreal:", rst 436 | 437 | x_star = [0, 1] 438 | print "\npenity_method for equal constrained. x_star:", x_star 439 | 440 | K=1 441 | rst = penity_method_1(K) 442 | print "rst for K:%s; rst: %s" % (K, rst) 443 | 444 | K=10 445 | rst = penity_method_1(K) 446 | print "rst for K:%s; rst: %s" % (K, rst) 447 | 448 | K=100 449 | rst = penity_method_1(K) 450 | print "rst for K:%s; rst: %s" % (K, rst) 451 | 452 | K=10000 453 | rst = penity_method_1(K) 454 | print "rst for K:%s; rst: %s" % (K, rst) 455 | 456 | -------------------------------------------------------------------------------- /line_program/sample_by_cvxopt.py: -------------------------------------------------------------------------------- 1 | from cvxopt import matrix, solvers 2 | 3 | ######################################################################## 4 | 5 | ## mimimize 2 x1 + x2 6 | 7 | ##subject to 8 | 9 | ## -x1 +x2 <= 1 10 | 11 | ## x1 + x2 >= 2 12 | 13 | ## x2 >= 0 14 | 15 | ## x1 - 2 x2 <= 4 16 | 17 | ######################################################################## 18 | 19 | c = matrix([2.0, 1.0]) 20 | 21 | b = matrix([1.0, -2.0, 0.0, 4.0]) 22 | 23 | A = matrix([[-1.0, -1.0, 0.0, 1.0],[1.0, -1.0, 1.0, -2.0]]) 24 | 25 | sol = solvers.lp(c,A,b) 26 | 27 | print sol['x'] 28 | -------------------------------------------------------------------------------- /line_program/simplex.py: -------------------------------------------------------------------------------- 1 | # encoding: utf8 2 | 3 | ''' 4 | 线性规划的单纯型方法实现 5 | 6 | z = c.T * x_b 7 | min z 8 | s.t. D*x_b <= b, 9 | x_b >= 0 10 | 11 | 引入松驰变量(向量)xp, x_n = b - A*x_b >= 0, 12 | D * x_b + I * x_n = b 13 | [D I][x_b;x_n] = b 14 | 15 | 简写为: 16 | min z = c.T * x 17 | s.t. Ax = b, 18 | x >= 0 19 | 20 | A = [D I], 21 | x = [x_b; x_n] 22 | 23 | 24 | 其中对A要求行满秩(如果非行满秩,则约束条件行相关,Ax = b可能无解,需要把线性相关的线束去掉) 25 | 26 | 单纯形法,上式转为如下线性方程组: 27 | [1 -c.T 0; 0 D I] * [z;x_b;x_n] = [0;b] 28 | x >= 0 29 | 或 30 | [1 -c.T 0; 0 A] * [z;x] = [0;b] 31 | 32 | x >= 0 33 | 34 | 求满足上式z的最小值 35 | 36 | 37 | 以下解法中,只考虑 约束条件 <= b, 不考虑等式情况 38 | 引入松驰变量后的系数矩阵,其秩为m (m个松驰变量构成了m * m单位阵) 39 | 40 | 等式情况, 可以通过类似增加松驰变量的方式解决 41 | 42 | 选主元算法,两种: 43 | 1. dantzig规则 44 | 最大正判别数对应的列,正判别数最小标为列标 45 | 最小比值行标出基 46 | 对退化问题,可能会死循环,无最优解 47 | 48 | 2. Bland规则 49 | 正判别数最小下标进基, 即 50 | l = min{j|seta_j > 0, 1<=j <=n} 51 | 52 | ''' 53 | 54 | import numpy as np 55 | import sys 56 | import pdb 57 | 58 | class Simplex: 59 | def __init__(self, C, max_mode=False): 60 | self.mat = np.array([0] + C) 61 | if max_mode: 62 | self.mat *= -1 63 | 64 | def solve(self): 65 | ''' 66 | 松驰后的增广矩阵 [z C;b A] 67 | ''' 68 | m,n = self.mat.shape 69 | temp = np.vstack((np.zeros(m-1), np.eye(m-1))) #第一行:z=c.T * x; 2 ..m: m-1 维限制条件 70 | self.mat = np.hstack((self.mat, temp)) 71 | m,n = self.mat.shape 72 | B = np.array(range(m-1, n)) #B0, 初始基的列编号 73 | 74 | #判别数: C.T - Cb.T * B.inv * A, 75 | #Z.new - Z = (CN.T - Cb.T * B.inv * CN) * XN 76 | #theta0: B.inv = B = np.eye(m - 1) 77 | theta = np.array(self.mat[0]) 78 | while theta.min() < 0: 79 | col = theta.argmin() 80 | #出基判别 81 | out_row = np.zeros(m) 82 | out_row[0] = sys.maxint 83 | for i in range(1,m): 84 | out_row[i] = sys.maxint 85 | if self.mat[i, col] > 1e-9: #如果全小于0, 需要处理 86 | out_row[i] = self.mat[i, 0] / self.mat[i, col] 87 | 88 | row = out_row.argmin() 89 | 90 | self.mat[row,:] = self.mat[row,:] / self.mat[row, col] 91 | for i in range(1,m): 92 | if np.abs(self.mat[i, col]) > 1e-9 and i != row: 93 | self.mat[i,:] -= self.mat[row,:] * self.mat[i, col] 94 | 95 | B[row-1] = col 96 | pdb.set_trace() 97 | theta[1:] = self.mat[0,1:] - np.dot(self.mat[0,:].take(B), self.mat[1:, 1:]) # theta = C - (Cb.T * B.inv * A) = C - Cb.T * A 98 | 99 | pdb.set_trace() 100 | 101 | z = np.dot(self.mat[0].take(B) * self.mat[1:, 0]) 102 | 103 | return z 104 | 105 | ''' 106 | ax <= b 107 | x >= 0 108 | ''' 109 | def add_constraint(self, a, b): 110 | self.mat = np.vstack((self.mat, [b] + a)) 111 | 112 | 113 | ''' 114 | min z=-x1 - 14x2 - 6x3 115 | s.t. x1 + x2 + x3 <= 4 116 | x1 <= 2 117 | x3 <= 3 118 | 3x2 + x3 <= 6 119 | 120 | answer: -32.0 121 | ''' 122 | 123 | if __name__ == "__main__": 124 | z = [-1, -14, -6] 125 | t1 = Simplex(z) 126 | t1.add_constraint([1,1,1], 4) 127 | t1.add_constraint([1,0,0], 2) 128 | t1.add_constraint([0,0,1], 3) 129 | t1.add_constraint([0,3,1], 6) 130 | 131 | result = t1.solve() 132 | 133 | print "expect result -24; real result:", result 134 | 135 | -------------------------------------------------------------------------------- /line_program/simplex_alg.py: -------------------------------------------------------------------------------- 1 | # encoding: utf8 2 | 3 | ''' 4 | 线性规划的单纯型方法实现 5 | 6 | z = c.T * x_b 7 | min z 8 | s.t. D*x_b <= b, 9 | x_b >= 0 10 | 11 | 引入松驰变量(向量)xp, x_n = b - A*x_b >= 0, 12 | D * x_b + I * x_n = b 13 | [D I][x_b;x_n] = b 14 | 15 | 简写为: 16 | min z = c.T * x 17 | s.t. Ax = b, 18 | x >= 0 19 | 20 | A = [D I], 21 | x = [x_b; x_n] 22 | 23 | 24 | 其中对A要求行满秩(如果非行满秩,则约束条件行相关,Ax = b可能无解,需要把线性相关的线束去掉) 25 | 26 | 单纯形法,上式转为如下线性方程组: 27 | [1 -c.T 0; 0 D I] * [z;x_b;x_n] = [0;b] 28 | x >= 0 29 | 或 30 | [1 -c.T 0; 0 A] * [z;x] = [0;b] 31 | 32 | x >= 0 33 | 34 | 求满足上式z的最小值 35 | 36 | 37 | 以下解法中,只考虑 约束条件 <= b, 不考虑等式情况 38 | 引入松驰变量后的系数矩阵,其秩为m (m个松驰变量构成了m * m单位阵) 39 | 40 | 等式情况, 可以通过类似增加松驰变量的方式解决 41 | 42 | 选主元算法,两种: 43 | 1. dantzig规则 44 | 最大正判别数对应的列,正判别数最小标为列标 45 | 最小比值行标出基 46 | 对退化问题,可能会死循环,无最优解 47 | 48 | 2. Bland规则 49 | 正判别数最小下标进基, 即 50 | l = min{j|seta_j > 0, 1<=j <=n} 51 | 52 | ''' 53 | 54 | import numpy as np 55 | import sys 56 | import pdb 57 | 58 | class Simplex: 59 | def __init__(self, C, max_mode=False): 60 | self.mat = np.array([0] + C) 61 | if max_mode: 62 | self.mat *= -1 63 | 64 | ''' 65 | ax <= b 66 | x >= 0 67 | ''' 68 | def add_constraint(self, a, b): 69 | self.mat = np.vstack((self.mat, [b] + a)) 70 | 71 | def solve(self): 72 | ''' 73 | 松驰后的增广矩阵 [z C;b A] 74 | ''' 75 | cm,cn = self.mat.shape 76 | B = np.array(range(cm-1, cm+cn-1)) #B0, 初始基的列编号 77 | temp = np.vstack((np.zeros(cm-1), np.eye(cm-1))) #第一行:z=c.T * x; 2 ..m: m-1 维限制条件 78 | self.mat = np.hstack((self.mat, temp)) 79 | m,n = self.mat.shape 80 | #判别数: C.T - Cb.T * B.inv * A, 81 | #Z.new - Z = (CN.T - Cb.T * B.inv * CN) * XN 82 | #theta0: B.inv = B = np.eye(m - 1) 83 | theta = self.mat[0] 84 | while theta[1:].min() < 0: 85 | col = theta[1:].argmin() + 1 86 | #出基判别 87 | out_row = np.zeros(m) 88 | out_row[0] = sys.maxint 89 | for i in range(1,m): 90 | out_row[i] = sys.maxint 91 | if self.mat[i, col] > 1e-9: #如果全小于0, 需要处理 92 | out_row[i] = self.mat[i, 0] / self.mat[i, col] 93 | 94 | row = out_row.argmin() 95 | 96 | self.mat[row,:] = self.mat[row,:] / self.mat[row, col] 97 | for i in range(m): 98 | if np.abs(self.mat[i, col]) > 1e-9 and i != row: 99 | self.mat[i,:] -= self.mat[row,:] * self.mat[i, col] 100 | 101 | B[row-1] = col 102 | 103 | z = -1 * self.mat[0,0] 104 | 105 | sol=np.zeros(cn-1) 106 | for i in range(len(B)): 107 | if B[i] < cn: 108 | sol[B[i]-1] = self.mat[i+1,0] 109 | 110 | 111 | return z, sol 112 | 113 | 114 | ''' 115 | min z=-x1 - 14x2 - 6x3 116 | s.t. x1 + x2 + x3 <= 4 117 | x1 <= 2 118 | x3 <= 3 119 | 3x2 + x3 <= 6 120 | 121 | answer: -32.0 122 | ''' 123 | 124 | if __name__ == "__main__": 125 | z = [-1, -14, -6] 126 | t1 = Simplex(z) 127 | t1.add_constraint([1,1,1], 4) 128 | t1.add_constraint([1,0,0], 2) 129 | t1.add_constraint([0,0,1], 3) 130 | t1.add_constraint([0,3,1], 6) 131 | 132 | result,sol = t1.solve() 133 | 134 | print "expect result -32; real result:", result 135 | 136 | -------------------------------------------------------------------------------- /line_program/simplex_orginal.py: -------------------------------------------------------------------------------- 1 | # encoding: utf8 2 | 3 | ''' 4 | 线性规划的单纯型方法实现 5 | 6 | z = c.T * x_b 7 | min z 8 | s.t. D*x_b <= b, 9 | x_b >= 0 10 | 11 | 引入松驰变量(向量)xp, x_n = b - A*x_b >= 0, 12 | D * x_b + I * x_n = b 13 | [D I][x_b;x_n] = b 14 | 15 | 简写为: 16 | min z = c.T * x 17 | s.t. Ax = b, 18 | x >= 0 19 | 20 | A = [D I], 21 | x = [x_b; x_n] 22 | 23 | 24 | 其中对A要求行满秩(如果非行满秩,则约束条件行相关,Ax = b可能无解,需要把线性相关的线束去掉) 25 | 26 | 单纯形法,上式转为如下线性方程组: 27 | [1 -c.T 0; 0 D I] * [z;x_b;x_n] = [0;b] 28 | x >= 0 29 | 或 30 | [1 -c.T 0; 0 A] * [z;x] = [0;b] 31 | 32 | x >= 0 33 | 34 | 求满足上式z的最小值 35 | 36 | 37 | 以下解法中,只考虑 约束条件 <= b, 不考虑等式情况 38 | 引入松驰变量后的系数矩阵,其秩为m (m个松驰变量构成了m * m单位阵) 39 | 40 | 等式情况, 可以通过类似增加松驰变量的方式解决 41 | 42 | 选主元算法,两种: 43 | 1. dantzig规则 44 | 最大正判别数对应的列,正判别数最小标为列标 45 | 最小比值行标出基 46 | 对退化问题,可能会死循环,无最优解 47 | 48 | 2. Bland规则 49 | 正判别数最小下标进基, 即 50 | l = min{j|seta_j > 0, 1<=j <=n} 51 | 52 | ''' 53 | 54 | import numpy as np 55 | import sys 56 | import pdb 57 | 58 | class Simplex: 59 | def __init__(self, C, max_mode=False): 60 | self.C = np.array(C) 61 | self.max_mode = max_mode 62 | self.constraints = [] 63 | self.b = [] 64 | #松驰后的增广矩阵 [A b;C z] 65 | self.cons_mat = None 66 | self.C_array = None 67 | 68 | ''' 69 | ax <= b 70 | x >= 0 71 | ''' 72 | def add_constraint(self, a, b): 73 | self.constraints.append(a) 74 | self.b.append(b) 75 | 76 | def solve(self): 77 | #条件矩阵,松也变量m*m, + 最后一列b 78 | self.cons_mat = np.hstack((np.array(self.constraints), np.eye(len(self.constraints)), np.mat(self.b).T)) 79 | #最后一行:c.T * x, z 80 | self.C_array = np.hstack((np.array(self.C), np.zeros(len(self.b) + 1))) 81 | 82 | m,n = self.cons_mat.shape 83 | #Z.new - Z = (CN.T - Cb.T * B.inv * CN) * XN 84 | #判别数: C - Cb.T * B.inv * A, B.inv = B = np.eye(m - 1), theta0 = C - Cb.T * A = C 85 | theta = np.array(self.C_array[:-1]) 86 | B = np.array(range(len(self.C), n-1)) #B0, 初始基的列编号 87 | while theta.min() < 0: 88 | col = theta.argmin() 89 | #出基判别 90 | out_row = np.full(m, sys.maxint, dtype='float') 91 | for i in range(m): 92 | if self.cons_mat[i, col] > 1e-9: #如果全小于0, 需要处理 93 | out_row[i] = self.cons_mat[i, 0] / self.cons_mat[i, col] 94 | 95 | row = out_row.argmin() 96 | self.cons_mat[row,:] = self.cons_mat[row,:] / self.cons_mat[row, col] 97 | for i in range(m): 98 | if np.abs(self.cons_mat[i, col]) > 1e-9 and i != row: 99 | self.cons_mat[i,:] -= self.cons_mat[row,:] * self.cons_mat[i, col] 100 | 101 | B[row] = col 102 | # theta = C - (Cb.T * B.inv * A) = C - Cb.T * A 103 | theta[:] = self.C_array[:-1] - np.dot(self.C_array.take(B), self.cons_mat[:, :-1]) 104 | 105 | z = self.C_array.take(B) * self.cons_mat[:,-1] 106 | 107 | pdb.set_trace() 108 | 109 | return z[0,0] 110 | 111 | 112 | if __name__ == "__main__": 113 | ''' 114 | min z=-x1 - 14x2 - 6x3 115 | s.t. x1 + x2 + x3 <= 4 116 | x1 <= 2 117 | x3 <= 3 118 | 3x2 + x3 <= 6 119 | 120 | answer: -32.0 121 | ''' 122 | z = [-1, -14, -6] 123 | t1 = Simplex(z) 124 | t1.add_constraint([1,1,1], 4) 125 | t1.add_constraint([1,0,0], 2) 126 | t1.add_constraint([0,0,1], 3) 127 | t1.add_constraint([0,3,1], 6) 128 | 129 | result = t1.solve() 130 | 131 | print "expect result -32; real result:", result 132 | 133 | -------------------------------------------------------------------------------- /line_search.py: -------------------------------------------------------------------------------- 1 | #encoding: utf8 2 | 3 | ''' 4 | f = 8 * x**3 - 2*x**2 - 7*x + 3, x* = 0.63, epsilon = 0.1, 0=< 0 <= 1 5 | 6 | 主要方法: 7 | 1. 二分法 8 | 2. 等分法(四等分) 9 | 3. 10 | 11 | ''' 12 | 13 | import numpy as np 14 | import pdb 15 | 16 | #二分法 17 | #x* = 0.63 18 | def f1(x): 19 | f = 8 * (x ** 3) - 2 * (x ** 2) - 7 * x + 3.0 20 | return f 21 | 22 | # def_field2 = [0, 10.0] 23 | # for fibonacci_search 24 | # x* = 2.98 25 | def f2(x): 26 | f = x ** 2 - 6 * x + 2 27 | return f 28 | 29 | # def_field3 = [1, 2.0] 30 | # for golden_section_search 31 | # x* = 1.609 32 | def f3(x): 33 | f = np.exp(x) - 5*x 34 | return f 35 | 36 | #二分 37 | def bisection_search(f, def_field, epsilon): 38 | half_epsilon = epsilon / 2.0 39 | lf = list(def_field) 40 | f_vals = [f(lf[0]), f(lf[1])] 41 | 42 | while True: 43 | mid_x = (lf[1] + lf[0])/2.0 44 | mid_esp = [mid_x - half_epsilon, mid_x + half_epsilon] 45 | tmp_f = [f(mid_esp[0]), f(mid_esp[1])] 46 | if tmp_f[0] > tmp_f[1]: 47 | f_vals[0] = tmp_f[0] 48 | lf[0] = mid_esp[0] 49 | else: 50 | f_vals[1] = tmp_f[1] 51 | lf[1] = mid_esp[1] 52 | 53 | if (lf[1] - lf[0]) <= epsilon * 1.000001: 54 | x_star = (lf[0] + lf[1]) / 2 55 | return x_star, f(x_star) 56 | 57 | 58 | #等分搜索法 59 | #四等分 60 | #取中间3个点的最小值点。该点两边两个点为新的区间,最小值落在该区间里 61 | #如果有两个相同的最小值,则最小值就在这两个最小值点之间。算法适用 62 | def equal_interval_search(f, def_field, epsilon): 63 | steps = np.linspace(def_field[0], def_field[1], 5) 64 | values = np.apply_along_axis(f, 0, steps) 65 | 66 | while True: 67 | min_id = values[1:4].argmin() + 1 68 | steps = np.linspace(steps[min_id-1], steps[min_id+1], 5) 69 | values = np.array([values[min_id-1], f(steps[1]), values[min_id], f(steps[3]), values[min_id+1]]) 70 | 71 | if (steps[4] - steps[0]) < epsilon * 0.1: 72 | return steps[2], values[2] 73 | 74 | return None 75 | 76 | 77 | fib_const_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, \ 78 | 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, \ 79 | 75025, 121393, 196418, 317811, 514229, 832040, 1346269, \ 80 | 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, \ 81 | 39088169, 63245986, 102334155, 165580141,267914296, \ 82 | 433494437, 701408733, 1134903170, 1836311903, 2971215073, \ 83 | 4807526976, 7778742049] 84 | 85 | #fibonacci搜索 86 | def fibonacci_search(f, def_field, epsilon): 87 | fib_values = np.array(fib_const_list) 88 | num = (def_field[1] - def_field[0]) / epsilon 89 | fidx_n = np.where(fib_values >= num)[0][0] 90 | 91 | step = (def_field[1] - def_field[0]) * fib_values[fidx_n - 1] * 1.0/fib_values[fidx_n] 92 | points = [def_field[0], def_field[1] - step, def_field[0] + step, def_field[1]] 93 | f_values = np.apply_along_axis(f, 0, points) 94 | 95 | for i in range(fidx_n-1, 1, -1): 96 | step = points[2] - points[1] 97 | if f_values[1] < f_values[2]: 98 | min_point = 1 99 | points[3] = points[2] 100 | f_values[3] = f_values[2] 101 | points[2] = points[1] 102 | f_values[2] = f_values[1] 103 | points[1] = points[0] + step 104 | f_values[1] = f(points[1]) 105 | else: 106 | min_point = 2 107 | points[0] = points[1] 108 | f_values[0] = f_values[1] 109 | points[1] = points[2] 110 | f_values[1] = f_values[2] 111 | points[2] = points[3] - step 112 | f_values[2] = f(points[2]) 113 | 114 | dst_p = (points[2] + points[1]) / 2 115 | 116 | return (dst_p, f(dst_p)) 117 | 118 | #黄金分割法 119 | def golden_section_search(f, def_field, epsilon, args=None): 120 | golden_const = 0.618 121 | 122 | step = (def_field[1] - def_field[0]) * 0.618 123 | points = [def_field[0], def_field[1] - step, def_field[0] + step, def_field[1]] 124 | f_values = np.zeros(len(points)) 125 | for i in range(len(points)): 126 | f_values[i] = f(points[i]) 127 | 128 | while (points[2] - points[1]) > epsilon: 129 | #step = (points[2] - points[1]) 130 | step = (points[2] - points[0]) * (1 - golden_const) 131 | if f_values[1] < f_values[2]: 132 | min_point = 1 133 | points[3] = points[2] 134 | f_values[3] = f_values[2] 135 | points[2] = points[1] 136 | f_values[2] = f_values[1] 137 | points[1] = points[0] + step 138 | f_values[1] = f(points[1]) 139 | else: 140 | min_point = 2 141 | points[0] = points[1] 142 | f_values[0] = f_values[1] 143 | points[1] = points[2] 144 | f_values[1] = f_values[2] 145 | points[2] = points[3] - step 146 | f_values[2] = f(points[2]) 147 | 148 | dst_p = (points[2] + points[1]) / 2 149 | 150 | return dst_p, f(dst_p) 151 | 152 | def f4(): 153 | # f = 4*x1**2 + 2*x1*x2 + 2 * x2**2 + x1 + x2 154 | # normal: f = c + b.T * x + 1/2 * x.T * A * x 155 | # dst_x = np.array([-1.0/14, -3.0/14]) 156 | c = 2 157 | b = np.matrix('1;1') 158 | A = np.matrix('8,2;2,4') 159 | 160 | return c,b,A 161 | 162 | def quad_value(f, x): 163 | c,b,A = f 164 | return c + b.T * x + x.T * A * x 165 | 166 | 167 | 168 | #非精确搜索 169 | #多项式拟合法, 求出a,b,c三点 170 | #x0: 起始点,v: 梯度下降方向(负梯度单位方向) 171 | def quadratic_polynomial(f, x0, v): 172 | a = 0. 173 | fa = f(x0) 174 | b=1. 175 | fb = f(x0 + b*v) 176 | c = 0. 177 | fc = 0. 178 | 179 | st = 1. 180 | 181 | if fa > fb: 182 | #c: the first point f(c) > f(b) 183 | # lambda = 2, 4,8,...,a,b,c 184 | while True: 185 | c = b + st 186 | fc = f(x0 + c*v) 187 | if fc >= fb: 188 | break 189 | 190 | fa = fb 191 | fb = fc 192 | a = b 193 | b = c 194 | st *= 2. 195 | else: 196 | #a=0,b=lambda, c=2*lambda, lambda=1/2, 1/4, ... 197 | c = b 198 | fc = fb 199 | while True: 200 | st *= 1./2 201 | b = a * st 202 | 203 | fb = f(x0 + b*v) 204 | if fb < fc: 205 | break 206 | fc = fb 207 | c = b 208 | 209 | #pdb.set_trace() 210 | lambd = 1/2.0 * (fa*(c**2 - b**2) + fb*(a**2 - c**2) + fc*(b**2 - a**2)) 211 | lambd /= (fa*(c - b) + fb*(a - c) + fc*(b - a)) 212 | 213 | f_lamb = f(lambd) 214 | if f_lamb < fb: 215 | return lambd 216 | 217 | return b 218 | 219 | 220 | from newton_method import newton_search_for_quad 221 | 222 | if __name__ == "__main__": 223 | # x* = 2.98 224 | def_field2 = [0, 10.0] 225 | fr = fibonacci_search(f2, def_field2, 0.05) 226 | print "fr: expect 2.98; real:", fr 227 | 228 | # x* = 1.609 229 | def_field3 = [1, 2.0] 230 | gr = golden_section_search(f3, def_field3, 0.01) 231 | print "gr: expect 1.609; real:", gr 232 | 233 | def_fd = [0.,1.] 234 | br = bisection_search(f1, def_fd, 0.1) 235 | 236 | print "br:", br 237 | er = equal_interval_search(f1, def_fd, 0.1) 238 | print "er:", er 239 | 240 | x0 = np.matrix('0.0;0.0') 241 | rst = newton_search_for_quad(f4, x0, 0.01) 242 | dst_x = np.array([-1.0/14, -3.0/14]) 243 | 244 | print "expect x:0.63" 245 | print "nr: dst:", dst_x 246 | print "nr: rst:", rst 247 | 248 | # x* = 0.63 249 | #rst: 0.52 250 | rst = quadratic_polynomial(f1, 0, 1) 251 | print "quadratic_polynomial, expect x: 0.63, 0.52; real:", rst 252 | 253 | # x* = 0.609 254 | #rst: 0.531 255 | rst = quadratic_polynomial(f3, 1, 1) 256 | print "quadratic_polynomial, expect x: 0.609, 0.531; real:", rst 257 | -------------------------------------------------------------------------------- /newton_method.py: -------------------------------------------------------------------------------- 1 | #encoding: utf8 2 | 3 | import numpy as np 4 | import pdb 5 | 6 | ''' 7 | 求二次型函数在指定点的值 8 | 其梯度值为: Gx + b 9 | ''' 10 | def f_value(f, x): 11 | c,b,A = f() 12 | val = c + b.T * x + 1./2.*x.T * A * x 13 | 14 | return np.sum(val) 15 | 16 | def f4(): 17 | # f = 4*x1**2 + 2*x1*x2 + 2 * x2**2 + x1 + x2 18 | # normal: f = c + b.T * x + 1/2 * x.T * A * x 19 | # dst_x = np.array([-1.0/14, -3.0/14]) 20 | c = 2 21 | b = np.matrix('1;1') 22 | A = np.matrix('8,2;2,4') 23 | 24 | return c,b,A 25 | 26 | ''' 27 | 牛顿法、拟牛顿法用在非线性优化上 28 | 不过因为牛顿法、拟牛顿法在非线性优化上用得比较广,单独写一个文件 29 | 包括: 直接求解、牛顿法、dsp、bfgs, l-bfgs(稍晚点实现) 30 | ''' 31 | 32 | ''' 33 | 对正定型二次型函数,直接求解最优点 34 | Gx + b = 0 35 | x = -G.inv * b 36 | Ax = -b, 求解x 37 | ''' 38 | def solve_direct(f): 39 | c,b,A = f() 40 | 41 | eigs = np.linalg.eigvals(A) 42 | less_zero = np.take(eigs, np.where(eigs < 0)) 43 | if less_zero.shape[1] > 0: 44 | #非正定,不能求解。 45 | return None 46 | 47 | #x_star = -1. * np.linalg.inv(A) * b 48 | # 不用求逆. 用求解线性方程线的方法求解: x=A.inv * b ==> Ax = -b 49 | x_star = np.linalg.solve(A, -b) 50 | 51 | return x_star, f_value(f, x_star) 52 | 53 | 54 | ''' 55 | 牛顿法. 要求f有二阶导数 56 | 牛顿法非区间搜索法。只要给到起始点,就可以下降(对凸函数是这样子) 57 | 58 | 算法大致如下: 59 | 对原函数二阶tayler展开,然后用二次多项式近似: 60 | f(x) = f(x0) + g(x)(x - x0) + 1/2(x-x0).T * H * (x - x0) + O((x-x0).T(x-x0)) 61 | f_sim(x) = f(x0) + g(x)(x - x0) + 1/2(x-x0).T * H * (x - x0) 62 | f_sim'(x) = g(x) + H(x-x0) = 0 63 | x = x0 - H.inv * g(x) 64 | 65 | dk = -H.inv * f', 称为牛顿方向 66 | 67 | 牛顿法求解,计算量比较大,还要求H正定 68 | H为海森矩阵, 要求是非奇异的 69 | 70 | 阻尼牛顿法 71 | 由于牛顿法并不能保证收敛.于是改为沿dk方向进行一维搜索求,xk+1 = xk + lambk * dk, 72 | 73 | 实际上并不直接求H.inv, 而改为解线性方程: 74 | H*dk = f' 75 | 76 | ''' 77 | def newton_search_for_quad(f, x0, epsilon): 78 | c,b,A = f() 79 | x_n_1 = x0 80 | x = x0 81 | f_n_1 = c + b.T * x + 1/2.0 * x.T * A * x 82 | 83 | while True: 84 | H_f = A 85 | deriv_f = A * x_n_1 + b 86 | 87 | x_n = x_n_1 - np.dot(np.linalg.inv(H_f), deriv_f) 88 | x = x_n 89 | f_n = c + b.T * x + 1/2.0 * x.T * A * x 90 | 91 | if np.abs(f_n - f_n_1) < epsilon: 92 | return x_n, f_n 93 | 94 | x_n_1 = x_n 95 | f_n_1 = f_n 96 | 97 | return None 98 | 99 | ''' 100 | 拟牛顿条件 101 | 如上式: 102 | ~=: sim_eq 103 | f(x)在x_k+1点处理展开 104 | f(x) ~= f(x_k1) + f'(x_k1)(x-xk) + 1/2*(x_k1-x).T * H * (x_k1-x) 105 | 两边同时作用一个梯度算子,则: 106 | f'(x) ~= f'(x_k1) + H(x_k1)*(x_k1 - x) 107 | 记 x=x_k 108 | f'(x_k) ~= f'(x_k1) + H(x_k1) * (x_k1 - x_k) 109 | f'(x_k1) - f'(x_k) ~= H(x_k1) * (x_k1 - x_k) 110 | 111 | 记 B=H, D=H.inv, y_k = f'(x_k1) - f'(x_k), s_k = (x_k1 - x_k),则 112 | y_k ~= H*s_k 113 | s_k ~= H.inv * y_k 114 | 上述即为拟牛顿条件, 115 | 对 H(k+1)或H(k+1).inv做近似 116 | y_k = B(k+1)*s_k 117 | 或: 118 | s_k = D(k+1) * y_k 119 | 120 | 即用梯度近似计算H或H的逆. 121 | ''' 122 | 123 | ''' 124 | Dk_1=Dk + deltaD 125 | dletaD = alpha * u * u.T + beta * v * v.T 126 | u = sk 127 | v = Dk*yk 128 | alpha = 1/(u.T * yk) 129 | beta = -1/(v.T * yk) 130 | deltaD = 1/(sk.T * yk) * sk * sk.T - 1/((Dk * yk).T * yk) * (Dk * yk).T * (Dk * yk) 131 | ''' 132 | 133 | from line_search import golden_section_search 134 | 135 | def DFP(f, f_deriv, x0, epsilon): 136 | x_k = x0 137 | D_k = np.eye(x0.shape[0]) 138 | g_k = f_deriv(x0) 139 | 140 | while True: 141 | def_field = [-100., 100.] 142 | d = -1. * D_k * g_k 143 | k,min_fk = golden_section_search(lambda k:f(x_k + k*d), def_field, epsilon) 144 | x_k1 = x_k + k*d 145 | g_k1 = f_deriv(x_k1) 146 | 147 | #pdb.set_trace() 148 | g_sum = np.sum((g_k1.T * g_k1)) 149 | g_sum = np.sqrt(g_sum) 150 | 151 | if g_sum < epsilon: 152 | break 153 | 154 | sk = x_k1 - x_k 155 | yk = g_k1 - g_k 156 | 157 | v = sk 158 | u = D_k * yk 159 | 160 | alpha = 1. / (v.T * yk)[0,0] 161 | beta = -1. / (u.T * yk)[0,0] 162 | 163 | delta_D = alpha * v * v.T + beta * u * u.T 164 | 165 | #下一个点的D 166 | D_k = D_k + delta_D 167 | x_k = x_k1 168 | g_k = g_k1 169 | 170 | return x_k1, f(x_k1) 171 | 172 | ''' 173 | BFGS: 近似求H, 这样在计算下降方向时,需要求H的逆。求逆时会有优化方法. 而不是直接调用 174 | 方法1: 求解线性方程组:dk = -Bk * gk ---> Bk * dk = -gk, 175 | 方法2: B_k1.inv = (I - sk*yk.T/(yk.T *sk) Bk.inv (I - yk*sk.T/(yk.T*sk)) + sk*sk.T/(yk.T*sk) 176 | np.linalg.inv(B_k) 177 | ''' 178 | def BFGS_simple(f, f_deriv, x0, epsilon): 179 | x_k = x0 180 | B_k = np.eye(x0.shape[0]) 181 | g_k = f_deriv(x0) 182 | 183 | while True: 184 | def_field = [-100., 100.] 185 | #D_k = np.linalg.inv(B_k) 186 | #d = -1. * D_k * g_k 187 | d = np.linalg.solve(B_k, g_k) 188 | 189 | k,min_fk = golden_section_search(lambda k:f(x_k + k*d), def_field, epsilon) 190 | x_k1 = x_k + k*d 191 | g_k1 = f_deriv(x_k1) 192 | 193 | #pdb.set_trace() 194 | g_sum = np.sum((g_k1.T * g_k1)) 195 | g_sum = np.sqrt(g_sum) 196 | 197 | if g_sum < epsilon: 198 | break 199 | 200 | sk = x_k1 - x_k 201 | yk = g_k1 - g_k 202 | 203 | v = yk 204 | u = B_k * sk 205 | 206 | alpha = 1. / (v.T * sk)[0,0] 207 | beta = -1. / (u.T * sk)[0,0] 208 | 209 | delta_B = alpha * v * v.T + beta * u * u.T 210 | 211 | #下一个点的D 212 | B_k = B_k + delta_B 213 | x_k = x_k1 214 | g_k = g_k1 215 | 216 | return x_k1, f(x_k1) 217 | 218 | ''' 219 | 方法2: B_k1.inv = (I - sk*yk.T/(yk.T *sk) Bk.inv (I - yk*sk.T/(yk.T*sk)) + sk*sk.T/(yk.T*sk) 220 | 该实现方法和原版算法书上的介绍不太一致,需要对一下 221 | ''' 222 | def BFGS(f, f_deriv, x0, epsilon): 223 | x_k = x0 224 | B_k = np.eye(x0.shape[0]) 225 | D_k = np.linalg.inv(B_k) 226 | g_k = f_deriv(x0) 227 | 228 | while True: 229 | def_field = [-100., 100.] 230 | d = -1. * D_k * g_k 231 | 232 | k,min_fk = golden_section_search(lambda k:f(x_k + k*d), def_field, epsilon) 233 | sk = k * d 234 | x_k1 = x_k + sk 235 | g_k1 = f_deriv(x_k1) 236 | yk = g_k1 - g_k 237 | 238 | g_sum = np.sqrt(np.sum((g_k1.T * g_k1))) 239 | if g_sum < epsilon: 240 | break 241 | 242 | #下一个点的D 243 | I = np.eye(x0.shape[0]) 244 | rho = 1./(yk.T * sk)[0,0] 245 | V = I - sk * yk.T * rho 246 | #D_k1 = (I - rho * sk * yk.T) * D_k * (I - rho* yk*sk.T) + rho * sk * sk.T 247 | D_k1 = V * D_k * V.T + rho * sk * sk.T #与上式等价 248 | 249 | D_k = D_k1 250 | x_k = x_k1 251 | g_k = g_k1 252 | 253 | return x_k1, f(x_k1) 254 | 255 | ''' 256 | 257 | ''' 258 | def L_BFGS(f, f_deriv, x0, epsilon): 259 | return None 260 | 261 | if __name__ == "__main__": 262 | x0 = np.matrix('0.0;0.0') 263 | esplison = 0.005 264 | c,b,A = f4() 265 | dst_x = np.matrix(np.array([-1.0/14, -3.0/14])) 266 | print "\nnr: dst:", dst_x 267 | 268 | dr = solve_direct(f4) 269 | print "\ndr: rst:", dr 270 | 271 | rst = newton_search_for_quad(f4, x0, 0.01) 272 | 273 | print "\nnr: rst:", rst 274 | 275 | f = lambda x:f_value(f4, x) 276 | f_deriv = lambda x:(A*x + b) 277 | 278 | dfp_rs = DFP(f, f_deriv, x0, esplison) 279 | print "\ndfp rst:", dfp_rs 280 | 281 | bfgs_rs = BFGS_simple(f, f_deriv, x0, esplison) 282 | print "\nbfgs rst:", bfgs_rs 283 | 284 | bfgs2_rs = BFGS(f, f_deriv, x0, esplison) 285 | print "\nbfgs rst:", bfgs2_rs 286 | 287 | -------------------------------------------------------------------------------- /optimal_grandient.py: -------------------------------------------------------------------------------- 1 | #encoding: utf8 2 | 3 | import numpy as np 4 | import pdb 5 | 6 | ''' 7 | 1. 直接求解:对二次函数,直接求解 8 | x_star = A.inv * b 9 | 10 | 2. 最优梯度下降法 11 | 2.1. 给定起始点 12 | 2.2. 找到该方向的梯度 13 | 2.3. 沿负梯度方向,找到该方向最优值 (lambda 参数。) 14 | a. 一维搜索方法 15 | b. 对二次函数,如果A为正定矩阵,可以直接求解 16 | f = c + b.T * x + 1/2 * x.T * A * x 17 | 18 | 对纯二次函数: 19 | f = 1/2 * x.T * Q * x 20 | 其k_star = -1 * x'QQx/x'QQQx 21 | 22 | df(xp + kAxp)/dk = A(xp + kAxp)*Axp = AxpAxp + kAAxpAxp 23 | = xp'AAxp + kxp'AAAxp 24 | 25 | ''' 26 | 27 | ''' 28 | f = 1/2(x1 * x1 + 2x2 * x2) 29 | x0 = [4,4] 30 | k* = -5/9 31 | x1 = (16/9, -4/9) 32 | ''' 33 | def f1(): 34 | c = 0 35 | b = np.matrix('0;0') 36 | A = np.matrix('1, 0; 0,2') 37 | 38 | return (c, b, A) 39 | 40 | from newton_method import f_value 41 | from newton_method import solve_direct 42 | 43 | def optimal_grandient_for_f1(f,x0, epsilon): 44 | c,b,A = f() 45 | x = x0 46 | AA = A * A 47 | AAA = A * A * A 48 | f_deriv = A * x 49 | while True: 50 | #对纯二次函数,直接求解k的值,而不是用线性搜索方法。推导公式见上 51 | k = -1. * (x.T * AA * x) / (x.T * AAA * x) 52 | k = np.sum(k) 53 | x_n = x + k * f_deriv 54 | 55 | f_deriv_n = A * x_n 56 | 57 | if np.sum(np.abs(f_deriv_n)) < epsilon: 58 | break 59 | 60 | x = x_n 61 | f_deriv = f_deriv_n 62 | 63 | return x,f_value(f, x) 64 | 65 | 66 | from line_search import newton_search_for_quad 67 | from newton_method import newton_search_for_quad 68 | from newton_method import solve_direct 69 | 70 | if __name__ == "__main__": 71 | rs = solve_direct(f1) 72 | print "\nsolve_direct:", rs 73 | 74 | x0 = np.matrix('4;4') 75 | ors = optimal_grandient_for_f1(f1, x0, 0.01) 76 | print "\noptimal_grandient_for_f1:", ors 77 | 78 | nrs = newton_search_for_quad(f1, x0, 0.01) 79 | print "\nnewton_search_for_quad(f1):", nrs 80 | -------------------------------------------------------------------------------- /sample/sample_by_cvxopt.py: -------------------------------------------------------------------------------- 1 | from cvxopt import matrix, solvers 2 | 3 | import pdb 4 | 5 | ''' 6 | min 2*x1 + x2 7 | s.t -x1 + x2 <= 1 8 | x1 + x2 >= 2 9 | x1 - 2 x2 <= 4 10 | x2 >= 0 11 | ''' 12 | 13 | c = matrix([2.0, 1.0]) 14 | b = matrix([1.0, -2.0, 0.0, 4.0]) 15 | A = matrix([[-1.0, -1.0, 0.0, 1.0],[1.0, -1.0, 1.0, -2.0]]) 16 | 17 | sol = solvers.lp(c,A,b) 18 | 19 | print sol['x'] 20 | -------------------------------------------------------------------------------- /sample/sample_by_scipy.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.optimize import linprog 3 | import pdb 4 | 5 | ''' 6 | c = [-1., 4] 7 | minimize c.T * x 8 | s.t. [-3., 1].T * x <= 6 9 | [1,2.].T * x <= 4 10 | x[1] + x[2] = 10 11 | x[1] >= -3 12 | ''' 13 | c = np.array([-1, 4]) 14 | A = np.array([[-3, 1], [1,2]]) 15 | b = np.array([6,4]) 16 | 17 | A_eq = np.array([[1,1]]) 18 | b_eq = 6 19 | x0_bounds = (None, None) 20 | x1_bounds = (-3, None) 21 | 22 | res = linprog(c, A_ub=A, b_ub=b, A_eq=A_eq, b_eq=b_eq, bounds=(x0_bounds, x1_bounds),options={"disp": True}) 23 | 24 | pdb.set_trace() 25 | print res 26 | -------------------------------------------------------------------------------- /uncostrained_optimize.py: -------------------------------------------------------------------------------- 1 | #encoding: utf8 2 | 3 | import numpy as np 4 | import pdb 5 | 6 | ''' 7 | 1. 直接求解:对二次函数,直接求解 8 | x_star = A.inv * b 9 | 10 | 2. 最优梯度下降法 11 | 2.1. 给定起始点 12 | 2.2. 找到该方向的梯度 13 | 2.3. 沿负梯度方向,找到该方向最优值 (lambda 参数。) 14 | a. 一维搜索方法 15 | b. 对二次函数,如果A为正定矩阵,可以直接求解 16 | f = c + b.T * x + 1/2 * x.T * A * x 17 | 18 | 对纯二次函数: 19 | f = 1/2 * x.T * Q * x 20 | 其k_star = -1 * x'QQx/x'QQQx 21 | 22 | df(xp + kAxp)/dk = A(xp + kAxp)*Axp = AxpAxp + kAAxpAxp 23 | = xp'AAxp + kxp'AAAxp 24 | 25 | 3. 共轭梯度方向下降法 26 | 共轭方向法,开始用来求解 Ax=b方程组. 而在求解二次函数最优解时,其梯度函数为 Ax+b=0的解, 27 | 于是也用这个方法来求解二次函数的最优解。其它非二次的凸函数,则可以用二次函数来近似 28 | 29 | (x, Ay) = 0, 称x,y为共轭向量 (正交是共轭的特殊形式,A为单位阵) 30 | 3.1 找到n个共轭向量 ui 31 | 3.2 沿共轭向量方向进行最优搜索, 得到每次搜索的最优步长列表 lbi 32 | 3.3 得到最优点: 33 | x_star = x0 + sum(lbi * ui) 34 | 35 | 对非二次函数,可以这样逼近最优解 36 | ''' 37 | 38 | 39 | ''' 40 | f = 1/2(x1 * x1 + 2x2 * x2) 41 | x0 = [4,4] 42 | k* = -5/9 43 | x1 = (16/9, -4/9) 44 | ''' 45 | def f1(): 46 | c = 0 47 | b = np.matrix('0;0') 48 | A = np.matrix('1, 0; 0,2') 49 | 50 | return (c, b, A) 51 | 52 | from newton_method import f_value 53 | from newton_method import solve_direct 54 | 55 | def optimal_grandient_for_f1(f,x0, epsilon): 56 | c,b,A = f() 57 | x = x0 58 | AA = A * A 59 | AAA = A * A * A 60 | f_deriv = A * x 61 | while True: 62 | #对纯二次函数,直接求解k的值,而不是用线性搜索方法。推导公式见上 63 | k = -1. * (x.T * AA * x) / (x.T * AAA * x) 64 | k = np.sum(k) 65 | x_n = x + k * f_deriv 66 | 67 | f_deriv_n = A * x_n 68 | 69 | if np.sum(np.abs(f_deriv_n)) < epsilon: 70 | break 71 | 72 | x = x_n 73 | f_deriv = f_deriv_n 74 | 75 | return x,f_value(f, x) 76 | 77 | 78 | ''' 79 | f = 1 + x1 -x2 + x1**2 + 2x2**2 80 | u1 = [1,0] 81 | u2 = [0,1] 82 | x0 = [0,0] 83 | 84 | lambda1 = -1/2, lambda2 = 1/4 85 | ''' 86 | def f2(): 87 | c = 1. 88 | b = np.matrix('1.; -1.') 89 | A = np.matrix('2, 0; 0,4') 90 | 91 | return c, b, A 92 | 93 | from line_search import golden_section_search 94 | 95 | ''' 96 | 共轭方向法: 97 | 1. 使用黄金搜索找lambda 98 | ''' 99 | def conj_grandient_method_for_f2(): 100 | u1 = np.matrix('1.;0.') 101 | u2 = np.matrix('0.;1.') 102 | x0 = np.matrix('0.;0.') 103 | 104 | def_field = [-1,1] 105 | esplison = 0.005 106 | c,b, A = f2() 107 | 108 | ''' 109 | 线性搜索用的一次函数, 参数为k 110 | f = f(xi + kui) 111 | ''' 112 | k1 = golden_section_search(lambda k:f_value(f2, x0 + k*u1), def_field, esplison) 113 | x1 = x0 + k1[0] * x0 114 | 115 | k2 = golden_section_search(lambda k:f_value(f2, x1 + k*u2), def_field, esplison) 116 | x2 = x0 + k1[0] * u1 + k2[0] * u2 117 | 118 | return x2, f_value(f2, x2) 119 | 120 | ''' 121 | 共轭方向法: 122 | 2. 对二次函数直接求解lambda 123 | lamb_i+1 = (u(i+1), Ax0 + b) / (u(i+1), Au(u+1)) 124 | ''' 125 | def conj_grandient_method_for_f2_direct(): 126 | u1 = np.matrix('1.;0.') 127 | u2 = np.matrix('0.;1.') 128 | x0 = np.matrix('0.;0.') 129 | 130 | c,b, A = f2() 131 | lamb1 = -1. * (u1.T * (A*x0 + b))/(u1.T * (A*u1)) 132 | lamb2 = -1. * (u2.T * (A*x0 + b))/(u2.T * (A*u2)) 133 | 134 | x2 = x0 + lamb1[0,0] * u1 + lamb2[0,0] * u2 135 | 136 | return x2, f_value(f2, x2) 137 | 138 | 139 | def conj_f3(): 140 | A = np.matrix('1,1;1,2') 141 | c = 0 142 | b = np.matrix('0;0') 143 | 144 | return c,b,A 145 | 146 | ''' 147 | Fletcher_Reeves_conj 148 | 关于v0,v1,...vn共轭,最好推导一次 149 | x0, x1, ... 150 | v0, v1,.... 151 | xi = xi_1 + lambda * vi_1 152 | vi = -gi + ||gi||/||gi_1|| * vi_1 153 | 沿共轭方向求极小值: 154 | gi, 第xi点的梯度值 155 | 156 | example: 157 | 158 | f=1/2x.TAx 159 | A=[1,1;1,2] 160 | x0 = [10.;-5.] 161 | v0 = g0 162 | 163 | lamb0 = 0.75 164 | x1 = [1.25,-3.75] 165 | v1=[-4.36,3.75] 166 | lamb1 = 1.34 167 | 168 | x2 = [0.4, 0.01] 169 | 再迭代一次? 170 | 讲义上似乎算错了。有空算一下 171 | ''' 172 | def Fletcher_Reeves_conj(): 173 | f = conj_f3 174 | c,b,A = f() 175 | x0 = np.matrix('10.;-5.') 176 | g0 = A * x0 + b 177 | v0 = -g0 178 | 179 | #pdb.set_trace() 180 | lamb0, f_x0 = golden_section_search(lambda k:f_value(f, x0 + k*v0), [0,2], 0.001) 181 | 182 | x1 = x0 + lamb0 * v0 183 | g1 = A*x1 + b 184 | v1 = -g1 + np.dot(g1.T, g1)[0,0]/np.dot(g0.T, g0)[0,0] * v0 185 | lamb1, f_x1 = golden_section_search(lambda k:f_value(f, x1 + k*v1), [0,2], 0.001) 186 | x2 = x1 + lamb1 * v1 187 | return x2, f_x1 188 | 189 | ''' 190 | ''' 191 | def f_powell(): 192 | c = 0 193 | b = np.matrix('0.;0.') 194 | A = np.matrix('2,0;0,4') 195 | 196 | return c,b,A 197 | 198 | ''' 199 | 相比于fletcher算法,powell算不需要计算梯度。但需要有n个线性无关的初始向量, 200 | 201 | 1. 每一步的过程 202 | xi = xi_1 + lambda * vi_1, lambda线性搜索后的最小值 203 | vi --> vi_1 204 | xn-x0 --> vn 205 | u0 = xn-x0 206 | x0 = xn + lambda * (xn - x0), 为新的x0值 207 | 208 | 算法本身所需要的步数,并不比fletcher小 209 | 210 | 2. 重复上述步骤,直到收敛 211 | 留意下收敛条件:如 ||xi - xi_1|| < espilon, |fi - fi_1| < esplilon, max_steps 212 | 213 | 214 | 这种产生共轭向量的方法,并没有推导,只有实现。最好去推一下 215 | 216 | 217 | 这两个算法,和DFP/BFGS关系密切。具体参考 newton算法相关内容 218 | 219 | ''' 220 | def powell_conj(): 221 | ''' 222 | u1=[-11.14, -24.46] 223 | u2=[-1.8, -0.28] 224 | ''' 225 | x0 = np.matrix('20.;20.') 226 | #v1,v2线性无关 227 | v = np.matrix('1.,1.;-1.,1.') 228 | 229 | c,b,A = f_powell() 230 | u = np.matrix('0.,0.;0.,0.') 231 | lamb = np.matrix('0.;0.') 232 | 233 | id = 0 234 | total = 0 235 | while total < 3: 236 | k,min_fk = golden_section_search(lambda k:f_value(f_powell, x0 + k*v[:,0]), [-100., 100], 0.001) 237 | x1 = x0 + k * v[:,0] 238 | 239 | k,min_fk = golden_section_search(lambda k:f_value(f_powell, x1 + k*v[:,1]), [-100., 100], 0.001) 240 | x2 = x1 + k * v[:,1] 241 | 242 | #找到u向量 243 | u[:,id] = x2 - x0 244 | k,min_fk = golden_section_search(lambda k:f_value(f_powell, x2 + k*u[:, id]), [-100., 100], 0.001) 245 | 246 | x0 = x2 + k*u[:,id] 247 | v[:,0] = v[:,1] 248 | v[:,1] = u[:,id] 249 | 250 | id = (id+1) % len(lamb) 251 | total += 1 252 | 253 | conj = u[:,0].T * A * u[:,1] 254 | #print "conj: ", conj 255 | 256 | x_star = x0 257 | 258 | return x_star, f_value(f_powell, x_star) 259 | 260 | from line_search import newton_search_for_quad 261 | 262 | from newton_method import newton_search_for_quad 263 | 264 | if __name__ == "__main__": 265 | rs = solve_direct(f1) 266 | print "\nsolve_direct:", rs 267 | 268 | x0 = np.matrix('4;4') 269 | ors = optimal_grandient_for_f1(f1, x0, 0.01) 270 | print "\noptimal_grandient_for_f1:", ors 271 | 272 | nrs = newton_search_for_quad(f1, x0, 0.01) 273 | print "\nnewton_search_for_quad(f1):", nrs 274 | 275 | conj_rst = conj_grandient_method_for_f2() 276 | print "\nconj_grandient_method_for_f2:", conj_rst 277 | 278 | conj_rst = conj_grandient_method_for_f2_direct() 279 | 280 | print "\nconj_grandient_method_for_f2_direct:", conj_rst 281 | 282 | nrs = newton_search_for_quad(f2, x0, 0.01) 283 | print "\nnewton_search_for_quad(f2):", nrs 284 | 285 | rs = solve_direct(f2) 286 | print "\nsolve_direct:", rs 287 | 288 | frs = Fletcher_Reeves_conj() 289 | print "Fletcher_Reeves_conj.\nexpect: x2 = [0.4, 0.01]. \nReal:", frs 290 | 291 | frs = powell_conj() 292 | print "Fletcher_Reeves_conj.\nexpect: x2 = [0.4, 0.01]. \nReal:", frs 293 | --------------------------------------------------------------------------------