Implement various optimization algorithms of python

The python video tutorial section introduces various optimization algorithms

Related free learning recommendations: python video tutorial

Dichotomy
function see rres, this code makes the algorithm run twice

def asdf(x):

    rres=8*x**3-2*x**2-7*x+3

    return rres

 

i=2

left=0

right=1

while i>0 :

    i = i-1

    ans = 0.1

    mid1 = (left + right + ans) / 2

    mid2 = (left + right - ans) / 2

    a=asdf(mid1)

    c=asdf(mid2)

    if a > c :

        right = mid1

    else :

        left = mid2

b=(left+right) / 2

print("左极限=%s,右极限=%s,极小值x=%s"%(left,right,b))
左极限=0.45,右极限=0.775,极小值x=0.6125

Harvest:
This is the first code I implemented. After learning the algorithm, the logical framework is basically there, and what remains to be clear is the corresponding python language. So I started looking for "how to define a function" (see mofan's Youku), "loop body" and "if conditional statement" format (https://blog.csdn.net/qq_39407518/article/details/79822498) "Mathematics symbols" (see mofan's Youku for details), and the use of print

1. Def is the definition of the middle finger of python, which is generally used to define functions. If you need deep learning to build a network, it can be used to define the network. It is worth noting that

The return must be added after the function to start a new line.

I don't know why, but if it is not added, the function formula is a vase, just like a result cannot be input.

2. The worst thing is logic. In the beginning, the logic was not clear, or there was an omission in the code, which led me to put left and right in the loop body, and the result can be imagined. But also because of this error, I know how to use debug in pycharm. It's very simple. Baidu came out in one click.

3. I don't know the reason. The multiple variables of print in the Mofan video can not be used in my pycharm. The result is very strange. Maybe it's because I am win10 and not ios. print If multiple variables are output together, it must be print ("name: %s, name 2: %s"% (a, b)) and the result output is name: a, name 2: b

Question: 1. Why add return?
Return means to output any variable value in this def as the result display. Generally speaking, it is the naming of the relational expression of the output function, so that when you call this function, the function value corresponding to the variable can be displayed, otherwise it will only run without results and will not have any effect.

Grid-point method-three-point equal division method

import numpy as np

def qwer(x):

    third = np.exp(x) - 5*x

    return third

 

left = 1

right = 2

mid1 =float(left+right) / 2

mid2 = (left+mid1) / 2

mid3 = (mid1+right) /2

a = qwer(mid1)

b = qwer(mid2)

c = qwer(mid3)

i = 5

while i > 0:

    i=i-1

    if a > b:

        if c > b :

            #b

            right = mid1

            mid1 = mid2

            a=b

            mid2 = (left + mid1) / 2

            mid3 = (mid1 + right) / 2

            b = qwer(mid2)

            c = qwer(mid3)

        else:#b>c

            #c

            left = mid1

            mid1 = mid3

            a = c

            mid2 = (left + mid1) / 2

            mid3 = (mid1 + right) / 2

            b = qwer(mid2)

            c = qwer(mid3)

    else:#b>a

            if a > c:

                #C

                left = mid1

                mid1 = mid3

                a = c

                mid2 = (left + mid1) / 2

                mid3 = (mid1 + right) / 2

                b = qwer(mid2)

                c = qwer(mid3)

            else:#b>a&c>a

                # a

                left = mid2

                right = mid3

                mid2 = (left + mid1) / 2

                mid3 = (mid1 + right) / 2

                b = qwer(mid2)

                c = qwer(mid3)

 

print("最小值=%s"%mid1)

print("函数值=%s"%a)
最小值=1.609375

函数值=-3.047189552275773

About data variables in python. The results of the first run were obviously wrong, so I used debug. It turns out that mid1 is always 1 instead of 1.5, so I started to understand the data variables. At first I guessed that python defaults to all variables as integers, but according to the result of the dichotomy, I realized that this guess was wrong, so there is no need to change the variable format of the entire file. So I added a float in front of the mid1 formula, and the result was 1.5. But if I enclose the whole formula with () and add float before it, the result is still 1. I don't quite understand why. But I know that the python data format is determined by the input, that is to say, if your input is an integer, then the directly related calculation output must be an integer, and the integer is still not used. Before I did not use the two methods +float/+.0, mid1~3 were all integers.

left = 1.0

right = 2.0

mid1 =(left+right) / 2

Or no longer add float in front of mid1, just click a dot behind the input amount.
I really want to spit out the print, it's so troublesome, ah, ah, every time I have to get %s, and sometimes I can’t put them together! ! ! !

Fibonacci method

def fibonacci(n):

    i=0

    a = 0

    b = 1

    for i in range(n):

        i=i+1

        c = a+b

        a = b

        b = c

    return c

def bn(x):

    ert = x**2 - 6*x + 2

    return ert

z = 2

p = 0

left = 0.00000

right = 10.00000

L1 = right - left

while z < 100:

    m = fibonacci(z)

    l = L1/m

    k = 1.000/m

    if k < 0.03:

        print("n=%s,Fn=%s"%(z,m))

        L2 = l*fibonacci(z-1)

        t = left + L2

        r = right -L2

        while p < 3:

            p = p + 1

            l3 = t - r

            e= bn(t)

            o = bn(r)

            if e>o :

                right = t

                t = r

                r = left + l3

            else:#o>e

                left = r

                r = t

                t = right - l3

        break

    else:

        z = z + 1

 

okk=(left+right)/2

okky=bn(okk)

print(left)

print(right)

print("极小值x=",okk)

print("极小值y=",okky)

Don't ask what I have mastered, ask how much I love the accuracy of python after writing this code now:-) I decided to add a lot of 0
fibonacci after the small mathematical points of the input amount as long as I write the code of the mathematical formula in the future Function definition, my hands are shaking every time after debugging O(∩_∩)O~

Golden section

def gold(x):

    gg= x**2 - 6*x + 9

    return gg

 

left = 1

right = 7

ans = 0.4

a = left + 0.618 * (right - left)

b = left + 0.382*(right - left)

gga = gold(a)

ggb = gold(b)

i = 0

while i < 7:

    print("i=%s" % i)

    print("left=%s,right=%s" % (left, right))

    print("x左=%s,x右=%s" % (a, b))

    print("y左=%s,y右=%s" % (ggb, gga))

    c = right - left

    if c > 0.4:

        i = i + 1

        if gga > ggb:

            right = a

            a = b

            b = left + 0.382*(right - left)

            gga = ggb

            ggb = gold(b)

        else:#gga
            left = b

            b = a

            a = left + 0.618 * (right - left)

            ggb = gga

            gga = gold(a)

    else:

        break

I don't know when I have obsessive-compulsive disorder. As long as there is a "~" under the code, I must eliminate it. Laugh and cry. This is very simple. The first four are very simple except Fibonacci.

Indirect method-quadratic interpolation

def yy(x):

    y=x**4-4*x**3-6*x**2-16*x+4

    return y

 

def xing(xm1,xm2,xm3,fm1,fm2,fm3):

    yxxx=0.5000*((xm2**2-xm3**2)*fm1+(xm3**2-xm1**2)*fm2+(xm1**2-xm2**2)*fm3)/((xm2-xm3)*fm1+(xm3-xm1)*fm2+(xm1-xm2)*fm3)

    return yxxx

 

x1 = -1.0000

f1 = yy(x1)

x3 = 6

f3 = yy(x3)

x2 = 0.50000*(x1+x3)

f2 = yy(x2)

xp = xing(x1,x2,x3,f1,f2,f3)

fp = yy(xp)

a = abs(xp-x2)

while abs(xp-x2) > 0.05000:

    a = abs(xp - x2)

    if xp > x2:

        if fp > f2:

            x3=xp

            f3=fp

            xp = xing(x1, x2, x3, f1, f2, f3)

            fp = yy(xp)

            print("ans=%s" % a)

            print("left=%s,right=%s" % (x1, x3))

            print("x*=%s,fp*=%s" % (xp, fp))

            print("x2=%s,f2=%s" % (x2, f2))

            print("******************")

        else:#f2>fp

            x1 = x2

            f1 = f2

            x2 = xp

            f2 = fp

            xp = xing(x1, x2, x3, f1, f2, f3)

            fp = yy(xp)

            print("ans=%s" % a)

            print("left=%s,right=%s" % (x1, x3))

            print("x*=%s,fp*=%s" % (xp, fp))

            print("x2=%s,f2=%s" % (x2, f2))

            print("******************")

    else:#xp
        if fp > f2:

            x1 = xp

            f1 = fp

            xp = xing(x1, x2, x3, f1, f2, f3)

            fp = yy(xp)

            print("ans=%s" % a)

            print("left=%s,right=%s" % (x1, x3))

            print("x*=%s,fp*=%s" % (xp, fp))

            print("x2=%s,f2=%s" % (x2, f2))

            print("******************")

        else:

            x3 = x2

            f3 = f2

            x2 = xp

            f2 = fp

            xp = xing(x1, x2, x3, f1, f2, f3)

            fp = yy(xp)

            print("ans=%s" % a)

            print("left=%s,right=%s" % (x1, x3))

            print("x*=%s,fp*=%s" % (xp, fp))

            print("x2=%s,f2=%s" % (x2, f2))

            print("******************")

This formula seems very troublesome, so be careful when writing it. I put the 2 under the semicolon last time, the result is very big, so it is better to convert to 0.5 (PS: don't forget the long river of 0).
Although the code is very long, it is mainly because of too much print. I planned to print at the beginning, but the final result will miss the last part. I'm too lazy to think of other ways, just do it

Indirect method-Newton method

def fd(x):

    y = 4*x**3-12*x**2-12*x-16

    return y

def fdd(x):

    ys = 12*x**2-24*x-12

    return ys

 

i = 1

x0 = 3.00000

ans = 0.001

while i < 7:

    fd0 = fd(x0)

    fdd0 = fdd(x0)

    if abs(fd0) > ans:

        x1 = x0 - (fd0/fdd0)

        x0 = x1

        print("次数:%s,所得的值x:%s"%(i,x1))

        i = i + 1

    else:#fd0<0.001

        print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")

        print("Bingo!顺利通关!祝您开学愉快!")

        print("Boss  X=%s"%x0)

        break

In the beginning, the "written" in while caused the run not to come out. Then, debug is useless. I checked it online and found out that "no internet connection" + "no breakpoint selected". Finally, I wanted to try to output the content in the else, but found that the screen was swiped after the run. So after changing to i<7, it still doesn't work, so I thought of adding a break to jump out of the loop, and it worked.
Then I just got a debug and found out that i+1 is in if, because there is no way to +1, so i=6 always exists, and it keeps looping. It’s okay to add break or i+1.

Just an hour and a half ago, I successfully completed the optimization of the six major codes, pure hands, no external force. Happy!
This is my first set of python codes that I have implemented by myself, which is to assemble mathematical formulas in python language. At the beginning, I knew what I needed to reflect in the language, but I was not quite clear. So I found a few dichotomy on the Internet, they are all different, but the framework is similar, but if we want to use the formula we need to change a lot. Then I began to analyze our problem, and I found that roughly two parts are needed, one part function definition, and one loop body. But I don't know how to define functions, how to write mathematical formulas, how to make variables, which means that some small points are not very good, so I choose to Baidu directly. Because I know that I am good at reading, I am better at getting the main points through reading than extracting elements from videos. Purposely find knowledge points, and grasp more firmly.
So I started the first one-the dichotomy. I found that I have made a lot of mistakes and many of them are very basic. But I still did not choose the video, but directly looked for these questions on Baidu, because after the video, you may not find a point. Of course, this is done step by step, instead of just putting the program up and changing it bit by bit.
With the success of the first two, I found myself confident in these codes, seeming to see through their disguise and grasp the essence. In addition, I also realize that my learning ability seems to have improved a lot since August, and I have a more effective learning method. There is a certain awakening in all aspects. Except for the first one I found a few wrong codes, the others are written according to my own logic. After the logic is passed, I don’t know how to translate a certain part of the corresponding language and go to Baidu. In fact, these routines are the same or Said that the routines of mathematical formula transformation are the same.
I also realized that assembly is actually the most difficult language. What I have learned so far is that many of them need to be defined by themselves, they need to remember a lot of instructions and cannot be flexible. But for others, just write down some corresponding ones. Python is really simple. Moreover, I found that I seem to have opened the door to a new world today. I fell in love with this spiritual thing, full of rigorous beauty, and the unknown changes. I found that I seemed to fall in love with code. It may not be limited to python, these languages ​​are full of challenges. I think when you are in doubt, you need to trust your intuition, at least I found it to be accurate.
This article comes from php Chinese website: python video tutorial section https://www.php.cn/course/list/30.html

Guess you like

Origin blog.csdn.net/Anna_xuan/article/details/110878491