Sunday, 5 April 2015

Reflections

CSC148 has been, hands down, the hardest course I have taken thus far at U of T. Having taken Calculus last semester, I figured that 148 would be an enjoyable vacation from the rigours of Math and the other demanding Life Science courses I have been enrolled in. Programming is, after all, pretty fun right? In spite of the level of challenge this course entailed, the additional challenge posed by the strike,  and the litany of apparent impasses I hit throughout it's duration I still recall wanting to work on my Computer Science assignments more so than I did my other courses. And I have really come away from it with important cognitive developments.

Aside from an introductory experience to concepts in computer science, my biggest takeaway from CSC148 is a meta-cognitive one relating to problem solving. I have not only learnt (and relearnt) the importance of how we approach problems, but also specific strategies and habits that I believe will be of lasting import. 

The general theme of this meta-cognitive lesson is how and when to let go, especially when dealing with a highly complicated and challenging problem that has emotional counter-parts in frustration, anxiety, hopelessness and so forth. There are various points in the long-term process of tackling such a problem that the only pragmatic choice is to forfeit effort, and either retry later or divert attention to a different problem. I will explore a couple that I specifically recall as being vital to my completion of the assignments and to learning how to write recursive functions. 

When speaking with more experienced programmers, one gets the sense that they have a lower degree of confidence in their cognitive faculties than oneself. Substitute "realistic" for "lower", and you have a more accurate view of the psychological picture. It is incredibly important to have a very acute sense of your cognitive limitations in any given scenario: Willpower and computational capacity are both limited, and there is absolutely a diminishing returns point that can be passed with insufficient awareness. This diminishing returns point can actually show up somatically as a sense of muscular strain behind the eyes, and longer-term as substantial cognitive fatigue. This happened to me after A2 and Term Test 2 and I believe that, now, I would be extremely less likely to suffer that same misfortune. 

One concrete lesson is what I call "black-box" problem solving, which is vital to recursion. To avoid thinking out a full trace of what the computer is doing each time you would like understand a fraction of what it is doing, it is important to treat objects and methods like black boxes. You consider what goes into and what comes out of these boxes, but trust their implementation enough (at least for the time being) to avoid pulling it into conscious deliberation. This kind of thinking applies to designing classes and functions, where abstract algorithms have to be designed without excessive distraction from thoughts about how each step will be translated into code. If one part of the system of black boxes is not doing its job, you can visit it to the exclusion of the others. In this way, your mind remains sharply honed-in to one problem, instead of scattered about many in ways that strain working memory. In cases where the problem does get too complicated, but a full-trace is required, drawings can take some of the load off of working memory and facilitate creative associations. 

Another concrete lesson is simply to take breaks. There has been a fair amount of neuroscientific and psychological research into the role of rest in creativity and insight problem solving: Higher resting levels of activity in association cortices (Andreasen, 2011) and reduced outward-orientation as being correlated with insightful "Aha!" moments (Kounios and Beeman, 2009) are two such examples. Anecdotally, I can also speak to this. The relative ease with which my mind would "figure it out" when I had taken a break, especially if that break was fun and rejuvenating, was a replicated experiment. Counter-intuitively, I solved Minimax Prune the morning after forcing myself to go out and drink with friends (against my initial instinct to stay in and continue chipping away). 

Lastly, I learnt that persistence does, in context, pay off. After repeatedly doubting my choice to go with Option A for Assignment 3, in spite of a dysfunctional Minimax from A2, I got Minimax and all of its optimization classes passing all Unit Tests this morning (praise the extension). If I had worked ahead on A3 with a killer-instinct, like I did with A2,  I doubt I would have figured it out...and I know I would have been left depleted for finals. But calm, collected, and calculated persistence is exactly the sort I learnt from CSC148.


Works Cited

Andreasen, N. C. (2011). A Journey into Chaos: Creativity and the Unconscious. Mens Sana Monographs, 9(1), 42–53. doi:10.4103/0973-1229.77424

Kounios, J., & Beeman, M. (2014). The cognitive neuroscience of insight. Annual Review of Psychology, 65, 71-93. doi:10.1146/annurev-psych-010213-115154


Thursday, 2 April 2015

Revisitation Of Minimax (The Official "Revisitation" Post)

Two weeks ago I documented my apparent triumph over Minimax, only to find out that it's finality did not survive the scrutiny of doc tests and compatibility with A3 optimizations. At this point, I would like to offer some concluding remarks on a (still) incomplete Minimax/A3 and about the learning experience Minimax has entailed for me. In the future, when I think CSC148 I will think Minimax, likely as some personified entity the likes of which will reveal itself as this semester is consolidated in memory and more perspective develops. However, in the mean time, I still think I have a few words to say.

Technically, I am still unsure of my code. I have managed to pass all official Unit Tests except for one, which appears to have been elusive to other students (see http://adamosslog.blogspot.ca/) for reasons not directly related to Minimax's effectiveness. Specifically, this involves a winning start after the Unit Tests generates a Tippy grid. Debugging this last test will have to be a patient, clever trial-and-error process that really has to factor in all of the possibilities. The problem arising from the TippyGameState code is a best case scenario, with a worst-case being some deep-seated flaw in Minimax that will require a complete revamp. My guess is either the latter or a minor tweak in Minimax; it seems unlikely to pass all Subtract Square tests and be completely off.

Of course this begs the question: Why am I still pursuing A3 with an incomplete Minimax? There are several contributing factors here, but the primary one is simply that I wanted to. I got interested in AI search algorithms, have a persistent disposition, and really did not think that the finish line was too far off. I didn't seek enough help for A2 so I factored in that, with more help, I would be able to crack Minimax quickly and get on to the optimizations. Minimax itself proved to be a challenge even for helpful TA's, with the strike obviously factoring in to the level of preparation they had for A3 as well as the available aid for my initial stab at Minimax in A2. By the time I realized what I had gotten myself into, I was too close to the deadline to restart (creating a whirlwind of stress, for 6% of my mark, in a sensitive time before finals).

In the end, the real mistake I made was  assuming that my Minimax worked before Unit Testing, thus allocating my resources to optimizations of a flawed foundation. However, I still believe that I stand on optimistic grounds. Currently, my Minimax is one Unit Test away from full pass, the code of my optimizations makes perfect logical sense (evaluated by TA third-parties), was designed for a Minimax that isn't too far off of my latest version, and I have learnt an immense amount in a process for which transient regret ("I should have taken Option B!") is regularly replaced by a more productive process-orientation that leaves me confident that I'll bounce back from whatever negative consequences I may have accrued.

To address some algorithmic and implementation details: Two posts ago I mentioned what I perceived to be a genuine stroke of insight about the way Minimax had to function. With my recursive "score checking" in a get_score function, I believed that its base cases had to examine two moves ahead so that each full evaluation only looked at special opponent cases where the opponent played themselves into a loss, then made a recursive call on the next GameState where the computer was the current player. This was based a real misunderstanding of Minimax, which I rectified via discussions with Professor Heap and some "rigorous" hours paroozing YouTube. Minimax is supposed to make its simulated opponent as savvy as possible. In traditional versions of Minimax floating around the web ether, there is a "Minimizer" and a "Maximizer" (hence the name "Minimax") that take turns. The Maximizer's possible moves are whatever the Minimizer serves up from its possible moves, and vice-versa. This sets us up straightforwardly for pruning: The Maximizer sets a lower boundary for what values its will accept from calls to Minimizers, thus allowing us to recognize when to stop computing values the Maximizer will ignore anyways. The Minimizer also sets boundaries in an analogous manner.

The Minimax of CSC148 is most usefully thought of in terms of +1/-1, instead of a Maximizer and Minimizer, but a similar logic applies. As such I set out to create a get_max_score and get_worst_score functions to represent the competitors, then collapse them both into a _get_score helper that took a parameter for either +1 or -1. _get_worst_score lacked that parameter, simply returning _get_score(state, -1).

Upon failing multiple Unit Tests, I began to clean the code up. Humair Kahn and his assignment partner were incredibly helpful here, pointing out a HUGE mistake I was making (born of an overly-ambitious attempt at A2). I was incorporating bits of pruning into my original Minimax without realizing it!! get_score stopped computation upon seeing its first +1, and suggest_move returned the first move leading to a GameState with a +1 score. This created a huge headache for me in A2, and is illustrative of a general problem I have with academic assignments: Over-complication. Computer science, at the moment, is challenging for me in the way that Philosophy was when I initially decided to major in it (one degree ago). Simple, structured thought is more difficult for me than scattered creativity. Interesting research in Neuroscience and Psychology actually points to trade-offs between single-pointed attention and creativity (often associated with open attention and wandering thoughts), with the challenge for me being the former. Comp sci is a great exercise in that, and actually helps me productively channel creative thinking.

After dumbing down my basic Minimax to a version that straightforwardly fit the recommended algorithm in A2, I am now the mere Unit Test away from throwing my arms up and climbing atop a tall structure in my underwear. If that ends up happening or not, I have no regrets about the choice to attempt closure with Minimax. It has been bumpy, frustrating, but never boring.

Thursday, 26 March 2015

Unit Tests: Before and After

After learning, and re-learning, that the best way to write a sophisticated program is to do extensive algorithmic planning before even looking at an IDE I have decided to take a novel approach to Assignment 3: Writing unit tests before implementing my classes.

This does a few things. First off, it familiarizes me with how class will be structured before I start implementing it. I get to think about what kinds of properties and methods it needs, but I am still a safety-layer away from actual implementation code. I am therefore thinking about what my class needs to do, as well as (to a helpful degree) how it will do it in a way that baby steps me towards filling in the details. Then, when I actually begin to implement my class, I will be productively haunted by the test cases so that I proceed gently and carefully, bearing in mind the totality of what criteria my code must meet for the client. Rushing to patch up a bug with code that creates three more bugs should be more difficult.

Second off, when my class is fully implemented I will have test cases ready to go. This allows me to test my class while implementation details are still fresh in memory, instead of diverting attention to creating Unit Tests (which may reveal things that cause me to actually redesign my class) and then trying to find bugs in code that I have a vaguer recollection of. Furthermore, with general tests cases in place, I can change code to address bugs while still having firm criteria in place for when my class is back to regular performance. At this point I can even design more savvy test cases to find specific bugs, while remaining assured that I know what my code must do before it gets shipped.



Monday, 23 March 2015

Slaying The Foe Of Minimax

*Official "revisitation" post is on April 2nd

Finally! After multiple revisitations, I finally managed to crack Minimax. Shipping the non-functional code for assignment 2 was a disappointing experience, albeit slightly relieving because I could now justify my withdrawal from the agony of trying to get it to work like the doc string says.

The problem? My get_score function did not handle recursive calls in a way that actually fit GameState's properties. I split Minimax into two functions: suggest_move to return a move to the game state, and get_score to see what the best move(s) were for the computer. Most of the heavy lifting was done in get_score, which would check the GameState it was passed first and (pending a non-terminal state) would proceed recursively until it found finished games. Where I ran into trouble, and where I will guess many others did too, is with how many levels down (to analogize possible GameStates to a tree) the function checked.

If get_score begins by asking "Can I win?" of the current GameState, it is left with a response that satisfies a base case. The game is either over (leading to a win, lose or tie), or the game is not over and the possible subsequent game states must be assesed from the frame of reference of the same player. The answer may seem simple: Because of our game's zero-sum nature, we assume that the score of Minimax's opponent can simply be multiplied by minus one; but this does not really inform us of what the possibilities are for the computer. Supposing, at level 2, the game was still incomplete and the game is winnable for the opponent. This does not mean that the game is not winnable for Minimax! The only case we care about at this level, is if the computer has won or tied the game.

What I had to do was go two layers below any game state passed into get_score, to get to the next state where the computer was the state.next_player. This subsequent GameState could be asked, again, "Can I win?" and the framework would therefore be set for a recursive algorithm. Each recursive call would therefore not only check the GameStates one move away, but also the ones two moves away. The next recursive call would start where the last one left off, resetting the state.next_player to the computer.

Friday, 13 March 2015

Creativity In Programming

While working through lab 7, I had the benefit of experiencing a brief "aha" moment that I am less familiar with in my humanities experience. Sitting with a problem, deliberating to the point of diminishing returns, taking breaks, and finally having the solution "emerge from the ether" has an inherent pleasure that makes me begin to understand how it is that so many accomplished scientists have forgone much of 21st century Western leisure in exchange for vocational commitment.

In computer science, this takes an interesting form: Elegant solutions to seemingly unsolvable problems. These elegant solutions, when combined, give us the sophisticated functionality that takes from Abstract Data Structures right through to cars that can drive themselves. In the case of linked lists, the example I am writing about is fairly simple: How it is that one programs into a data structure the capacity to add or remove data elements. We take the apparent simplicity of this problem for granted, because (as introductory programmers) we are so used to having this problem handled for us in pre-implemented data structures. However, when creating data structures from scratch one has to do the creative heavy lifting oneself.

The elegance lies in a simple trick: Point the prior element's "next" property past the current element to delete the current element. Garbage collection handles the rest. These "out of the ether" solutions take a creative form, and are incredibly powerful. Another one, discussed last class, allows us to delete elements from a Binary Search Tree: Either replace the deleted element with the rightmost element in the left sub-tree, or the leftmost element in the right sub-tree. This is another clever solution that allows data structures to perform in intuitive ways for clients, and allows them the benefit of taking the creativity on the back-end for granted. The extent to which our clients can do this can be framed as a measure of our success as developers. 

Sunday, 8 March 2015

Thoughts on Artificial Intelligence

So far in the course, our strategy classes have acquired an increasing degree of intelligence: In assignment 1, we used a computer strategy that simply picked a random move for the computer. In assignment 2, we were required to create a strategy that led the computer to winnable game states.

While planning the Minimax class, I was struck by a relation to a Cognitive Science course I took with Professor Vervaeke. While the Touring Test is often considered to be criteria by which we can judge a computer to have "human-like" intelligence, it neglects key components of how it is that we achieve intelligence which may be essential to what intelligent behaviour we can actually perform. Here is one distinction between computer algorithms and human intelligence: While the algorithms of a class such as Minimax must compute all possibilities until they arrive at one that they are programmed to look for, the human mind is somehow able to automatically discount an enormous amount of data "out there" without having to compute it at all. Take, for example, a chess game: The brain does not need to process the combinatorially explosive range of possible sequences before it picks a favourable one. The ability to pick courses of action that cohere with underlying imperatives and incentives comes with an equal ability to discount courses of action that are irrelevant to said motives: Professor Vervaeke calls this "relevance realization".

While relevance realization is a "how" rather than a "what" (an implementation detail, rather than an output), its mimicry is not just essential to an actual working model of the human mind. It may actually be essential to mimicking the mind's output as well. While a computer can be programmed to handle domain-specific tasks such as chess, navigation and so forth, the brain (and consequently the mind) is a machine capable of incredible degrees of plasticity. It can compensate for functional damage by constructing new pathways, it can master novel challenges through repetition, and it carefully yet brilliantly controls what information is processed both consciously and subconsciously and what is simply not computed at all. All of this is taking place in an incredibly dynamic internal and external environment, while factoring in quantities of data that would be impossible to consider at the conscious level. Consider the amount of data required to simply make you flinch out of the way of a projectile object: Trajectory, distance, the object itself, sorrounding circumstances (would you flinch into oncoming traffic?), and so forth.

The brain does not respond to its circumstances in a static manner, either: While a computer can be programmed to avoid projectile objects, if you were to place it next to an open flame it may very well avoid an incoming object by jumping into a fiery dissolution. To alter that unintended consequence, programmers and engineers would have to manually add additional behaviour, and the cycle would repeat itself. Following this developmental order, it may be reasonable to suppose that human-like intelligence will never really be repliated: The best we can do is produce robots that are indistinguishable from humans in very specific performance domains.

What makes a human brain, or even a bird's brain, so impressively intelligent should begin to jump out at you: It obviously transcends the specific algorithms by which life forms accomplish discerete tasks. The transcience of these algorithms points to an underlying imperative, by which an organism constantly devises new sequences of behaviour, metabolism, thought (in the case of humans), and so forth. The imperative to survive and reproduce has granted us, via millions of years of natural selection and spontaneous mutation, an incredible array of adaptive faculties and new ones that can evolve in the course of a life time (for example, skill mastery).

Whether it is possible to program a machine to have such an imperative, by which it can be let loose in the world only to self-organize and co-develop new forms of intelligence alongside a dynamic environment, is beyond me. Logically, nothing seems out of bounds here. As a materialist, who long ago reliquished belief in philsophically replete notions of immortal souls and "free will", I don't see any inherent contradiction. A computer, being made of matter in the same way that a brain is, shouldn't be limited in any fundamental regard. The question is whether the Darwinian imperative of life can be packaged in an algorithm to give AI an evolutionary starting point, and if not, how that imperative could somehow be installed in a machine while avoiding an infinite regress of pre-programmed algorithms 

Saturday, 28 February 2015

Class Design

***Recursion covered in last blog.

Laziness and over-complication reach an interesting nexus at the beginning of class design, where the temptation to jump straight into implementation details can be overwhelming. One has a flash of insight into how, generally, the class will operate then simply picks up the keyboard, cracks a Red Bull and pounds away lines of code like the main character in HBO's Silicon Valley. Like many things, as a beginner it is best not to imitate "professionals".

The real professional move is to begin designing your class abstractly: Focus on doc strings, use mind maps and flow charts, do some quality thinking. Treat your algorithms abstractly as well: "if the node is not a leaf, evaluate its children", "if the item is a list, flatten it", etc. The point is to think out the behaviour and relationships that objects (or functions) have, and then begin implementing; otherwise you are bound to get confused by your own implementation details, backtrack often and generally make mistakes. The real unfortunate part is the psychological investment we have in our work: Once we have created something, we are less inclined to give it up regardless of the practical consequences.

With recursive functions there is a level of "magical" trust you must develop (which I wrote about in my last blog) that your recursive calls will simply work; this is in order to prevent you from thinking out the entire trace. Class design requires less of a faith-leap, but does require more deliberation spent on what it is this object will do. When that is done, the how seems to follow more naturally. Conversely, one could spend a few minutes thinking about what kind of object a Subtract Square Game State must be like and then simply rush into the code. On line 300 they may realize that they have actually bundled half of the interface code into the game state, and then spend hours separating the two by rewriting methods and doc strings. Yuk.

So, like many things in life, the disciplined thing to do is actually the one that gives you the easiest time.

Friday, 13 February 2015

Trusting Your Technique

As a beginner, it is easy to approach algorithmic programming problems by considering every implementation detail relevant to the problem at hand. Consciously running over every line the compiler hits, keeping the changing values of variables in your own working memory, and generally tracing everything a method does in order to find out the important thing it does. However, object oriented programming teaches you, very quickly, not to do this.

One of the beauties of object oriented concepts such as public/private interfaces (which take a strange form in Python) is that you can know what a method does, without having to know how it does it. The developers behind the method were spared the luxury of being able to flip a wand and have an algorithm appear, however there is an interesting caveat to being a developer and interacting with your own code.

When you create a function, you (in some senses) become a client of your own code. You stop tracking what happens to data once it goes in and squeezes its way through the cumbersome implementation details of your method bodies. This sounds obvious, but for me it actually requires discipline to habituate. 

It is my general tendency to approach difficult matters from the maximum level of complexity: Let's consider all of the steps, possibilities, and moving parts so that we imprint as accurate a model of the problem and solution in our working memories as possible. However, past a point of bare-bones simplicity this is simply too much of a cognitive strain to be productive, or even realistic. 

Recursion was the real guru for me on this one. Given a recursive problem, it is easy (for me, at least) to fall into the trap of trying to trace each recursive call to see if function will give me the desired output. When given a simple problem to address recursively, such as sorting nodes in a tree, it can be easy to marvel at the level of intelligence your code may need: How does it know whether a node has children? How does it know how to order items in the list it returns? If there are operators in the nodes, how can it "know" to put them in the right places? Your mind goes right from the problem to the maximum level of complexity.

However, I was shown quickly that this was the cause of my troubles. As in combative sports, you have to trust your technique. In my last lab, it was repeatedly emphasized to follow the prescribed steps for solving recursive problems. The steps provided may not be the best ones for every person, but the general point stands: Without a reliable process, a beginner's mind can easily get swept away with the apparent complexity of the matter and a cognitive crash can ensue.

Address the simplest (base) case first; already you have taken care of a huge amount of the work. Now you have a foundation from which to proceed: You know what a good amount of your subsequent recursive calls will return. From then on it's a matter of following your docstring, and structuring your recursive calls so that your function returns what it says it will return. If it returns a the maximum integer in a nested list structure, return the maximum of a list of your recursive calls. Your base case and your docstring can provide you with stable ground from which to structure the intimidating "else" clause in recursive functions.

Apparently writing recursive functions gets easier, I'm looking forward to it.




Tuesday, 3 February 2015

Abstraction For A Concrete Reason

Throughout my entire Philosophy BA I wondered if my calling in life was to find some intellectual ivory tower within which to consider highly abstract matters, with a vague hope (but no requirement) that someone, somewhere would put my ideas to use. Since enrolling in the computer sciences I have learnt that this was never the case, and have actually gained insight about the process of learning itself.

I had a chemistry professor make an interesting remark the other day, regarding a highly arbitrary naming system for 3D molecular structures with a chiral centre: "Some of you students are mathematically minded, so when I tell you that something's arbitrary you sit back and relax. Then there's a bunch of you that get all touchy feely and want to know the reason for everything". In one witty sentence, this essentially summated my experiences learning maths and sciences throughout high school and even to this day.

Computer science makes use of highly abstract concepts: Recursion, inheritance, object-orientation and so forth. Even when applying these concepts in the form of computer code, one can get the sense that they are engaged in an abstract symbol-manipulation ritual alongside the likes of math, symbolic logic and other "purely intellectual" problem solving domains. That is not to say that these areas of expertise do not have their applications; much of what we consider to be integral to modern, civilized society depends on the applications that they do have. But what is interesting about the computer sciences is how quickly and intimately you are acquainted with its applications.

As one learns to code, they get the feeling that they are perpetually mere inches away from the capacity to build the next trendy app. The feedback loop involved is incredible: As soon as basic syntax is covered, you can "do something" with the code you write within weeks. Whether that be a basic game, or a simple script that sorts information, you constantly relate this to programs/devices with similar functionality that shape your life (and your pocket book).

In reality, a beginning programmer is likely years away from being able to build the next Tinder. However, I was never treated like it. I learnt to code in certification programs at Ryerson University, and despite my apparent skill level (or lack thereof) I was always spoken to by my teachers and peers as if I had a mere "few things" to learn before being able to whip up a fully functional iOS app. Eventually, my capacities caught up and I did just that by the end of the semester.

So in spite of the highly abstract, logically-detached nature of the code itself there is another side to computer programming that grounds it in the material world very beautifully, and attracts not just the abstract-logical types but the hands-on pragmatists and the creatives as well. It took me a university degree to figure this out, but I am interested in the tools of the former insofar as they serve the latter's ends. And so whether it be from the democratization of programming culture, or the quick feedback loop in learning to code, I find myself actually enjoying highly abstract, algorithmic problems for what may be the first time in my life.

Sunday, 25 January 2015

Should Geeks, Write?

Joel Spolsky’s piece “Advice For Computer Scientists” beautifully voiced an intuition that many of us, current or former, arts students share regarding the sciences: You guys are really smart, but oh my…. would you ever benefit from some of what’s happening over on our side? 

As a (relatively) mature student in the foreign, yet fascinating, world of technical expertise I try to impart the one piece of advice I can when I run into my younger counterparts: take philosophy courses. 

Although, as a variety of tech bloggers note, the need in computer programming for clear-cut commenting and informative debugging logs is substantial, the issue really runs deeper than this. Yes, programmers need to know how to write; but they also need to learn how to think in the way that writing, at least in the humanities, affords. 

Why do we write code in the first place? Why do we engineer machines? People can take writing courses to improve rhetorical capacities, to communicate better, to sound more marketable, but oftentimes the how is directly derivative of the why. A conviction that one’s creative fruits will make profound and lasting changes in the world is often more inspiring, for potential buyers and investors, than an intrinsic joy or talent for the craft alone. We are our clients' greatest asset when we can understand abstract relationships that extend beyond those between data structures, but into interfaces between the technology we make and the world we make it for. It may pertain to machinery that will reduce our impact on the environment, or a new programming language that is easier to learn and easier to understand: In any case, it starts with the capacity to notice a problem with the grander status quo and think “outside-of-the-box” as to how to fix it. This kind of thinking is cultivated directly in humanities-based writing.