python类uniform()的实例源码

search.py 文件源码 项目:robocup-soccer 作者: kengz 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def genetic_algorithm(population, fitness_fn, ngen=1000, pmut=0.0):
    """[Fig. 4.7]"""
    def reproduce(p1, p2):
        c = random.randrange(len(p1))
        return p1[:c] + p2[c:]

    for i in range(ngen):
        new_population = []
        for i in len(population):
            p1, p2 = random_weighted_selections(population, 2, fitness_fn)
            child = reproduce(p1, p2)
            if random.uniform(0,1) > pmut:
                child.mutate()
            new_population.append(child)
        population = new_population
    return argmax(population, fitness_fn)
search.py 文件源码 项目:robocup-soccer 作者: kengz 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def random_weighted_selection(seq, n, weight_fn):
    """Pick n elements of seq, weighted according to weight_fn.
    That is, apply weight_fn to each element of seq, add up the total.
    Then choose an element e with probability weight[e]/total.
    Repeat n times, with replacement. """
    totals = []; runningtotal = 0
    for item in seq:
        runningtotal += weight_fn(item)
        totals.append(runningtotal)
    selections = []
    for s in range(n):
        r = random.uniform(0, totals[-1])
        for i in range(len(seq)):
            if totals[i] > r:
                selections.append(seq[i])
                break
    return selections


#_____________________________________________________________________________
# The remainder of this file implements examples for the search algorithms.

#______________________________________________________________________________
# Graphs and Graph Problems
search.py 文件源码 项目:robocup-soccer 作者: kengz 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def RandomGraph(nodes=range(10), min_links=2, width=400, height=300,
                                curvature=lambda: random.uniform(1.1, 1.5)):
    """Construct a random graph, with the specified nodes, and random links.
    The nodes are laid out randomly on a (width x height) rectangle.
    Then each node is connected to the min_links nearest neighbors.
    Because inverse links are added, some nodes will have more connections.
    The distance between nodes is the hypotenuse times curvature(),
    where curvature() defaults to a random number between 1.1 and 1.5."""
    g = UndirectedGraph()
    g.locations = {}
    ## Build the cities
    for node in nodes:
        g.locations[node] = (random.randrange(width), random.randrange(height))
    ## Build roads from each city to at least min_links nearest neighbors.
    for i in range(min_links):
        for node in nodes:
            if len(g.get(node)) < min_links:
                here = g.locations[node]
                def distance_to_node(n):
                    if n is node or g.get(node,n): return infinity
                    return distance(g.locations[n], here)
                neighbor = argmin(nodes, distance_to_node)
                d = distance(g.locations[neighbor], here) * curvature()
                g.connect(node, neighbor, int(d)) 
    return g
rate.py 文件源码 项目:pineapple 作者: peter765 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def rate(self, message_object, user):
        '''
        # totally not rigged or something
        def isDevMentioned():
            for u in message_object.mentions:
                if u.name == "Theraga" or u.name == "Dynista":
                    return True
            return False
        if user == "theraga" or user == "Theraga" or user == "dynista" or user == "Dynista" or isDevMentioned():
            await self.pm.client.send_message(message_object.channel, "I would rate **" + user + "** 100.00/100")
        else:
                '''
        number = round(random.uniform(1, 100), 2)
        print(message_object.mentions)
        await self.pm.client.send_message(message_object.channel,
                                          "I would rate " + "**" + user + "** " + str(number) + "/100")
nvData.py 文件源码 项目:PaintsPytorch 作者: orashi 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __call__(self, img):
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.9, 1.) * area
            aspect_ratio = random.uniform(7. / 8, 8. / 7)

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                assert (img.size == (w, h))

                return img.resize((self.size, self.size), self.interpolation)

        # Fallback
        scale = Scale(self.size, interpolation=self.interpolation)
        crop = CenterCrop(self.size)
        return crop(scale(img))
sqData.py 文件源码 项目:PaintsPytorch 作者: orashi 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __call__(self, img):
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.70, 0.98) * area
            aspect_ratio = random.uniform(5. / 8, 8. / 5)

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                assert (img.size == (w, h))

                return img.resize((self.size, self.size), self.interpolation)

        # Fallback
        scale = Scale(self.size, interpolation=self.interpolation)
        crop = CenterCrop(self.size)
        return crop(scale(img))
opData.py 文件源码 项目:PaintsPytorch 作者: orashi 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __call__(self, img):
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.70, 0.98) * area
            aspect_ratio = random.uniform(5. / 8, 8. / 5)

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                assert (img.size == (w, h))

                return img.resize((self.size, self.size), self.interpolation)

        # Fallback
        scale = Scale(self.size, interpolation=self.interpolation)
        crop = CenterCrop(self.size)
        return crop(scale(img))
proData.py 文件源码 项目:PaintsPytorch 作者: orashi 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __call__(self, img):
        for attempt in range(10):
            area = img.size[0] * img.size[1]
            target_area = random.uniform(0.9, 1.) * area
            aspect_ratio = random.uniform(7. / 8, 8. / 7)

            w = int(round(math.sqrt(target_area * aspect_ratio)))
            h = int(round(math.sqrt(target_area / aspect_ratio)))

            if random.random() < 0.5:
                w, h = h, w

            if w <= img.size[0] and h <= img.size[1]:
                x1 = random.randint(0, img.size[0] - w)
                y1 = random.randint(0, img.size[1] - h)

                img = img.crop((x1, y1, x1 + w, y1 + h))
                assert (img.size == (w, h))

                return img.resize((self.size, self.size), self.interpolation)

        # Fallback
        scale = Scale(self.size, interpolation=self.interpolation)
        crop = CenterCrop(self.size)
        return crop(scale(img))
test_sinks.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_put():
    sink = IntFloatDataSink()

    values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        result = sink.put(int, value)

        assert result is None
        assert value in sink.items[int]

    values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        result = sink.put(float, value)

        assert result is None
        assert value in sink.items[float]
test_sinks.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_wildcard_put():
    sink = SimpleWildcardDataSink()

    values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        result = sink.put(int, value)

        assert result is None
        assert value in sink.items[int]

    values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        result = sink.put(float, value)

        assert result is None
        assert value in sink.items[float]


#####################
# Put Many Function #
#####################
test_sinks.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_put_many():
    sink = IntFloatDataSink()

    values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        items = (value for _ in range(VALUES_COUNT))
        result = sink.put_many(int, items)

        assert result is None
        assert value in sink.items[int]

    values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        items = (value for _ in range(VALUES_COUNT))
        result = sink.put_many(float, items)

        assert result is None
        assert value in sink.items[float]
test_sinks.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_wildcard_put_many():
    sink = SimpleWildcardDataSink()

    values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        items = (value for _ in range(VALUES_COUNT))
        result = sink.put_many(int, items)

        assert result is None
        assert value in sink.items[int]

    values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        items = (value for _ in range(VALUES_COUNT))
        result = sink.put_many(float, items)

        assert result is None
        assert value in sink.items[float]


#####################
# CompositeDataSink #
#####################
test_sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_get():
    source = IntFloatDataSource()

    values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        query = {VALUE_KEY: value}
        result = source.get(int, query)

        assert type(result) is int
        assert result == value

    values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        query = {VALUE_KEY: value}
        result = source.get(float, query)

        assert type(result) is float
        assert result == value
test_sources.py 文件源码 项目:datapipelines-python 作者: meraki-analytics 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_wildcard_get():
    source = SimpleWildcardDataSource()

    values = [random.randint(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        query = {VALUE_KEY: value}
        result = source.get(int, query)

        assert type(result) is int
        assert result == value

    values = [random.uniform(-VALUES_MAX, VALUES_MAX) for _ in range(VALUES_COUNT)]

    for value in values:
        query = {VALUE_KEY: value}
        result = source.get(float, query)

        assert type(result) is float
        assert result == value


#####################
# Get Many Function #
#####################
Sphere_indiv.py 文件源码 项目:PyGenAlg 作者: RaphDeau 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def mutation(cls, indiv):
        newInd = indiv.duplicate()
        nbMute = int(random.random()*(len(newInd.__x)-1))+1
        toMute = []
        for i, x in enumerate(indiv.__x):
            if len(toMute) < nbMute:
                toMute.append(i)
            else:
                iMin = 0
                for im, i2 in enumerate(toMute):
                    if abs(indiv.__x[i2]) < abs(indiv.__x[toMute[iMin]]):
                        iMin = im
                if abs(x) > abs(indiv.__x[toMute[iMin]]):
                    toMute[iMin] = i
        for i in toMute:
            newInd.__x[i] = random.uniform(cls.__BOUNDS[0], cls.__BOUNDS[1])
        return newInd
Individual.py 文件源码 项目:PyGenAlg 作者: RaphDeau 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __generateRandomVarValue(cls, iVar):
        # 1- Get the definition domain of the variable
        defDomain = cls.VARIABLES_RANGES[iVar]
        if defDomain is None:
            randFloat = random.uniform(-sys.maxint-1, sys.maxint)
        else:
            # 2- Check the open/closed bounds
            includeFirst = defDomain[0] == '['
            includeLast = defDomain[-1] == ']'
            # 3- Get a random number in the domain
            defDomain = eval('[' + defDomain[1:-1] + ']')
            randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0]
            # 4- Check the bounds
            while (randFloat == defDomain[0] and not includeFirst) or\
                    (randFloat == defDomain[1] and not includeLast):
                randFloat = random.random()*(defDomain[1]-defDomain[0]) + defDomain[0]
        # 5- Cast the variable type
        return cls.VARIABLES_TYPE(randFloat)
    # ----------------------
params.py 文件源码 项目:Tinychat-Bot--Discontinued 作者: Tinychat 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def recaptcha(self):
        """ Check if we need to solve a captcha.

        This will open in the default browser.

        If we choose to not solve the captcha should it be required,
        we will then be considered a 'lurker' and we will not be able to chat
        and our name will be shown as a guest name in the room.
        """
        t = str(random.uniform(0.9, 0.10))
        _url = 'https://tinychat.com/cauth/captcha?{0}'.format(t)

        _response = util.web.http_get(url=_url, json=True, proxy=self.proxy)
        log.debug('recaptcha response: %s' % _response)
        if _response['json'] is not None:
            if _response['json']['need_to_solve_captcha'] == 1:
                link = 'https://tinychat.com/cauth/recaptcha?token={0}'.format(_response['json']['token'])
                webbrowser.open(link, new=True)
                print (link)
                raw_input('Solve the captcha and click enter to continue.')
genome.py 文件源码 项目:PyNEAT 作者: hugofragata 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def mutation(self, mutation_type):
        if mutation_type not in MUTATION_TYPES:
            raise GenomeError("mutation type not supported")
        threshold = random.uniform(self.mutation_lower_threshold, self.mutation_higher_threshold)
        if threshold < self.mutation_threshold:
            return
        if mutation_type == "add_node":
            self.mutate_add_node()
        elif mutation_type == "remove_node":
            self.mutate_remove_node()
        elif mutation_type == "add_connection":
            self.mutate_add_connection()
        elif mutation_type == "remove_connection":
            self.mutate_remove_connection()
        else:
            raise GenomeError("something wrong happened in mutation.")
hellozmq.py 文件源码 项目:zanph 作者: zanph 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def serviceB(context=None):
    #reuse context if it exists, otherwise make a new one
    context = context or zmq.Context.instance()
    service = context.socket(zmq.DEALER)

    #identify worker
    service.setsockopt(zmq.IDENTITY,b'B')
    service.connect("tcp://localhost:5560")
    while True:
        message = service.recv()
        with myLock:
            print "Service B got:"
            print message
        if message == "Service B":
            #do some work
            time.sleep(random.uniform(0,0.5))
            service.send(b"Service B cleaned your room")
        elif message == "END":
            break
        else:
            with myLock:
                print "the server has the wrong identities!"
            break
image_pool.py 文件源码 项目:DistanceGAN 作者: sagiebenaim 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def query(self, images):
        if self.pool_size == 0:
            return images
        return_images = []
        for image in images.data:
            image = torch.unsqueeze(image, 0)
            if self.num_imgs < self.pool_size:
                self.num_imgs = self.num_imgs + 1
                self.images.append(image)
                return_images.append(image)
            else:
                p = random.uniform(0, 1)
                if p > 0.5:
                    random_id = random.randint(0, self.pool_size-1)
                    tmp = self.images[random_id].clone()
                    self.images[random_id] = image
                    return_images.append(tmp)
                else:
                    return_images.append(image)
        return_images = Variable(torch.cat(return_images, 0))
        return return_images


问题


面经


文章

微信
公众号

扫码关注公众号