Example #1
0
def monte_carlo_localization(a, z, N, P_motion_sample, P_sensor, m, S=None):
    """Monte Carlo localization algorithm from Fig 25.9"""

    def ray_cast(sensor_num, kin_state, m):
        return m.ray_cast(sensor_num, kin_state)

    M = len(z)
    W = [0]*N
    S_ = [0]*N
    W_ = [0]*N
    v = a['v']
    w = a['w']

    if S is None:
        S = [m.sample() for _ in range(N)]

    for i in range(N):
        S_[i] = P_motion_sample(S[i], v, w)
        W_[i] = 1
        for j in range(M):
            z_ = ray_cast(j, S_[i], m)
            W_[i] = W_[i] * P_sensor(z[j], z_)

    S = weighted_sample_with_replacement(N, S_, W_)
    return S
Example #2
0
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
    highest = 0
    highestEvolved = None
    optimalReached = ngen
    optimal = sum(range(len(population[0].genes)))
    for i in range(ngen):
        new_population = []
        for j in range(len(population)):
            fitnesses = map(fitness_fn, population)
            p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
            child = p1.mate(p2)
            if random.uniform(0, 1) < pmut:
                child.mutate()
            new_population.append(child)
        population = new_population
        
        #Check and keep track of max; not necessarily pure GA
        currentEvolved = argmax(population, fitness_fn)
        currentHigh = fitness_fn(currentEvolved)
        if currentHigh > highest:    
            highest = currentHigh
            highestEvolved = currentEvolved
        if optimalReached == ngen and currentHigh == optimal:
            optimalReached = i
    return (highestEvolved, highest, optimalReached)
def monte_carlo_localization(a, z, N, P_motion_sample, P_sensor, m, S=None):
    """
    [Figure 25.9]
    Monte Carlo localization algorithm"""

    def ray_cast(sensor_num, kin_state, m):
        return m.ray_cast(sensor_num, kin_state)

    M = len(z)
    W = [0] * N
    S_ = [0] * N
    W_ = [0] * N
    v = a['v']
    w = a['w']

    if S is None:
        S = [m.sample() for _ in range(N)]

    for i in range(N):
        S_[i] = P_motion_sample(S[i], v, w)
        W_[i] = 1
        for j in range(M):
            z_ = ray_cast(j, S_[i], m)
            W_[i] = W_[i] * P_sensor(z[j], z_)

    S = weighted_sample_with_replacement(N, S_, W_)
    return S
Example #4
0
def consensus_score(q, times_by_source, mu, node2id, source2nodeid_counter):
    """return the consensus value from different sources on node q"""
    qid = node2id[q]
    M, N = times_by_source[next(iter(times_by_source.keys()))].shape

    np.testing.assert_almost_equal(sum(mu.values()), 1.0)

    nodes = list(node2id.keys())
    # node_indices = list(node2id.values())
    weights = np.asarray([mu[n] for n in nodes])
    sampled_experts = weighted_sample_with_replacement(nodes, weights, M)
    # [nodes[np.random.choice(node_indices, p=weights)] for _ in range(M)]

    # the "centroid" belief on q's infection time
    centroid = np.zeros(M)
    for i, e in enumerate(sampled_experts):
        time = np.random.choice(times_by_source[e][:, qid])
        centroid[i] = time

    centroid = Counter(centroid)
    similarity_scores = np.zeros(N)

    for i, n in enumerate(nodes):
        similarity_scores[i] = generalized_jaccard_similarity(
            centroid, source2nodeid_counter[n][qid])
    return np.mean(similarity_scores * weights)  # weighted mean
def consensus_score(q, times_by_source, mu, node2id, source2nodeid_counter):
    """return the consensus value from different sources on node q"""
    qid = node2id[q]
    M, N = times_by_source[next(iter(times_by_source.keys()))].shape
    
    np.testing.assert_almost_equal(sum(mu.values()), 1.0)
    
    nodes = list(node2id.keys())
    # node_indices = list(node2id.values())
    weights = np.asarray([mu[n] for n in nodes])
    sampled_experts = weighted_sample_with_replacement(nodes, weights, M)
    # [nodes[np.random.choice(node_indices, p=weights)] for _ in range(M)]

    # the "centroid" belief on q's infection time
    centroid = np.zeros(M)
    for i, e in enumerate(sampled_experts):
        time = np.random.choice(times_by_source[e][:, qid])
        centroid[i] = time

    centroid = Counter(centroid)
    similarity_scores = np.zeros(N)

    for i, n in enumerate(nodes):
        similarity_scores[i] = generalized_jaccard_similarity(
            centroid, source2nodeid_counter[n][qid])
    return np.mean(similarity_scores * weights)  # weighted mean
Example #6
0
def particle_filtering(e, N, HMM):
    """Particle filtering considering two states variables."""
    dist = [0.5, 0.5]
    # Weight Initialization
    w = [0 for _ in range(N)]
    # STEP 1
    # Propagate one step using transition model given prior state
    dist = vector_add(scalar_vector_product(dist[0], HMM.transition_model[0]),
                      scalar_vector_product(dist[1], HMM.transition_model[1]))
    # Assign state according to probability
    s = ['A' if probability(dist[0]) else 'B' for _ in range(N)]
    w_tot = 0
    # Calculate importance weight given evidence e
    for i in range(N):
        if s[i] == 'A':
            # P(U|A)*P(A)
            w_i = HMM.sensor_dist(e)[0] * dist[0]
        if s[i] == 'B':
            # P(U|B)*P(B)
            w_i = HMM.sensor_dist(e)[1] * dist[1]
        w[i] = w_i
        w_tot += w_i

    # Normalize all the weights
    for i in range(N):
        w[i] = w[i] / w_tot

    # Limit weights to 4 digits
    for i in range(N):
        w[i] = float("{0:.4f}".format(w[i]))

    # STEP 2
    s = weighted_sample_with_replacement(N, s, w)
    return s
Example #7
0
def weighted_replicate(seq, weights, n):
    """Return n selections from seq, with the count of each element of
    seq proportional to the corresponding weight (filling in fractions
    randomly).
    >>> weighted_replicate('ABC', [1,2,1], 4)
    ['A', 'B', 'B', 'C']"""
    assert len(seq) == len(weights)
    weights = normalize(weights)
    wholes = [int(w * n) for w in weights]
    fractions = [(w * n) % 1 for w in weights]
    return (flatten([x] * nx for x, nx in zip(seq, wholes)) +
            weighted_sample_with_replacement(seq, fractions, n - sum(wholes)))
Example #8
0
def weighted_replicate(seq, weights, n):
    """Return n selections from seq, with the count of each element of
    seq proportional to the corresponding weight (filling in fractions
    randomly).
    >>> weighted_replicate('ABC', [1,2,1], 4)
    ['A', 'B', 'B', 'C']"""
    assert len(seq) == len(weights)
    weights = normalize(weights)
    wholes = [int(w * n) for w in weights]
    fractions = [(w * n) % 1 for w in weights]
    return (flatten([x] * nx for x, nx in zip(seq, wholes)) +
            weighted_sample_with_replacement(seq, fractions, n - sum(wholes)))
Example #9
0
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
    "[Figure 4.8]"
    for i in range(ngen):
        new_population = []
        for i in range(len(population)):
            fitnesses = map(fitness_fn, population)
            p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
            child = p1.mate(p2)
            if random.uniform(0, 1) < pmut:
                child.mutate()
            new_population.append(child)
        population = new_population
    return argmax(population, key=fitness_fn)
Example #10
0
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
    "[Fig. 4.8]"
    for i in range(ngen):
        new_population = []
        for i in len(population):
            fitnesses = map(fitness_fn, population)
            p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
            child = p1.mate(p2)
            if random.uniform(0, 1) < pmut:
                child.mutate()
            new_population.append(child)
        population = new_population
    return argmax(population, fitness_fn)
Example #11
0
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.1):
    global generationCount
    highest = 0
    highestEvolved = None
    for i in range(ngen):
        new_population = []
        for j in range(len(population)):
            fitnesses = map(fitness_fn, population)
            p1, p2 = weighted_sample_with_replacement(population, fitnesses, 2)
            child = p1.mate(p2)
            if random.uniform(0, 1) < pmut:
                child.mutate()
            new_population.append(child)
        population = new_population

        #Check and keep track of max; not necessarily pure GA
        currentEvolved = argmax(population, fitness_fn)
        currentHigh = fitness_fn(currentEvolved)
        if currentHigh > highest:
            highest = currentHigh
            highestEvolved = currentEvolved
            generationCount += 1
    return highestEvolved
Example #12
0
def particle_filtering(e, N, HMM):
    """Particle filtering considering two states variables."""
    s = []
    dist = [0.5, 0.5]
    # State Initialization
    s = ['A' if probability(dist[0]) else 'B' for i in range(N)]
    # Weight Initialization
    w = [0 for i in range(N)]
    # STEP 1
    # Propagate one step using transition model given prior state
    dist = vector_add(scalar_vector_product(dist[0], HMM.transition_model[0]),
                      scalar_vector_product(dist[1], HMM.transition_model[1]))
    # Assign state according to probability
    s = ['A' if probability(dist[0]) else 'B' for i in range(N)]
    w_tot = 0
    # Calculate importance weight given evidence e
    for i in range(N):
        if s[i] == 'A':
            # P(U|A)*P(A)
            w_i = HMM.sensor_dist(e)[0]*dist[0]
        if s[i] == 'B':
            # P(U|B)*P(B)
            w_i = HMM.sensor_dist(e)[1]*dist[1]
        w[i] = w_i
        w_tot += w_i

    # Normalize all the weights
    for i in range(N):
        w[i] = w[i]/w_tot

    # Limit weights to 4 digits
    for i in range(N):
        w[i] = float("{0:.4f}".format(w[i]))

    # STEP 2
    s = weighted_sample_with_replacement(N, s, w)
    return s
Example #13
0
def particle_filtering(e, N, HMM):
    """Filtragem de partículas considerando duas variáveis de estados."""
    s = []
    dist = [0.5, 0.5]
    # Inicialização do estado
    s = ['A' if probability(dist[0]) else 'B' for i in range(N)]
    # Inicialização de peso
    w = [0 for i in range(N)]
    # PASSO 1 - Propagar um passo usando o modelo de transição dado estado anterior
    dist = vector_add(scalar_vector_product(dist[0], HMM.transition_model[0]),
                      scalar_vector_product(dist[1], HMM.transition_model[1]))
    # Atribuir o estado de acordo com a probabilidade
    s = ['A' if probability(dist[0]) else 'B' for i in range(N)]
    w_tot = 0
    # Calcular peso de importância dado evidência e
    for i in range(N):
        if s[i] == 'A':
            # P(U|A)*P(A)
            w_i = HMM.sensor_dist(e)[0] * dist[0]
        if s[i] == 'B':
            # P(U|B)*P(B)
            w_i = HMM.sensor_dist(e)[1] * dist[1]
        w[i] = w_i
        w_tot += w_i

    # Normalizar todos os pesos
    for i in range(N):
        w[i] = w[i] / w_tot

    # Limite pesos a 4 dígitos
    for i in range(N):
        w[i] = float("{0:.4f}".format(w[i]))

    # STEP 2
    s = weighted_sample_with_replacement(s, w, N)
    return s
Example #14
0
 def data_bagging(dataset, m=0):
     """Sample m examples with replacement"""
     n = len(dataset.examples)
     return weighted_sample_with_replacement(m or n, dataset.examples, [1]*n)
Example #15
0
 def data_bagging(dataset, m=0):
     """Sample m examples with replacement"""
     n = len(dataset.examples)
     return weighted_sample_with_replacement(m or n, dataset.examples, [1]*n)