473,568 Members | 2,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Optimization: Picking random keys from a dictionary and mutatingvalues

Hey everyone,
Just a friendly question about an efficient way to do this. I have
a graph with nodes and edges (networkx is am amazing library, check it
out!). I also have a lookup table with weights of each edge. So:

weights[(edge1, edge2)] = .12
weights[(edge2, edge5)] = .53
weights[(edge5, edge1)] = 1.23
weights[(edge3, edge2)] = -2.34
etc.

I would like to take this weight table and subject it to evolutionary
mutations. So given a probability p (mutation rate), mutate edge
weights by some random value. So in effect, if p is .25, choose 25%
random edges, and mutate them some amount. So:
1. Whats a good way to get the keys? I'm using a loop with
random.choice() at the moment.
2. Any comments on how to get a 'fair' mutation on an existing edge
value?

I currently am doing something like this, which seems like it leaves
something to be desired.

import random
weights = generateweights () # generates table like the one above
p = 0.25
v = random.betavari ate(2, 10)
num = int(v*len(weigh ts)) # How many weights should we mutate?
keys = w.keys()
for i in xrange(num):
val = random.choice(k eys) # Choose a single random key
w[val] = w[val]*(random.random ()*5-1) # Is this a 'good' way to
'mutate' the value?

This is an evolutionary search, so mutate in this sense relates to a
genetic algorithm, perhaps a gradient decent?
Thanks!
Blaine
Jun 27 '08 #1
2 1799
On May 28, 4:41*pm, blaine <frik...@gmail. comwrote:
1. *Whats a good way to get the keys? I'm using a loop with
random.choice() at the moment.
Why not keep a separate list of keys and use random.sample() ?
Raymond
Jun 27 '08 #2
On May 28, 7:41 pm, blaine <frik...@gmail. comwrote:
Hey everyone,
Just a friendly question about an efficient way to do this.
Friendly advance reminder: in many optimization problems, the
objective function is far more expensive to calculate than the
optimizing procedure. Your time is usually better spent optimizing
the objective function, or tuning the optimizer.

But what they hey.
I have
a graph with nodes and edges (networkx is am amazing library, check it
out!). I also have a lookup table with weights of each edge. So:

weights[(edge1, edge2)] = .12
weights[(edge2, edge5)] = .53
weights[(edge5, edge1)] = 1.23
weights[(edge3, edge2)] = -2.34
etc.

I would like to take this weight table and subject it to evolutionary
mutations. So given a probability p (mutation rate), mutate edge
weights by some random value. So in effect, if p is .25, choose 25%
random edges, and mutate them some amount. So:
1. Whats a good way to get the keys? I'm using a loop with
random.choice() at the moment.
That's probably the best way.

You might be able to squeeze a little more speed out of it by using a
partial random shuffle as opposed to removing the item from the list.
This will minimize the amount of copying. Here's an example (without
error checking):

def partial_random_ shuffle(lst,nsh uffled):
for i in xrange(nshuffle d):
j = random.randrang e(i,len(lst))
t = lst[i]
lst[i] = lst[j]
lst[j] = t

The first nshuffled items of lst upon return will be the selected
items. Note: This might also be slower than removing items. It
should scale better, though.

2. Any comments on how to get a 'fair' mutation on an existing edge
value?
random.normalva riate is usually a good choice for selecting random
real-valued increments.

val = random.normalva riate(val,sigma )

where sigma, the standard deviation, is the amount

I currently am doing something like this, which seems like it leaves
something to be desired.

import random
weights = generateweights () # generates table like the one above
p = 0.25
v = random.betavari ate(2, 10)
num = int(v*len(weigh ts)) # How many weights should we mutate?
keys = w.keys()
for i in xrange(num):
val = random.choice(k eys) # Choose a single random key
w[val] = w[val]*(random.random ()*5-1) # Is this a 'good' way to
'mutate' the value?
If you don't remove keys[val], there's a chance you'll mutate the same
key twice, which I doubt is what you want.

This is an evolutionary search, so mutate in this sense relates to a
genetic algorithm, perhaps a gradient decent?
A gradient descent method is not an evolutionary search and involves
no randomness (unless noise is added to the objective, which is a
possible way to attack a function with unimportant small scale
features, and in that case normalvariate would be the thing used).

Carl Banks
Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1612
by: r.e.s. | last post by:
Would anyone care to offer pointers on how the following code might be optimized? Or alternatives? ... --- def lz(string): """ Return the Lempel-Ziv complexity (LZ78) of string. """ vocabulary = word = '' for char in string:
57
3563
by: Egor Bolonev | last post by:
why functions created with lambda forms cannot contain statements? how to get unnamed function with statements?
5
6215
by: Tor Erik Sønvisen | last post by:
Hi How can I select a random entry from a dictionary, regardless of its key-values? regards tores
90
10738
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys():
5
1365
by: Bob Kline | last post by:
I have a suggestion for speeding up the performance of code like this: fields = cgi.FieldStorage() if fields: ... which, as it turns out, invokes FieldStorage.__len__(), which in turn calls FieldStorage.keys(), which builds a list of keys by hand, taking several minutes for large forms. This implementation of keys() reduces the amount...
39
2439
by: Alan Isaac | last post by:
This may seem very strange, but it is true. If I delete a .pyc file, my program executes with a different state! In a single directory I have module1 and module2. module1 imports random and MyClass from module2. module2 does not import random. module1 sets a seed like this::
3
1724
by: David | last post by:
On Sun, May 4, 2008 at 4:43 AM, lev <levlozhkin@gmail.comwrote: Hi, I started tidying up the script a bit, but there are some parts I don't understand or look buggy. So I'm forwarding you the version I have so far. Look for the comments with my e-mail address in them for more information. If I have time I'll tidy up the script some more...
13
12748
by: Nader | last post by:
Hello, I have a dictionary and will get all keys which have the same values. d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} I will something as : d.keys(where their values are the same)
3
2942
by: Michel Esber | last post by:
Hi all, Db2 v8 FP15 LUW . create table T (ID varchar (24), ABC timestamp) There is an index for (ID, ABC), allowing reverse Scans. My application needs to determine MIN and MAX(ABC) for a given ID. We are currently using a simple statement:
0
7604
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7916
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8117
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6275
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5498
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2101
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
932
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.