コード例 #1
0
 def mutation(self,probability):
     #randomly swap two tuples from sequence
     r = random.random()
     if r > probability:
         idx = range(len(self.perm))
         i1, i2 = random.sample(idx, 2)
         self.perm[i1], self.perm[i2] = self.perm[i2], self.perm[i1]
コード例 #2
0
def n_images_from_dir(path, num):
    file_images = {}
    for f in os.listdir(path):
        if os.path.isdir(path + f):
            for r, d, fil in os.walk(path + f):
                idxs = random.sample(range(0, len(fil)), num)
                random_imgs = []
                for idx in idxs:
                    random_imgs.append(fil[idx])
                file_images[f] = random_imgs
    return file_images
コード例 #3
0
ファイル: states.py プロジェクト: Mechachleopteryx/qca
def rand_n(L, config):
    csplit = config.split('_')
    ns = csplit[0]
    nssplit = ns.split('-')
    n = int(nssplit[0])
    if len(nssplit) > 1:
        s = int(nssplit[1]) * L * n
    else:
        s = None
    random.seed(s)
    fock_config = '-'.join([str(i) for i in random.sample(range(L), n)])
    if len(csplit) > 1:
        config = csplit[1:]
        fock_config = ''.join([fock_config, config])
    return fock(L, fock_config)
コード例 #4
0
    def orderedCrossover(self, ind2):
        """Executes an ordered crossover (OX) on the input
        individuals. The two individuals are modified in place. This crossover
        expects :term:`sequence` individuals of indices, the result for any other
        type of individuals is unpredictable.
        :param self: The first individual participating in the crossover.
        :param ind2: The second individual participating in the crossover.
        :returns: A tuple of two individuals.
        Moreover, this crossover generates holes in the input
        individuals. A hole is created when an attribute of an individual is
        between the two crossover points of the other individual. Then it rotates
        the element so that all holes are between the crossover points and fills
        them with the removed elements in order.
        """
        size = len(self.perm)
        a, b = random.sample(range(size), 2)
        if a > b:
            a, b = b, a

        newPerm1 = [0] * size
        newPerm2 = [0] * size
        for i in range(a,b+1):
            newPerm1[i]=self.perm[i] #cut part from 1st parent
            newPerm2[i]=ind2.perm[i] #cut part from 2nd parent
        i=(b+1)%size
        while 0 in newPerm1:
            oldi=i
            while (ind2.perm[i] in newPerm1):
                i = (i + 1) % size
            newPerm1[oldi]=ind2.perm[i]
            i=(oldi+1)%size
        i = (b + 1)%size

        while 0 in newPerm2:
            oldi = i
            while (self.perm[i] in newPerm2):

                i = (i + 1) % size
            newPerm2[oldi] = self.perm[i]
            i = (oldi + 1) % size

        return Individual(size,newPerm1),Individual(size,newPerm2)
コード例 #5
0
def str2mat(instr, limit=5, placeholder=None):
    '''
    Convert string to a vector base on average vector of the composing words.
    instr: the inpput string
    placeholder: for the non-vocabularies
    '''
    # make a place-holder: mean of three strange words
    mystr = trim_string(instr)
    # number of words
    L = min(len(mystr), limit)
    ## padding up
    sheet = np.ones((300, limit)) * 2
    for l in range(L):
        if (mystr[l] in vocab):
            sheet[:, l] = c_dict[mystr[l]]
        else:
            ph = np.ones(300) * 1
            ph[random.sample(list(np.arange(300)), 20)] = -3
            sheet[:, l] = ph
    return L, sheet
コード例 #6
0
def main():
    from recommend.data.datasets import load_100k
    import random
    # 数据集处理
    df = load_100k(type='pd').alldata
    nums_train = 10
    df = df.groupby('user_id').filter(lambda x: len(x) >= nums_train + 10)
    data_train = []
    data_test = []
    for gb, dtfm in df.groupby('user_id'):
        dtfm = dtfm.reset_index(drop=True)  # 去除原索引
        index_sample = random.sample(range(len(dtfm)), nums_train)
        data_train.append(dtfm.iloc[index_sample, :])
        data_test.append(dtfm.drop(index_sample))
    data_train = pd.concat(data_train)
    data_test = pd.concat(data_test)
    x_train = np.array(data_train[['user_id', 'item_id', 'timestamp']])
    y_train = np.array(data_train['rating'])
    x_test = np.array(data_test[['user_id', 'item_id', 'timestamp']])
    y_test = np.array(data_test['rating'])

    lrmf = ListRankMF(0.01, 10, 0.01, 800)
    lrmf.fit(x_train, y_train, evals=(x_test, y_test), top=10)
コード例 #7
0
  Mouse2.mouseClock = core.Clock()
  
  #initialize variables for loops and array manipulation and keeping track of users incorrect inputs
  wrongCounter=0
  looper=0
  
  # Create some handy timers
  globalClock = core.Clock()  # to track the time since experiment started
  routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine 
 
  #used as index for arrays and matrixes while keeping track of how many stimuli have been displayed for training and testing
  looper=0
  
  #generate random order for each run through of training 
  random.seed()
  order_list=random.sample(range(0, n_stims), n_stims)
  
  #resize matrix 
  new_col = data_matrix.sum(1)[...,None] 
  new_col.shape
  all_data = np.append(data_matrix, new_col, 1)
  all_data.shape
  data_matrix=all_data
  #resize matrix 
  new_col = data_matrix.sum(1)[...,None] 
  new_col.shape
  all_data = np.append(data_matrix, new_col, 1)
  all_data.shape
  data_matrix=all_data
  #resize matrix 
  #new_col = data_matrix.sum(1)[...,None] 
コード例 #8
0
ファイル: n400.py プロジェクト: irfanmustafas/Brainlock
#for i in range(len(knownA)):
#    if i % 2 == 0:
#        acrL[i]=knownA[i]
#    else:
#        acrL[i]=unknownA[i]
######

#acrL=range(len(knownA))

####Create a Random List of Acronyms/ ####Change Size based on what you need

#acrLknown = random.sample(knownA,(lSize/2))

acrLknown = [
    knownA[i]
    for i in sorted(random.sample(xrange(len(knownA)), int(lSize / 2)))
]
acrlunknown = [
    unknownA[i]
    for i in sorted(random.sample(xrange(len(unknownA)), int(lSize / 2)))
]

#indices = random.sample(range(len(knownA)), int(lSize/2))
#[knownA[i] for i in sorted(indices)]

#print knownA

acrL = acrLknown.extend(acrlunknown)
#acrL=acrLknown
#print acrL
コード例 #9
0
    height=0.1,
    wrapWidth=None,
    ori=0,
    color='white',
    colorSpace='rgb',
    opacity=1,
    depth=0.0)

# Initialize components for Routine "trial"
trialClock = core.Clock()
import random

index = 0
sent_ok = 0
count_sent = 0
order = random.sample(range(2, 7), 5)
recall = False
end_order = 0
time_band = False
text = visual.TextStim(win=win,
                       name='text',
                       text='default text',
                       font='Arial',
                       pos=(0, 0),
                       height=0.1,
                       wrapWidth=None,
                       ori=0,
                       color='black',
                       colorSpace='rgb',
                       opacity=1,
                       depth=-2.0)
コード例 #10
0
cols = 3 + (files * 3) + (final_files * (2 * nReps))
currentCol = cols
data_matrix = import_data('final_test_', final_files - 1, rows, cols)

looper = 0
#make lists of stims used and last testing error
while looper < rows:
    stim_list.append(data_matrix[looper][0])
    error_list.append(data_matrix[looper][cols - 1])
    looper = looper + 1
looper = 0

#choose 8 stims at random (for now later will calculate from errors)
use_list = []
#randomly choose
use_these = random.sample(range(0, rows - 1), (int((rows - 2) / 2)))

#add the random 8 to a new list
for num in use_these:
    use_list.append(stim_list[num])

#choose timings for each iti
iti_timings = np.zeros((32, 4))

# matrix that hold parameters for how experiment should run, first created and then shuffled to make pseudo random
# col 1 - iti reps 5-8, col 2 - 0 word, 1 pseudo word, col 3 - 0 reexpose, 1 do nothing
# col 4- -1 do nothing, 0-7 stim to reexpose, col 5- 0 left arrow, 1 right arrow
#8 of each iti timing
#within each 8 1/2 are word and 1/2 are pseudoword
#first word and pseudo word of each 8 is a reexpose so 8 reexposed throughout
x = 0
コード例 #11
0
mStimuli = {}                                              #dictionary of all manmade stimuli - 272
nStimuli = {}                                              #dictionary of all natural stimuli - 272

for i in range(272):                                       #loops through 272 to initialize all stimuli elements 
    num = i + 1
    
    man = ['M' + str(num) + '.jpg', expInfo['ManmadeKeys'], 'manmade']
    mStimuli[i] = man
    
    nat = ['N' + str(num) + '.jpg', expInfo['NaturalKeys'], 'natural']
    nStimuli[i] = nat
    
manSelectedStimuli = []                                       #list of the randomly selected manmade stimuli - 196
natSelectedStimuli = []                                       #list of the randomly selected natural stimuli - 196

imgRandShuffle = random.sample(range(len(mStimuli)), 196)     #randomly access 196 numbers from 272 to use in the loop to select the 196 stimuli
imgNotSelected = [i for i in range(272)]

for selected in imgRandShuffle:
    manSelectedStimuli.append(mStimuli[selected])
    natSelectedStimuli.append(nStimuli[selected])
    imgNotSelected.remove(selected)
    
shuffle(imgNotSelected)

varSaveFile = "blockData" + expInfo['participant'] + ".txt"
varSaver = open(os.path.join(newpath, varSaveFile), 'w')
varSaver.write("ManmadeKeys:" + str(expInfo['ManmadeKeys']))
varSaver.write("\nNaturalKeys:" + str(expInfo['NaturalKeys']))
varSaver.write("\nimgRandShuffle:" + str(imgRandShuffle))
varSaver.write("\nPracticeSet:" + str(imgNotSelected[0:10]))
コード例 #12
0
ファイル: LSL.py プロジェクト: NeuroTechX/Brainlock
#Create the List of Acronyms with known and Unknown
#for i in range(len(knownA)):
#    if i % 2 == 0:
#        acrL[i]=knownA[i]
#    else:
#        acrL[i]=unknownA[i]
######

#acrL=range(len(knownA))    

####Create a Random List of Acronyms/ ####Change Size based on what you need 

#acrLknown = random.sample(knownA,(lSize/2))        

acrLknown = [knownA[i] for i in sorted(random.sample(xrange(len(knownA)), int(lSize/2))) ]
acrlunknown = [unknownA[i] for i in sorted(random.sample(xrange(len(unknownA)), int(lSize/2))) ]

#indices = random.sample(range(len(knownA)), int(lSize/2))
#[knownA[i] for i in sorted(indices)]

#print knownA

acrLknown.extend(acrlunknown)
acrL=acrLknown
print acrL

random.shuffle(acrL)

#if lSize is not 0:
#    acrL=acrL[:lSize]
コード例 #13
0
ファイル: BARTAlgorithm.py プロジェクト: tptibbett/UsefulCode
            balloonValMsg.setText(u"This balloon value:\n$%.2f" %
                                  thisBalloonEarnings,
                                  log=False)

        # *bankedMsg* updates
        if t >= 0.0 and bankedMsg.status == NOT_STARTED:
            # keep track of start time/frame for later
            bankedMsg.tStart = t  # underestimates by a little under one frame
            bankedMsg.frameNStart = frameN  # exact frame index
            bankedMsg.setAutoDraw(True)
        if bankedMsg.status == STARTED:  # only update if being drawn
            bankedMsg.setText(u"You have banked:\n$%.2f" % bankedEarnings,
                              log=False)
        if event.getKeys(['space']):  # When a person presses space...
            overall = overall + 1
            PopIndicator = random.sample(
                Samp, 1)[0]  # This randomly samples 1 data point.
            nPumps = nPumps + 1
            if PopIndicator == 0:  # If that data point is 0
                popped = True  # The balloon will pop
                continueRoutine = False  # The routine will end
            elif nPumps > 0:  # If it's greater than 0...
                Samp = Samp[:
                            -1]  # Make this list shorter by the last item in the list.

        # *bankButton* updates
        if t >= 0.0 and bankButton.status == NOT_STARTED:
            # keep track of start time/frame for later
            bankButton.tStart = t  # underestimates by a little under one frame
            bankButton.frameNStart = frameN  # exact frame index
            bankButton.status = STARTED
            # keyboard checking is just starting