Wiimote Controlled Coil Gun

I know it seems like a while since I last posted, but since my Christmas enlistment into the Joint Strike Force I’ve been busy winning WWIII for America! Actually it’s not been all video games, I’ve been working on a Django project that I hope to release in a few weeks, and inspired by ServoBeer I managed to find time for some ioBridge hacking.

However, as you can tell my recent militaristic tendencies have probably gotten the better of me!

Weapons of War

Weapons of War

As you know from my previous posts I’m interested bringing a higher level of physical awareness and capability to my typical computing environment. Embedded systems are usually used to bypass the need for sophisticated systems, and the ioBridge is great for those situations.

Yet, I’m perfectly comfortable with the idea of using a laptop for a command and control system. It might be a more “tethered” solution then some people would like but I figure in a few years my iPhone will be able to fulfill the role my laptop currently has!

I wanted to move beyond some of the work I’ve been doing with passive sensors and in thinking about some ideas for a more active interfaces I realized that the wiimote certainly fits the description of a powerful controller! There are already enough great wii control hacks out there and some programs let you use the wiimote as a mouse!

But I wanted more then to just replace my mouse, and in most of these cases the flow control goes from the wiimote to a computer, or the wiimote to an arduino with lots of wiring. I wanted to both avoid the electrical requirements as well as extend the influence and “reach” of my wiimote beyond my immediate vicinity.

There are certainly times when you wouldn’t want to put your expensive new Macbook in harm’s way. Whether on the front lines or in the basement laptops are sometimes the wrong systems to dedicate to a task, so ioBridge to the rescue!

The ioBridge already has a number of features which make it idea for “remote” situations and so all I needed create was a mechanism to coordinate wiimote events sent to my computer with ioBridge events sent to the module. Luckily the team at ioBridge has created just such an API!

In this setup I use a python script and MoteDaemeon to bring the events into my laptop’s domain. Of course I could script up a number of local events but what I wanted to do was act on that data and sending commands to an ioBridge module.

So I build a website which monitors the position from one axis of the wiimote and extrapolates that position to a servo output on a remote ioBridge module (which happens to be in my office, but doesn’t have to be). I’m also tracking some of the button inputs and can expand easilly to include other axes as well!

Now I just needed something fun to control on the other end! I happened to have an office golf putter lying around and that uses an electromagnetic induction coil to generate the force needed for the ball return when you sink a putt. If you take that apart and replace the metal cylinder with something a tad bit smaller then you’re left with a coil gun capable of some pretty powerful shooting!

I’m not sure it’s up to DoD standards yet but remember the only required link between the wiimote and the ioBridge module is the Internet so if you can sneak one of these into your friend’s house, or a colleagues’ office, then you could be anywhere on the planet with Internet access and stick it to them!

How’s that for “Can you hear me now?”. Check out the video of it in action on YouTube or Vimeo!

Posted in hacks, hardware, iobridge | 80 Comments

Taking (and keeping) your temperature!

I swear I don’t have a penchant for medical terminology but this ioBridge stuff is making me feel like that time I stayed at a Holiday Inn… so refreshing, I think I could perform surgery!

After my heart hacks (see my previous posts) I had questions from some friends about how we could graph the data from an ioWidget’s (my term). Initially, I wanted to push the data into a Google Spreadsheet but unfortunately there doesn’t seem to be a higher level javascript library supporting Google Docs and sorting through the feed URL’s was just too complicated.

At the same time I was thinking through this request, I received a resounding response from the ioBridge team! Although I’d worked around the need for a simple API they quickly responded to the desire (apparently I wasn’t the only one with interesting ideas) and now there’s a full JSON API!

I won’t bore you with my initial graphing solution as the sample made it into their official API demo (along with some much needed code enhancements). However, there were a few pitfalls with that approach that I still didn’t like, most specifically that the data is “lost” every time you reload the page.

It took me until after the holiday break (along with a welcome return to python) but I’ve solved my initial frustration with great results.

Here’s a script which will poll my ioBridge module and then store the results of my tempreature sensor in a Google Spreadsheet that I created! Once the data’s there you can use Google’s visualization widgets to make some fun graphs!

Aside from some setup and “ease of use” code, the real work is done by two very brief classes. I deliberately didn’t add some error checking nor make the widget class generic (it’s actually proxying the full ioBridge module) so I think it should be straightforward enough to modify for your own uses!

All you need to do is create a spreadsheet and open it in your browser. Copy the key from that URL and paste it, along with your ioBridge feed URL, into the appropriate places in the script (the locations are commented).

I simply run this from a cron script every few minutes (once I get more data I’ll reduce the time) and although there’s not a lot of variation in the data (I deliberately introduced some to make the graph more interesting) it’s a spectacular way to record, visualization and act on the sensor’s findings!

Good luck with your own modifications and let me know if I can help!

Posted in code, Google, hardware, iobridge, python, visualization | 10 Comments

Open heart surgery!

It’s not quite a detailed tutorial but I hope any budding ioBridge cardiologists will find my latest foray into web2.0 useful.

I’ve recorded a video of my ioBridge project and posted it on Vimeo in the hope that it will help anyone looking to do something similar.

Unfortunately, pasting HTML into a blog post usually isn’t successful but I believe my source and previous writeup should be simple enough for others to follow. The trick is to include your widget script in your page and wrap it with a “div” using a specific, ID. In my case I used “#content” and was then able to use jQuery to mark this as hidden, CSS “display: hidden” would also work equally well.

I could then use jQuery to parse on this div ID (rather then having to find out the ioBridge widget number), which isn’t hard either and convert the html content to a floating point value. It’s a straightforward query though you may have to play with the “split()” function depending on your layout and sensor.

If you’ve got any questions feel free to email me, jay, at thecapacity.org or find me via http://wjhuie.com

Posted in uncategorized | 3 Comments

Bridge to my heart…

Yesterday I talked quickly about my new ioBridge module and how excited I was to get started with it!

As I mentioned, my real goal is to bring physical interactions into the digital world and I had a heartbreakingly simple desire to get started with! Like most of you I’m sure, I have a special someone who’s stuck on the other side of the tubes most of the day.

I’ve known several coworkers to spend quite some time on their cellphones with family members exchanging tidbits throughout the day. I’m lucky that my spouse has some significant technology savvy (who says they can’t be trained… j/k hon!) so we get a lot of our “chit chat” done without breaking the context of our mental modes by using gtalk.

I’m sure many of you use some form of instant messaging for work, and have developed an enjoyable bit of asynchronicity to your conversations. It’s rewarding to be able to stay in the zone and then pick up a conversation where you left off once you’ve got a moment’s break.

However, how many of you have started a conversation with “Hey, are you there?”. It’s a personal pet peeve of mine (i.e. tell me what you need so I can deal w/ it when I have a chance) but often there’s no need beyond wanting to know the other person’s there and still has a pulse.

So that’s where iobridge_project_v0.01 comes in!

If you’ve checked out the link and are a bit confused here’s the explanation!

1) I wanted to build a digital representation of my physical presence and I decided that a “heartbeat” was a pretty obvious analogy.

2) So I found a wonderful tutorial on how to draw animated gifs but stopped with a single heart jpg and then needed to animate this beating in correspondence with my presence.

3) Using the very simple iobridge widget script I’m able to display the temp from my sensor wherever I want. However,  I wanted to actually _act_ on this data!

I’ve already talked with some of the ioBridge guys about them providing an XML / JSON interface and they were really receptive but there’s so much excitement over their device that I knew it would take a little bit of time before they could put something together.

First I tried to use jQuery to make a JSONP call to their server, but that didn’t work. Although I’m not smart enough to understand exactly how JSONP works, but I know the server has to cooperate. Despite their enthusiasm I knew ioBridge had more important things to work on and couldn’t turn around an API in 10 minutes (though I’m sure they’d try if you asked)!

I consider myself a persistent fellow, so I broke out firebug and started tracing through their script! It’s not rocket science, but the session variables and timestamps were a bit daunting. I must say they’ve put some thought and effort in securing your data (they even use HTTPS) and I started to feel myself deflate.

However, I decided to have a bit of lunch before I gave up entirely and that’s when I had my brightest idea all day!

4) I realized I didn’t need to worry about “spoofing” the request I could simply let ioBridge’s code do what it did best, polling the data! In turn, I did what I could do best, which was utilize the power of jQuery to get to that data!

5) So I simply hid the content div that I’d wrapped the ioBridge Widget in and proceeded to parse out the data! It’s as simple as;

$("#content").hide();

Then to get the data you just need to do this;

var t = $("#content").text().split(";")[1];
new_temp = parseFloat(t);

6) After that you just need a little UI logic and you’re good to go! Here’s a description of what I settled on but check out the page for the full on code;

I build an “animate heart” function which is triggered to fade in and fade out the heart. This is a simple function and could get more complicated if you’re a better animator then I am. Then I build a control function which would query the current temperature and compare that to the previous temperature. If things had changed (up or down) it simply tweaked the timing interval and reset the trigger event on the heart icon to have it beat faster or slower!

So there you have it! I can tuck the tempreture gague under my laptop so you can see how hard I’m working, or I can put it the back of my chair so you can get visual feedback as my body heats up the seat!

I know you’ll have to take the pulsing example with a bit of faith, but compare that to the temerature results and see the correlation! Also you can twitter me if you want me to go hold the sensor and make sure I’m moslty human!

Posted in code, hardware, iobridge, technology, twitter | 3 Comments

Suggestions for Google Friend Connect

I’ve been building my personal site and one of the things I’m excited about is the chance to interconnect my work with the larger social networks out there.

I believe every site should do what it’s best at and my intent isn’t to manage comments, wall posts or user signups and security. So once I got a basic life aggregator put together my next step was to integrate Google Friend Connect and see what it was all about.

The idea of Friend Connect is to let Google proxy most of the “social interactions” for you so you can simply deal with what you do best (which is likely developing useful content and interacting with other humans… not swearing over spam and comment plugins).

It’s incredibility easy to get up and running, you simply copy two HTML files to your site and let Google give it a once over. After that things are “configured” but there’s still no interface for interacting “socially” with the site.

In order do that you add a members gadget (or a smaller signon module) and ‘viola – People are now able to “join” your site! To get one of these plugins installed you use Google’s site to generate the necessary Javascript and HTML. I simply copied these codes into a “friend.html” file which is loaded via a corresponding menu item.

It’s not very difficult but you need to have a fairly straightforward “color scheme” defined and I don’t understand why “Links” and “Secondary Links” are two separate categories. I also don’t like that the CSS Style information is coded inline but I understand this makes it a single step to setup.

Nontheless it’s pretty straightforward, but it annoys me that Google makes you re-enter your color settings each and every time, i.e. not only if you regenerate one of the plugins but a new plugin is similarly “blind” as to your preferences. You also have to pick a general “size” for your widget which isn’t difficult thanks to the Web Developer’s Dislpay Ruler (under Miscellaneous).

So once it’s up and running, what are my impressions?

Well it’s certainly a neat idea but I was a bit underwhelmed. Currently, there’s only a “Wall” a “Rate and Review” widgets available and neither of my two test posts “left” the walled garden of my site. What I’d like is the ability to control the publishing of these “events” so that my twitter friends currently know if I’m active and engadged on a site!

It also wasn’t clear with the widgets how I’d solve typical “use cases”. For example currently my site’s “Wall” is only on a single page, but if you wanted to use this plugin for post comments how would that be done? How could I connect it to Akismet so I didn’t have to worry about spam filtering? How about other common features like emailing people when someone posts a folow up, or what about an RSS feed for this widget?

There doesn’t seem to be the typical wealth of developer documentation either. I haven’t yet investigated the “Lame Game Demonstration” or how to build a custom gadget. But given that it’s Google I think API’s and sample code is likely forthecoming.

Bottom line, it’s a start but given all the noise this has been making for so long I was expecting things to  be much farther along. Still get started and you’ll find yourself on the forefront of yet another Beta product from Google!

Posted in Google, social | Comments Off

ioBridge setup

Although I’m often working with “web stuff” or Enterprise Architectures I’ve always had a soft spot for what used to be called “ubiquitious computing”. I once had an interview at IBM and their interpretation of the term was “the ability to buy something online wherever you are” (say wha!!?) so if you’re not familiar with the phrase I doubt it was ever popular enough to have an agreed upon meaning.

I much prefer the more current term, “augmented reality”, although that often has connotations of games or enhanced social interactions. If you ever get a chance to read Donnerjack I think it’s got some great illustrations of what life could be like once we unlock “computational intelligence” from the machine.

What’s always frustrated me about the computer is that for decades our most popular input device has been the mouse (although I’m a keyboard user myself). Why must I get RSI from paging through my Google Reader simply because the ‘j’ key (or repeated clicking) was the “least worse alternative” for “next post”?

One of the reasons I’ve loved my iPhone is that it’s given me another chance at decoupling my “interface” from the computer. Even if it’s via simple web pages it’s nice to have an alternate. I have a friend who has setup a page to control his streaming DVR, audio and much more. It’s a simple advancement but being able take the convenience of a remote and the scripting power of code has been really powerful. If we can get excited about “always on” video cameras for life streaming, well I’m even more so about the time when my computer ( or cloud companion ) knows I’m on the move (and how urgently) because it can read my Nike+ transmitter!

If you’ve seen any impact of the “Makers Movement” you’ll likely agree that we’re entering a time in history where we have the ability to shape the way we want to interact with our devices. From on demand fabrication and open interfaces there’s likely a good chance that you can find a way to interface with what you want, how you want!

However, even with the multitude of arduino tutorials I’ve found it hard to get started with some of the embedded programming. I have some friends who are interested in using embedded systems to remove their need for the computer. My desires are a little different in that I want to use embedded systems to even more strongly couple myself to my system but via better interface patterns.

In essence I want the reverse of augmenting reality with technology, I want to augment software with more realistic interfaces! Let’s call it “realistic augmentation” until O’Reilly coins a more acceptable term.

So it was with much excitement that I saw the announcement of iobridge coming to market! From the writeups it looked like iobridge was a painless way achive the interlocking I’ve been looking forward to for so long!

I managed to buy one of the last modules (and a temperature sensor for starters) before they sold out and when it came I was setup in less then 5 minutes!

Here’s a quick record of what I did to get my test setup going for anyone else who’s interested in it. I already have a “usage case” in mind but I’ve been messing with jQuery for my new site (wjhuie.com) and hadn’t gotten around to it yet.

When my order came there were all of 4 things to deal with, one of which was supplied by me (the network cable). I took the   module (part 1) connected it to my router via a self-supplied Cat5 (part 2) and then plugged in the power cable (part 3). The power pack is a very nicely build module which has very low profile.

Once the module’s plugged in you’ll see a numeric LED display light up (along with two onboard LED’s, one red and one green). I plugged my module in and then went to the iobridge site and signed up. It asks you for your confirmation code (which you get via email after your order) and you’ll also have to be prepared to read off the serial number (stamped on the top of your module). Once you’ve entered those you hold down the button on the side of the module till it presents a ‘-’ sign and click “next” on the page.

ioBridge will instruct your module to display 3 random numbers (at least I assume they’re random) and you simply read them off the digital display and enter them into the site. Once that’s been done, you are done. Literally, it’s that simple!

I then plugged my temperature module into the port (which is keyed to only go in one way so you can’t mess it up) and was instantly reading analog input values taken by my sensor off their website! It was a bit unintuative but I realize you can click on the “Raw” specification and convert it to a different unit (in my case Fahrenheit).

From there you can create a widget if you’d like by clicking on the widget menu then selecting “Create Widget -> I/O Module -> Analog Input -> Module Select -> Channel 1″… If that seems complex to you, trust me it’s not. You simply hit “Next” 5 times and ‘viola!

You can change the “Analog Input Scale” here as well and select “Auto refresh” so the data’s automatically updated (or you can click on the number to refresh). From this page you can also easily copy some javascript to embed on your page and you’re done!

If you’ve noticed I’m not much for screen shots but it’s as easy as can be to get running and I’m excited about what’s in store from the company and for me! Until next time, get real… go augment your life!

Update: I forgot to include the widget!
Check this out and see how hot my office gets, even in the winter!

Posted in hardware, iobridge | 2 Comments

My least favorite part of JSON…

I love how simple the JSON spec is. I never enjoyed reading through all the XML closures, etc. JSON just feels more programming so you don’t have to shift your brain as much as you do with XML.

However, I hate that ” is the only quoting character you can use. I’ve come to love python’s equal tolerance for ‘c’ and “c”.

I like that JSON’s simple but wish it was simply more accommodating.

Posted in code, frustration, uncategorized | Comments Off

Training Neural Nets with CouchDB – part 3

Hopefully you’ve been following parts 1 and 2 and I didn’t leave anyone too confused by my approach.

Please visit my posts for a far better recap then I can provide here (DRY); In part 1, I introduced the overall project discussed the django layout and focused on the jquery I/O part. My goal in part 2 was to show some of the underlying mechanics of how we triggered a neuron as well as queried couchdb for info.

I know we honed in on some serious specifics but now that we’ve got those specifics I’d like to step back and put together the pieces.

If you check out a copy of the interface (which doesn’t have the NN backend) you can get a sense of the I/O process. In the full application here’s the process;

(0) When a user clicks anywhere on the page that’s sent to our django URL and (1) django records the location then (2) queries our neural net for a guess. (Step 6) This guess will be sent back to the page to move the second coordinate box, and in the sample is set to be equal to the click location. However, before returning the guess, (3,4) the difference between the guess and the actual click is sent to the network so it can train for next time. Also, (5) the input nodes need to be set to the click location so that next time the net can base it’s output on your previous click.

Here’s the relevant code;

#get the clicked coordinates
click_X = int(request.POST['X'])
click_Y = int(request.POST['Y'])

#Figure out what the net would have guessed
guess_X = int(get_output(“output_x”))
guess_Y = int(get_output(“output_y”))

#Find the error and propagate that back to the net
error_X = float(click_X) – float(guess_X)
error_Y = float(click_Y) – float(guess_Y)
back_prop(“output_x”, error_X)
back_prop(“output_y”, error_Y)

#Set the inputs for next time
set_input_weight(“input_x”, “static”, request.POST['X'])
set_input_weight(“input_y”, “static”, request.POST['Y'])

#return the guess to jQuery
return HttpResponse( “{ “X”: %s, “Y”: %s}” % (guess_X, guess_Y) )

Now I know you only know how a neuron is defined and have no idea of our neural net structure but I think that process will be very illustrative.

Since our net needs to predict X and Y coordinates we need to have two output nodes which I’ve named “output_x” and “output_y” and similarly we have “input_x” and “input_y” in order to inject the coordinate values into the network. You can see the keyword “static” trick that we discussed previously being used.

Neural Nets are typically called “Feed Forward Neural Nets” because you stimulate node “A” and then things cascade A -> B ->C and you can read the output at “C”.

However, programtically this can be a royal pain.

  • In some situations you’d need a clock to sync with so you can ensure that you’re reading the n’th output of C and not the n+1 (e.g. if the input to A was controlled via a separate thread then things could shift underneath you before you read the values).
  • You could also build this communication via a messaging service. Node “A” could broadcast its output at a given time and then use a pub/sub model so interested nodes could be alerted as events progressed.

The last approach probably scales the best if you had a ready queuing mechanism then I’d go this way for larger networks. This is more apparent when you realize that “A,B & C” aren’t necessarially single nodes.

Neural nets are commonly built with layers, each of which typically contains multiple nodes all of which are connected to all of the nodes in the previous and subsequent layers.

So in my case “A” is the first layer containing “input_x” and “input_y” and “C” is the output layer containing “output_x” and “output_y”. Layer B would have many nodes all receiving the output from both nodes in layer A. (As an aside you can have more complicated layering systems, for example “output_x” might also have a direct link from “input_x” to further augment it’s correlation and it is legal for a layer to only have a single node.)

So you’ve the “API” for our neural net and part 2 covers the underlying mathematical (and procedural) mechanics so I should be able to wrap up next time by discussing how to get this thing off the ground and see how it works!

Posted in code, couchdb, python | Comments Off

You get what you pay for…

If you read this post on the site as opposed to via RSS you may have noticed the Theme change (and now be wondering why I changed it back).

The trial them was ASCII-one and other then not being able to figure out how to remove some of my sidebar contents I thought it was spectacular.

However, a friend informed me that he was unable to post a comment and I can only ascribe this to the update (or truthfully it could have been the migration to WordPress 2.7-RC1).

So I thought I’d switch back to the old one for now and test things out and give things time to bake.

I know most of you don’t post comments here anyway so it likely doesn’t matter. I actual prefer it that way believe it or not. Well I don’t mean I don’t like the feedback and input but I get most of it via twitter and that’s just fine with me.

Personally I’d love it if WP just allowed pingbacks and no comments except via twitter. I mean that every post page should have a list of the times it was twittered and / or posted.

I just don’t think every WP should have to maintain it’s own user authentication system, and judging by the constant “new user registrations” which look like spammers to me, I’d be happy not to.

Posted in uncategorized | 1 Comment

Training Neural Nets with CouchDB – part 2

It’s always nice to have a little encouragement especially when trying to work through some tough posts. I really prefer white boards and pictures but I find these too hard to make for blogging so I try to let the words shape the images in your mind.

So let’s get started with your first exercise… picture or graph the output of tanh() from [-1,1]. For those who will skip the process of pulling out their graphing calculator, you’ll get a sinusoidal curve, i.e. shaped like an “S”, with asymptotes at y=-1 and y=1.

So, I know that’s neat and all but what does it have to do with couchdb? Well it doesn’t per say but it represents our “trigger” function for our neurons. We’ll use this to convert a nodes input to its output, and let’s call this function sigmoid().

The input to this function is actually the weight our node attributes to a specific input. So let’s say I’m a node, N, and I have an input, I. That input will be a value, numeric in this case, and I’ll assign it a weight, W. That weight will correlate with my “trust” in that input (after an appropriate training process). But the key part now is that the output, O, of N will be; O = I * sigmoid(W).

If you play around and graph some of this, you’ll see that if I don’t “trust” I, and W approaches 0 then even if I is a very big number O will be near 0 also.

Before we get into this business of trust let me give you two functions;

def sigmoid(x):
return tanh(float(x))

def slope_sigmoid(y):
return 1.0-y*y

Let me comment on that slope function there. The slope tells us how “drastic” a small change will make our output and we’ll use this function in order to adjust our weights appropriately. This is important because if we’re at the center of our sigmoid (x=.5) and want to reinforce the weight then we may only need to move it by +.01 but if we’re at an extreme on our curve (e.g. x = -.8) then we may need to adjust the weight by -.1 (i.e. 10 times as much) in order to achieve a noticeable change.

OK, let’s talk about that mythic “trust” factor and in order to do that let’s talk about neural nets. NN’s are build by collecting Neurons, connecting outputs to inputs (not usually circular but they can be) and then stimulating an input layer with a set of values and reading an output layer to see what it produced.

Here’s, in psuedo python, is how I represented a neuron;

class neuron():

name = “”

inputs = []

It’s relatively a simple structure. Neuron’s have a name (which are forced to be unique) and a set of inputs (which is actually a list of dictionaries). An important thing to clarify is that I never actually had to define this class, since CouchDB doesn’t demand a schema; Let’s make this a bit more concrete with three examples;

>>> nn['input_x']
<Document u’input_x’@u’82302167′ {u’inputs’: [{u'node': u'static', u'weight': u'474'}], u’increment’: 0}>
>>> nn['1']
<Document u’1′@u’2027135756′ {u’inputs’: [{u'node': u'input_x', u'weight': 1}, {u'node': u'input_y', u'weight': -1}], u’increment’: 0}>
>>> nn['output_x']
<Document u’output_x’@u’1458836188′ {u’inputs’: [{u'node': u'1', u'weight': 1}, {u'node': u'2', u'weight': 9.536375211640632e+179}, {u'node': u'3', u'weight': -194411155905.33661}], u’increment’: 0}>

Hopefully that shows up ok on your browser. The variable “nn” is a link to the “neural_net” database on my couchdb server;

try:
server = couchdb.Server(‘http://127.0.0.1:5984′)
nn = server['neural_net']
len(nn)
except couchdb.client.ResourceNotFound:
server.create(‘neural_net’)
nn = server['neural_net']
len(nn)

I’ve printed out three neuron nodes; The first node, ‘input_x’, is part of the input layer and you’ll see it has list ‘inputs’ with a single dictionary element { ‘node’: ‘…’, ‘weight’: ‘…’ }. I’ve opted to use the name “static” as a keyword to represent an input which doesn’t point to another node and use the ‘weight’ as the actual input value. The second node ’1′ is more of a typical neuron which would be considered a “second level neuron”. This takes two inputs, one from ‘input_x’ and one from ‘input_y’. The output of “1″ will be;

for input in nn['1']['inputs']

output += get_output(inputs['node']) * sigmoid(input['weight'])

Note I used a function, called “get_output” to find the output value of a node. If the node is static, as ‘input_x’ is, then we could simply dereference it and get the “weight” value but if the input is another “pure” neuron then it may have some calculations to do.You can see how this would work in practice by examining the final node, ‘output_x’. In this case we have to query many nodes just like node “1″ and allow it to do it’s calculation before we can output our values. So a call to “get_output(“output_x’”) actually recurses to the various nodes in turn.

Let me take a moment to diverge from “what I did” to talk about “what I almost did”. I’d intended for “get_output()” to be a CouchDB view and take advantage of quick, asynchronous, lookups. However, if this was done as a view then I’d need the emit function to reference the database and I don’t think this is allowed, i.e. I’d need a map function something like;

Note this won’t, and to the best of my knowledge can’t, work;

function(doc) {
if ( doc['inputs'].length > 0 ) {
for ( i in doc['inputs'] ) {
emit( doc['_id'], “_view/getoutput(doc['inputs'][i])” );
}
}
}

The broken part of that view is the value part of the emit function (remember emit produces key/value pairs). However, since we’re on the topic of couchdb views here’s one way we can build a view to see what inputs a node has;

function(doc) {
if ( doc['inputs'].length > 0 ) {
for ( i in doc['inputs'] ) {
emit( doc['_id'], doc['inputs'][i] );
}
}
}

I also wanted a reduce function to combine the value parts to a single key (so it matched my “data structure” so here’s the reduce;

function(keys, values, rereduce) {
return values
}

The great part of couchdb is that you can input these views in it’s code window and get immediate feedback on what’s being produced! Now I’ll show you the sad part of my design, here’s how to query and act on the view;

#This loop gives us all the inputs to node: name
for input_nodes in db.view(“/nnodes/inputs”, group=True)[name]:
#This loop gives us all the input nodes to node: name
for in_node in input_nodes.value:
if u’static’ in in_node['node']:
output += float(in_node['weight'])
else: #Not a static input
output += get_output(in_node['node']) * sigmoid(in_node['weight'])

What’s sad to me is that it would be less code to query the documents directly;

node = db[str(name)]
for in_node in node['inputs']:
if u’static’ in in_node['node']:
output += float(in_node['weight'])
else: #Not a static input
output += get_output(in_node['node']) * sigmoid(in_node['weight'])

You’ll see that I used the “group=True” parm that I mentioned in my previous post. This just made things match my conceptual model but I wish the python library didn’t force me to dereference .key and .value to get them (it should turn them into a dictionary instead). I’ll also mention that several times I got confused trying ['value'] instead of .value (something that wouldn’t matter in javascript but the former seems more “pythonic”).

I think this is a clear example that I’ve got more to learn about views and better ways to represent my data structures. Here’s a great example which I think will find a lot of analogous fits so read it often.

Back to my situation though, I’d thought maybe each node could store an array called “output_history” which could then be queried with an “increment” value (which would make it a simple emit() process). However, this was much more complicated then it was worth for an initial pass and, since if the value didn’t exist, it would still have to be calculated via a non-Map/Reduce function (because it would have to reference the database).

Before I get into much more detail let me show you the code so you can take a moment to look it over and formulate some thoughts.

I’ll be back with post 3 to try and tie it all together (including a step back to revisit the overall connections, talk more about Neural Nets and my impressions of couchdb).

Posted in code, couchdb, python | 1 Comment