예제 #1
0
    def __init__(self, vocab_size, wordvec_size, hidden_size):
        V, D, H = vocab_size, wordvec_size, hidden_size
        #rn = np.radom.randn

        # 重みの初期化
        embed_W = (rn(V, D) / 100).astype('f')
        rnn_Wx = (rn(D, H) / np.sqrt(D)).astype('f')
        rnn_Wh = (rn(H, H) / np.sqrt(H)).astype('f')
        rnn_b = np.zeros(H).astype('f')
        affine_W = (rn(H, V) / np.sqrt(H)).astype('f')
        affine_b = np.zeros(V).astype('f')

        # レイヤの生成
        self.layers = [
            TimeEmbedding(embed_W),
            TimeRNN(rnn_Wx, rnn_Wh, rnn_b, stateful=True),
            TimeAffine(affine_W, affine_b)
        ]
        self.loss_layer = TimeSoftmaxWithLoss()
        self.rnn_layer = self.layers[1]

        self.params, self.grads = [], []
        for layer in self.layers:
            self.params += layer.params
            self.grads += layer.grads
def animate(i):
    global x, y, vx, vy, dr, con, j, vx_temp, vy_temp
    vx_temp, vy_temp = [], []
    dr = dr_slider.val
    #vx += ((rn(n)-.5)*noise_slider.val)*5
    #vy += ((rn(n)-.5)*noise_slider.val)*5
    for j in range(n):
        con = ((x < x[j] + dr) & (x > x[j] - dr) & (y < y[j] + dr) &
               (y > y[j] - dr))  #it indicates if there is someone near or not
        if sum(con) != 0:
            vx_temp.append(
                sum(con * vx) / sum(con) + (rn() - .5) * noise_slider.val)
            vy_temp.append(
                sum(con * vy) / sum(con) + (rn() - .5) * noise_slider.val)
        else:
            vx_temp.append(vx[j] + (rn() - .5) / 10)
            vy_temp.append(vy[j] + (rn() - .5) / 10)
    vx = np.array(vx_temp.copy())
    vy = np.array(vy_temp.copy())

    x = (x + vx * dt) % w  #+(rn(n)-.5)*noise_slider.val
    y = (y + vy * dt) % w  #+(np.sin(rn(n))-.5)/10

    line.set_xdata(x)
    line.set_ydata(y)

    return line,
예제 #3
0
    def nuevo(self, old, oldE):
        # genero nuevo
        new = self.sampleador.rvs()  # rn(8) * intervalo + cotas[:,0]
        self.generados += 1

        # cambio de error
        newE = self.etotalExt(new)
        deltaE = newE - oldE

        if deltaE < 0:
            self.gradPos += 1
            print("Gradiente Positivo")
            print(self.generados, self.gradPos, self.gradNeg, self.mismo)
            return new, newE  # tiene menor error, listo
        else:
            # nueva opoertunidad, sampleo contra rand
            pb = np.exp(-deltaE / 2)

            if pb > rn():
                self.gradNeg += 1
                print("Gradiente Negativo, pb=", pb)
                print(self.generados, self.gradPos, self.gradNeg, self.mismo)
                return new, newE  # aceptado a la segunda oportunidad
            else:
                #            # vuelvo recursivamente al paso2 hasta aceptar
                #            print('rechazado, pb=', pb)
                #            new, newE = nuevo(old, oldE)
                self.mismo += 1
                print("Mismo punto,        pb=", pb)
                print(self.generados, self.gradPos, self.gradNeg, self.mismo)
                return old, oldE

        return new, newE
예제 #4
0
def result():
    
    garr = CArray()
    bias = rn()
    
    x = request.values.get('lifex')
    y = request.values.get('lifey')
    lifeformx = request.values.get('lifeformx')
    lifeformy = request.values.get('lifeformy')
    nbx = request.values.get('nbx')
    nby = request.values.get('nby')
    n0x = request.values.get('n0x')
    n0y = request.values.get('n0y')
    fcx = request.values.get('fcx')
    fcy = request.values.get('fcy')
    pax = request.values.get('pax')
    pay = request.values.get('pay')

    

    resultlifeform = [lifeformx, lifeformy][int(bias)]

    garr = CArray(nbx, nby)
    nb = garr.get(bias)

    garr = CArray(n0x, n0y)
    n0 = garr.get(bias)

    garr = CArray(fcx, fcy)
    fc = garr.get(bias)

    garr = CArray(x, y)
    resultlife = garr.get(bias)

    garr = CArray(pax, pay)
    pa = garr.get(bias)

    formula = lambda a,b,c,d : a*c*d/b

    timeFormula = lambda x,a,b,c,d : formula(a,b,c,d)*x

    resultingTime = float(0)

    while(timeFormula(resultingTime,nb,n0,fc,pa)<0.5):
        resultingTime+=0.01

    arr = [int("1") for i in range(int(resultlife))]+[int("0") for i in range(100-int(resultlife))]
    populated = False
    if numpy.random.choice(arr):
        populated = True

    data = {"Nb":nb, "N0":n0, "Fc":fc, "Pa":pa, "Time":resultingTime, "LifeProb":resultlife, "LifeForm":resultlifeform, "LifeExpect":formula(nb, n0, fc, pa), "Populated":populated}

    return jsonify(data)
예제 #5
0
def set_camera_pose(dim_height, dim_width, camera_pose, camera_deg):
    """Set up the camera pose, potentially applying domain randomization.

    Defaults for the top-down view are 0.5, 0.5, and 1.5 for x, y, and z,
    respectively.  Defaults for rotations are 0 (radians) for all three angles.
    I think yaw, pitch, and roll but the ordering can be determined by testing
    values, e.g.: https://github.com/BerkeleyAutomation/gym-cloth/issues/28.
    """
    # Select the camera and make it the active object so that we can manipulate it
    bpy.data.objects['Camera'].select = True
    bpy.context.scene.objects.active = bpy.data.objects['Camera']

    # https://blender.stackexchange.com/questions/86233/blender-resizing-my-image-in-half
    bpy.data.scenes['Scene'].render.resolution_percentage = 100.0
    bpy.context.scene.render.resolution_x = dim_width
    bpy.context.scene.render.resolution_y = dim_height

    # Ryan: fixed DR
    if ADD_DOM_RAND:
        cp = [float(i) for i in camera_pose.split(",")]
        cd = [float(i) for i in camera_deg.split(",")]
    else:
        cp = [rn(0., scale=EPS), rn(0., scale=EPS), rn(0., scale=EPS)]
        cd = [rn(0., scale=EPS), rn(0., scale=EPS), rn(0., scale=EPS)]
    # Set the x, y and z location (Top-down view). Daniel: height was 1.5 but let's do 1.45.

    bpy.context.object.location[0] = 0.5 + cp[0]
    bpy.context.object.location[1] = 0.5 + cp[1]
    bpy.context.object.location[2] = 1.45 + cp[2]

    # Set the x, y and z rotation (Top-down view).
    bpy.context.object.rotation_euler[0] = DEG_TO_RAD * (0 + cd[0])
    bpy.context.object.rotation_euler[1] = DEG_TO_RAD * (0 + cd[1])
    bpy.context.object.rotation_euler[2] = DEG_TO_RAD * (0 + cd[2])
예제 #6
0
def nuevo(oldInt, oldExt, oldErr, retPb=False):
    global generados
    global gradPos
    global gradNeg
    global mismo
    global sampleador

    # genero nuevo
    newInt = sampleadorInt.rvs()  # rn(8) * intervalo + cotas[:,0]
    newExt = sampleadorExt.rvs()
    generados += 1

    # cambio de error
    newErr = etotal(newInt, Ns, newExt, params)
    deltaErr = newErr - oldErr

    if deltaErr < 0:
        gradPos += 1
        print(generados, gradPos, gradNeg, mismo, "Gradiente Positivo")
        if retPb:
            return newInt, newExt, newErr, 1.0
        return newInt, newExt, newErr  # tiene menor error, listo
    else:
        # nueva oportunidad, sampleo contra rand
        pb = np.exp(-deltaErr / 2)

        if pb > rn():
            gradNeg += 1
            print(generados, gradPos, gradNeg, mismo,
                  "Gradiente Negativo, pb=", pb)
            if retPb:
                return newInt, newExt, newErr, pb
            return newInt, newExt, newErr  # aceptado a la segunda oportunidad
        else:
            #            # vuelvo recursivamente al paso2 hasta aceptar
            #            print('rechazado, pb=', pb)
            #            new, newE = nuevo(old, oldE)
            mismo += 1
            print(generados, gradPos, gradNeg, mismo,
                  "Mismo punto,        pb=", pb)
            if retPb:
                return oldInt, oldExt, oldErr, pb
            return oldInt, oldExt, oldErr
예제 #7
0
def nuevo(oldInt, oldExt, oldErr, retPb=False):
    global generados
    global gradPos
    global gradNeg
    global mismo
    global sampleador

    # genero nuevo
    newInt = sampleadorInt.rvs() # rn(8) * intervalo + cotas[:,0]
    newExt = sampleadorExt.rvs()
    generados += 1

    # cambio de error
    newErr = etotal(newInt, Ns, newExt, params)
    deltaErr = newErr - oldErr

    if deltaErr < 0:
        gradPos += 1
        print(generados, gradPos, gradNeg, mismo, "Gradiente Positivo")
        if retPb:
            return newInt, newExt, newErr, 1.0
        return newInt, newExt, newErr # tiene menor error, listo
    else:
        # nueva oportunidad, sampleo contra rand
        pb = np.exp(- deltaErr / 2)

        if pb > rn():
            gradNeg += 1
            print(generados, gradPos, gradNeg, mismo, "Gradiente Negativo, pb=", pb)
            if retPb:
                return newInt, newExt, newErr, pb
            return newInt, newExt, newErr  # aceptado a la segunda oportunidad
        else:
#            # vuelvo recursivamente al paso2 hasta aceptar
#            print('rechazado, pb=', pb)
#            new, newE = nuevo(old, oldE)
            mismo +=1
            print(generados, gradPos, gradNeg, mismo, "Mismo punto,        pb=", pb)
            if retPb:
                return oldInt, oldExt, oldErr, pb
            return oldInt, oldExt, oldErr
예제 #8
0
def nuevo(old, oldE):
    global generados
    global gradPos
    global gradNeg
    global mismo
    global sampleador

    # genero nuevo
    new = sampleador.rvs()  # rn(8) * intervalo + cotas[:,0]
    generados += 1

    # cambio de error
    newE = etotal(new, Ns, XextList, params)
    deltaE = newE - oldE

    if deltaE < 0:
        gradPos += 1
        print("Gradiente Positivo")
        print(generados, gradPos, gradNeg, mismo)
        return new, newE  # tiene menor error, listo
    else:
        # nueva opoertunidad, sampleo contra rand
        pb = np.exp(-deltaE / 2)

        if pb > rn():
            gradNeg += 1
            print("Gradiente Negativo, pb=", pb)
            print(generados, gradPos, gradNeg, mismo)
            return new, newE  # aceptado a la segunda oportunidad
        else:
            #            # vuelvo recursivamente al paso2 hasta aceptar
            #            print('rechazado, pb=', pb)
            #            new, newE = nuevo(old, oldE)
            mismo += 1
            print("Mismo punto,        pb=", pb)
            print(generados, gradPos, gradNeg, mismo)
            return old, oldE

    return new, newE
예제 #9
0
def nuevo(old, oldE):
    global generados
    global gradPos
    global gradNeg
    global mismo
    global sampleador

    # genero nuevo
    new = sampleador.rvs() # rn(8) * intervalo + cotas[:,0]
    generados += 1

    # cambio de error
    newE = etotal(new, Ns, XextList, params)
    deltaE = newE - oldE

    if deltaE < 0:
        gradPos += 1
        print("Gradiente Positivo")
        print(generados, gradPos, gradNeg, mismo)
        return new, newE # tiene menor error, listo
    else:
        # nueva opoertunidad, sampleo contra rand
        pb = np.exp(- deltaE / 2)

        if pb > rn():
            gradNeg += 1
            print("Gradiente Negativo, pb=", pb)
            print(generados, gradPos, gradNeg, mismo)
            return new, newE # aceptado a la segunda oportunidad
        else:
#            # vuelvo recursivamente al paso2 hasta aceptar
#            print('rechazado, pb=', pb)
#            new, newE = nuevo(old, oldE)
            mismo +=1
            print("Mismo punto,        pb=", pb)
            print(generados, gradPos, gradNeg, mismo)
            return old, oldE

    return new, newE
예제 #10
0
first_row = ['W_speed', 'S1', 'S2', 'S3', 'waveX', 'waveY']
guardar = input('Do you want to save? [(S)/N]\t\t')
# guardar='n'
if guardar.lower() != 'n':
    print('\t\tGuardando...')
    import os.path
    if os.path.exists(file_name) == False:
        with open(file_name, 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(first_row)
else:
    print(first_row)

for i in range(num_valores):
    if change_speed == True:
        speed = rn(10, 25)
    activation = []
    control = []
    continuar = True
    if num_valores == 1:
        x, y = 450, 250
    else:
        x = rn(screen[0] * 2 / 3, screen[0])
        y = rn(screen[1] / 2, screen[1])
    radio = 0
    for comparate in range(10 * speed):
        radio += 1 * speed
        cont = 0
        for sensor in positions.values():
            cont += 1
            distance = int(np.sqrt((x - sensor[0])**2 + (y - sensor[1])**2))
예제 #11
0
# import statements
import datetime as dt
import pandas as pd
from numpy.random import randn as rn

# initialization
start_date = dt.datetime(2015,1,1).date()
end_date = dt.datetime(2015,12,31).date()
no_of_days = (end_date - start_date).days + 1

# build date collection
dates = [(start_date + dt.timedelta(days = i)).isoformat() for i in range(no_of_days) if not (start_date + dt.timedelta(days = i)).isoweekday() in [6,7]]

# build random numbers series
randoms = rn(len(dates))
random_series = pd.Series(randoms, name = "random_number")


# create data frame
df = pd.DataFrame({"Date": dates})

# join the series and data frame to build the desired output
df = df.join(random_series)
df.set_index("Date", inplace=True)
print(df)
예제 #12
0
import pandas as pd
import numpy as np
from pathlib import Path

my_path = Path('C:\\Users\\proy\\OneDrive - Tractor Supply Co\\PRAT_TSC\\MISC\\PYTHON'
               '\\Krish_Naik\\materials\\files\\')
print(my_path)

from numpy.random import randn as rn  # function generate random data
# numpy only understand array or matrix
print(rn(5, 4))

np.random.seed(100)  # by setting seed, for same seed , it will generate same set of random data
r = rn(5, 4)
print(r)

pd.DataFrame(r)  # convert matrix to dataframe

# passing list variable as row and column names

row = ['a', 'b', 'c', 'd', 'e']
column = ['p', 'q', 'r', 's']

pd.DataFrame(r, index=row, columns=column)

df = pd.DataFrame(r, index=row, columns=column)
df[['p']]

df['new'] = df['p'] + df['s']
df
df.drop('p')  # not found in Axis, by default axis = 0