Collective Intelligence (Segaran) – Chapter 5 – NoneType error

Been working through this excellent book when I stumbled upon the following error:

File "optimization.py", line 163, in geneticoptimize
    scores=[(costf(v),v) for v in pop]
  File "dorm.py", line 42, in dormcost
    for i in range(len(vec)):
TypeError: object of type 'NoneType' has no len()

After running the code on and before page 109. It took me a while to get to the bottom of it, so I thought I would share my findings. I did numerous searches on Google and eventually came across this posting, belonging to wentrue.

I had to translate it and found that the function mutate(vec) in genticoptimize has a “bug” in it. This “bug” (using the term very lightly) is because the condition to decide what to return appears to have a hole in it and sometimes nothing will be returned because the value being compared falls outside the criteria. To make live easy I simply added an else clause to the function and chose to return the first criteria result.

	def mutate(vec):
		i=random.randint(0,len(domain)-1)
		if random.random()<0.5 and vec[i]>domain[i][0]:
			return vec[0:i]+[vec[i]-step]+vec[i+1:]
		elif vec[i]<domain[i][1]:
			return vec[0:i]+[vec[i]+step]+vec[i+1:]
		else:
			return vec[0:i]+[vec[i]-step]+vec[i+1:]

Further to this I found on the errdata (search for page 109), for the book, a better way of running the code which is:

s=optimize.randomoptimize(dorm.domain,dorm.dormcost)
dorm.printsolution(s)
dorm.dormcost(s)
r=optimize.geneticoptimize(dorm.domain,dorm.dormcost)
dorm.printsolution(r)

Thats it, back to having fun with the book. Hope this helps others.

Advertisements

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: