Tuesday, October 30, 2012

Unit Testing an Artificial Neural Network

I am working on a Big Data experiment where I am using artificial neural networks to classify different data sets into conforming and non-conforming patterns and I needed a good artificial neural network library in C#.Net.

I surveyed a number of implementations and was dismayed that I could not find a good one. I was even more dismayed by the number of  blog posts and code articles that had deeply flawed implementations, where someone couldn't expect to get these implementations to work in test, much less production.

So... because I couldn't find a good implementation, I built my own library into my Big Data application. I am going to play the implementation details close to the chest, but I wanted to share one of my unit tests that I developed for the Backpropagation algorithm since it was time consuming to work out an example in Microsoft Excel. I could not find any other worked examples online, so I built an example by hand in Microsoft Excel for the following network:



I use both weights on the adjacencies and a threshold/bias factor for each node and I used the hyperbolic tangent function for the activation function. Below is the Visual Studio Unit Test showing the worked example. For simplicity, I round everything to 6 decimal points for test purposes.


[TestMethod]
 public void TestBackpropagationMultilayerUntrained()
 {
     //Arrange
     NeuralNetwork n = new NeuralNetwork("BackProp3LayerTest", "Back Propagation Test for 2 Processing Layers", new HyperbolicTangentActivationFunction(), 3, 3, 2, 3);
    
     n.layers[0].Adjacencies[0][0].Weight = .75D;
     n.layers[0].Adjacencies[1][0].Weight = -.75D;
     n.layers[0].Adjacencies[2][0].Weight = .75D;

     n.layers[0].Adjacencies[0][1].Weight = -.8D;
     n.layers[0].Adjacencies[1][1].Weight = .8D;
     n.layers[0].Adjacencies[2][1].Weight = -.9D;

     n.layers[1].Nodes[0].Threshold = .5D;
     n.layers[1].Nodes[1].Threshold = -.5D;

     n.layers[1].Adjacencies[0][0].Weight = .4D;
     n.layers[1].Adjacencies[0][1].Weight = -.5D;
     n.layers[1].Adjacencies[0][2].Weight = .6D;

     n.layers[1].Adjacencies[1][0].Weight = -.4D;
     n.layers[1].Adjacencies[1][1].Weight = .5D;
     n.layers[1].Adjacencies[1][2].Weight = -.6D;

     n.layers[2].Nodes[0].Threshold = .1D;
     n.layers[2].Nodes[1].Threshold = -.1D;
     n.layers[2].Nodes[2].Threshold = 0D;


     BackPropagationLearning l = new BackPropagationLearning(n);

     double[] input = { .5D, -.5D, .75D };
     double[] output = { 1D, -1D, 1D };
     double error;

     //Act

     error = l.Step(new List<double>(input), new List<double>(output));

     //Assert

     //Total error E
     Assert.AreEqual(.085699D, Math.Round(error, 6));
    
     ///////////////////////Verify Deltas///////////////////////////
     //Input layer (0)
     Assert.AreEqual( .018949D, Math.Round(l.deltas[0][0],6));
     Assert.AreEqual(-.018949D, Math.Round(l.deltas[0][1], 6));
     Assert.AreEqual( .019989D, Math.Round(l.deltas[0][2], 6));

     //Hidden layer (1)
     Assert.AreEqual( .014179D, Math.Round(l.deltas[1][0], 6));
     Assert.AreEqual(-.010394D, Math.Round(l.deltas[1][1], 6));
    
     //Output layer (2)
     Assert.AreEqual( .154514D, Math.Round(l.deltas[2][0], 6));
     Assert.AreEqual(-.083378D, Math.Round(l.deltas[2][1], 6));
     Assert.AreEqual( .061175D, Math.Round(l.deltas[2][2], 6));

     ///////////////////////Verify Threshold Updates/////////////////
     //No threshold updates for input layer
     Assert.AreEqual(.0D, l.ThresholdUpdates[0][0]);
     Assert.AreEqual(.0D, l.ThresholdUpdates[0][1]);
     Assert.AreEqual(.0D, l.ThresholdUpdates[0][2]);
    
     //Hidden Layer (1)
     Assert.AreEqual( .001418D, Math.Round(l.ThresholdUpdates[1][0], 6));
     Assert.AreEqual(-.001039D, Math.Round(l.ThresholdUpdates[1][1], 6));
    
     //Output Layer (2)
     Assert.AreEqual(.015451D, Math.Round(l.ThresholdUpdates[2][0], 6));
     Assert.AreEqual(-.008338D, Math.Round(l.ThresholdUpdates[2][1], 6));
     Assert.AreEqual(.006117D, Math.Round(l.ThresholdUpdates[2][2], 6));

     ///////////////////////Verify Weight Updates/////////////////
     //Input layer (0) - Hidden Layer (1)
     Assert.AreEqual(.000709D, Math.Round(l.WeightUpdates[0][0][0], 6));
     Assert.AreEqual(-.000520D, Math.Round(l.WeightUpdates[0][0][1], 6));

     Assert.AreEqual(-.000709D, Math.Round(l.WeightUpdates[0][1][0], 6));
     Assert.AreEqual(.000520, Math.Round(l.WeightUpdates[0][1][1], 6));

     Assert.AreEqual(.001063D, Math.Round(l.WeightUpdates[0][2][0], 6));
     Assert.AreEqual(-.000780D, Math.Round(l.WeightUpdates[0][2][1], 6));
    
     //Hidden Layer (1) - Output Layer (2)
     Assert.AreEqual( .014649D, Math.Round(l.WeightUpdates[1][0][0], 6));
     Assert.AreEqual(-.007905D, Math.Round(l.WeightUpdates[1][0][1], 6));
     Assert.AreEqual( .005800D, Math.Round(l.WeightUpdates[1][0][2], 6));

     Assert.AreEqual(-.014868D, Math.Round(l.WeightUpdates[1][1][0], 6));
     Assert.AreEqual( .008023D, Math.Round(l.WeightUpdates[1][1][1], 6));
     Assert.AreEqual(-.005886D, Math.Round(l.WeightUpdates[1][1][2], 6));

     ///////////////////////Verify Final Weights and Thresholds/////////////////
     //Input layer (0) - Hidden Layer (1)
     Assert.AreEqual(0.750709D, Math.Round(n.layers[0].Adjacencies[0][0].Weight, 6));
     Assert.AreEqual(-0.800520D, Math.Round(n.layers[0].Adjacencies[0][1].Weight, 6));

     Assert.AreEqual(-0.750709D, Math.Round(n.layers[0].Adjacencies[1][0].Weight, 6));
     Assert.AreEqual(0.800520D, Math.Round(n.layers[0].Adjacencies[1][1].Weight, 6));

     Assert.AreEqual(0.751063D, Math.Round(n.layers[0].Adjacencies[2][0].Weight, 6));
     Assert.AreEqual(-0.900780D, Math.Round(n.layers[0].Adjacencies[2][1].Weight, 6));

     //Hidden Layer (1)

     Assert.AreEqual(0.501418D, Math.Round(n.layers[1].Nodes[0].Threshold, 6));
     Assert.AreEqual(-0.501039D, Math.Round(n.layers[1].Nodes[1].Threshold, 6));

     //Hidden Layer (1) - Output layer (2)

     Assert.AreEqual(0.414649D, Math.Round(n.layers[1].Adjacencies[0][0].Weight, 6));
     Assert.AreEqual(-0.507905D, Math.Round(n.layers[1].Adjacencies[0][1].Weight, 6));
     Assert.AreEqual(0.605800D, Math.Round(n.layers[1].Adjacencies[0][2].Weight, 6));

     Assert.AreEqual(-0.414868D, Math.Round(n.layers[1].Adjacencies[1][0].Weight, 6));
     Assert.AreEqual(0.508023D, Math.Round(n.layers[1].Adjacencies[1][1].Weight, 6));
     Assert.AreEqual(-0.605886D, Math.Round(n.layers[1].Adjacencies[1][2].Weight, 6));

     //Output Layer (2)

     Assert.AreEqual(0.115451D, Math.Round(n.layers[2].Nodes[0].Threshold, 6));
     Assert.AreEqual(-0.108338D, Math.Round(n.layers[2].Nodes[1].Threshold, 6));
     Assert.AreEqual(0.006117D, Math.Round(n.layers[2].Nodes[2].Threshold, 6));

     ///////////////////////Verify Consistent Movement/////////////////

     double lasterr = error;

     for (int i = 0; i < 10; i++)
     {
         lasterr = error;

         error = l.Step(new List<double>(input), new List<double>(output));

         Assert.IsTrue(lasterr >= error);
     }

 }
-->


Friday, October 5, 2012

Windows Symbolic Links and File Sharing

Symbolic Links, Hard Links, and Junction Points are useful tools for an experienced administrator to manipulate the file system to bring things in different locations under a single logical tree. Symbolic Links have been posssible to create since Windows 2000 (using the linkd.exe, mountvol.exe, and delrp.exe utilities from the Windows 2000 Resource kit), but only in the most recent versions of Windows (Windows Vista, Windows 7, Windows 8, Windows Server 2008, Windows Server 2008 R2, and Windows Server 2012) has the mklink utility been provided with the OS to create symbolic links. The original functionality in Windows 2000 was called the NTFS reparse point, which is basically just a file system object with extended information. This functionality isn't particularly well known, but it is useful in a wide variety of scenarios.

By default, users in the local administrators group have the ability to create symbolic links, but this permission can be granted by modifying the "Create Symbolic Links" user right:



There are a lot of potential uses for symbolic links, but some of the ones that I've dealt with are:
  • A static content directory in IIS needs to be available at multiple points in the site/application tree so that pages do not need to use absolute or relative references that point outside of the current logical directory or a particular piece of content needs to appear at multiple points in the site.
  • A user wants to double click a folder in the "My Documents" folder and be able to access the root of the C: drive (note that this is not a shortcut)
  • A developer needs to create a separate tree that includes files used for unit tests, but wants changes to the "primary" source tree to be instantaneously propagated to the tree used for unit testing (I've used this one myself during the development of complex Latex/pdf documents that need to be generated with ASP.Net)
  • Scripts need to be developed that access other parts of the filesystem from a single folder.
  • The same file needs to be accessed by multiple names
Now that we understand what they are and some of the use cases, let's look at how to create/use them. The basic syntax of the command is

c:\symlinktest>mklink 
Creates a symbolic link. 
 
MKLINK [[/D] | [/H] | [/J]] Link Target
 
        /D      Creates a directory symbolic link.  Default is a file
                symbolic link. 
        /H      Creates a hard link instead of a symbolic link. 
        /J      Creates a Directory Junction. 
        Link    specifies the new symbolic link name. 
        Target  specifies the path (relative or absolute) that the new link
                refers to.  

Directory Hard Link

Long story short, you can't make a directory hard link. The mklink utility doesn't give a particular error, just "access is denied:"

c:\symlinktest>mklink /H test2 test
Access is denied.

c:\symlinktest>mklink /D /H test2 test
Access is denied.

Why can't a directory hard link be created? Because each directory has a pointer to its parent directory. In the case of a hard link, there would be ambiguity as to what the parent directory actually is because the hard link is actually another entry in the master file table (MFT). Directory hard links would also create the possibility of infinite recursion through the filesystem.

File Hard Link


Hard links create an additional pointer in the master file table (MFT) for a particular file, but with a different name. Hard links can be deleted, but the file will not be deleted until all of the hard links that reference the file are gone. When a hard link is created, the target has to exist (because it points to an existing file). Additionally, the file and the hard link have to exist on the same volume (this is the same as the Linux/UNIX world since Windows is POSIX compliant).

In this example, I created a file (important.txt) that I want to edit by another name (important2.txt),

c:\symlinktest>mklink /H important2.txt important.txt
Hardlink created for important2.txt <<===>> important.txt

Looking at the directory, the files look the same (and they are the same). Permissions are set on the file object, so changing the permissions on one hard link changes it on both of them.

 Directory of c:\symlinktest

10/05/2012  02:17 PM    <DIR>          .
10/05/2012  02:17 PM    <DIR>          ..
10/05/2012  02:10 PM                 0 important.txt
10/05/2012  02:10 PM                 0 important2.txt
10/05/2012  02:02 PM    <SYMLINKD>     system32 [c:\windows\system32]
10/05/2012  01:57 PM    <DIR>          test
10/05/2012  01:58 PM    <SYMLINKD>     test2 [test]
               2 File(s)              0 bytes
               5 Dir(s)  694,212,771,840 bytes free

From a file sharing perspective, a hard link can exist to a file outside of the root of the share (but on the same storage volume on the server) and be accessible to users who have share/NTFS permissions to the file.

File Symbolic Link


NTFS file symbolic links are filesystem objects that are different from shortcuts (.lnk files), but point to either a relative or absolute path of a file. These links are created without the /H option with mklink,

c:\symlinktest>mklink important2.txt ..\symlinktest\important.txt
symbolic link created for important2.txt <<===>> ..\symlinktest\important.txt

c:\symlinktest>mklink important3.txt c:\symlinktest\important.txt
symbolic link created for important3.txt <<===>> c:\symlinktest\important.txt

Looking at the links,
...
10/05/2012  02:10 PM                 0 important.txt
10/05/2012  02:33 PM    <SYMLINK>      important2.txt [..\symlinktest\important.txt]
10/05/2012  02:33 PM    <SYMLINK>      important3.txt [c:\symlinktest\important.txt]
...

In Windows Explorer, these look like shortcuts, but aren't.



The properties are greyed out and cannot be edited. Symbolic links do not have to point to a target that exists and can point between drive letters and volumes. From a file sharing perspective, a symbolic link that points outside of the shared directory structure is inaccessible (Errors like 'Operation not supported' and 'the network path was not found' are common). Relative path symbolic links that point to files within the same share structure are accessible, as are symbolic links that point to UNC shares, but this has a tendency to create a lot of complexity in a file sharing environment. Additionally, remote-remote and remote-local symlinks are disabled on clients by default. See below for more details.

Directory Symbolic Link


The Directory symbolic link is essentially the same as the file symbolic link, but the target is a directory instead. Here is a brief example:

c:\symlinktest>mklink /D test2 test
symbolic link created for test2 <<===>> test

Directory of c:\symlinktest

10/05/2012  02:17 PM    <DIR>          .
10/05/2012  02:17 PM    <DIR>          ..
10/05/2012  02:10 PM                 0 important.txt
10/05/2012  02:10 PM                 0 important2.txt
10/05/2012  01:57 PM    <DIR>          test
10/05/2012  01:58 PM    <SYMLINKD>     test2 [test]
               2 File(s)              0 bytes
               4 Dir(s)  694,212,771,840 bytes free


Directory Junction Point


Junction points act more like hard links than symbolic links and are specifically for directories. They are created with the /J option of mklink and they can be traversed just like a directory. Remote-Remote symbolic links (see below) do not need to be enabled because it is not technically a symbolic link, but rather a file object that allows a directory to be linked at multiple points in the filesystem. 

As an example, we will create a ZZZ folder that traverses to c:\windows:

c:\symlinktest>mklink /J ZZZ c:\windows
Junction created for ZZZ <<===>> c:\windows

c:\symlinktest>dir
...
10/05/2012  03:10 PM    <JUNCTION>     ZZZ [c:\windows]
               4 File(s)     19,577,576 bytes
               8 Dir(s)  694,211,403,776 bytes free

Accessing this junction from a share allows the server's c:\windows directory to be traversed, even though only the c:\symlinktest folder is shared. If the user has administrative permissions, then they can change files remotely.

If you make an error and create one for a file, it'll create, but won't work:

c:\symlinktest>mklink /J test.exe  FEPInstall.exe
Junction created for test.exe <<===>> FEPInstall.exe

Accessing the test.exe folder will fail with "The directory name is invalid"


Deleting a Symbolic Link

You can delete a symbolic link or junction point the same way that any other file can be deleted (Remote-Item in PowerShell, del in cmd, or right click -> delete in Windows explorer).

Dealing with "The symbolic link cannot be followed because its type is disabled"


As a security measure, symbolic links on file shares are not followed. You can see what the current behavior is by running  fsutil behavior query SymlinkEvaluation:

Here is the default behavior for symlinks:

c:\symlinktest>fsutil behavior query SymlinkEvaluation
Local to local symbolic links are enabled.
Local to remote symbolic links are enabled.
Remote to local symbolic links are disabled.
Remote to remote symbolic links are disabled.

To enable remote-remote symlinks, run fsutil behavior set SymlinkEvaluation R2R:1

c:\symlinktest>fsutil behavior set SymlinkEvaluation R2R:1

c:\symlinktest>fsutil behavior query SymlinkEvaluation
Local to local symbolic links are enabled.
Local to remote symbolic links are enabled.
Remote to local symbolic links are disabled.
Remote to remote symbolic links are enabled.

I wouldn't recommend enabling remote to local symlinks, but this is also possible.

Dealing with "Location is Not Available"



"Location is not available: %s refers to a location that is unavailable. It could be on a hard drive on this computer, or on a network. Check to make sure that the disk is properly inserted, or that you are connected to the Internet or your network, and then try again. If it still cannot be located, the information might have been moved to a different location"

If you get this error, your link isn't pointing to the right place, or the user has a different view (ex. mounting a share farther down in the tree than he/she should be) than the link was put in place to support. Look at the link and make sure it points to the right place. Access the share as the user and see if the path that the link references actually exists from the end user's perspective.

Wednesday, October 3, 2012

How to Mount a DFS Share in Linux

Microsoft Distributed File System (DFS) is a technology that allows multiple servers to host a single file share (providing fault tolerance and performance enhancement for multi-site Active Directory topologies). It is typically used in conjunction with a replication technology such as DFS-R (R is for Replication). Though these features have similar names, you don't have to have DFS to use DFS-R and vice versa (A typical use case might be the desire to replicate folders between servers, but not share them, which is accomplished via DFS-R without using a DFS namespace).

Windows clients (Windows XP SP3, Windows Vista, Windows 7, and Windows 8) and servers (Windows Server 2003 SP2, Windows Server 2008, Windows Server 2008 R2, and Windows Server 2012) mount shares in a DFS namespace seamlessly, but the same isn't true for Mac OS (earlier than Lion). Linux systems have the capability to mount DFS, but they require some additional configuration above and beyond issuing a 'mount' command. In the modern versions of Linux, Windows file shares are mounted using the kernel Common Internet File System (CIFS) driver.

In order to mount a DFS volume, the following packages need to be available (these may vary per platform, but are consistent on RedHat/CentOS and SUSE):

cifs-utils (specifically mount.cifs and cifs.upcall)
keyutils

Based on testing in RedHat Enterprise Linux, samba is NOT required to mount a CIFS share hosted in a DFS namespace. A small piece of configuration is necessary to mount a DFS share on Linux. The configuration needs to be added to the keyutils configuration file (bolded below in the list of files included with the package),

/bin/keyctl
/etc/request-key.conf
/etc/request-key.d
/sbin/request-key
/usr/share/doc/keyutils-1.4
/usr/share/doc/keyutils-1.4/LICENCE.GPL
/usr/share/doc/keyutils-1.4/README
/usr/share/keyutils
/usr/share/keyutils/request-key-debug.sh
/usr/share/man/man1/keyctl.1.gz
/usr/share/man/man5/request-key.conf.5.gz
/usr/share/man/man8/request-key.8.gz

The following lines need to be added to the end of the /etc/request-key.conf file:

create cifs.spnego * * /usr/sbin/cifs.upcall -c %k
create dns_resolver * * /usr/sbin/cifs.upcall %k

Note that if you have a newer version of cifs-utils, the -c above is not necessary (and is actually a deprecated option). After adding the lines to the request-key.conf file, you should now be able to mount the share:

 # mount -t cifs //mydfsdomain.lan/namespaceroot/sharedfolder /mnt -o username=windowsuser

If all goes well, this asks for a password and mounts. Note that mydfsdomain.lan should be your Active Directory name namespaceroot should be the root that you create using DFS Management in MMC. Note that all read/write/modify operations will be performed as the "windowsuser" user in the example above.

Thursday, September 27, 2012

How to Dual Boot Windows 8 and Windows 7

Generally when a new operating system version is released, people are timid about making the leap to upgrade to the new version. Many people want to take some time to try the new version while retaining access to their old files and folders on the older release.

This post will cover how to dual boot Windows 8 RTM and Windows 7. Before trying this procedure, be sure to back up your data in case something goes wrong.

To start out, I have a Windows 7 installation on a 120 GB disk. My Windows 7 files and data are only taking 20 GB or so and I want to create a partition to install Windows 8 using 50 GB (Note that the minimum recommended size is 20 GB, but I usually prefer 40-50GB). First, access the disk manager using mmc or by typing the following

  1. Windows key + R to access the run prompt
  2. Enter "diskmgmt.msc" and press enter
You can also use the search bar in the start menu,


Once you are in disk manager, right click the partition that belongs to Windows 7 and click "Shrink"


After you click shrink, specify 50 GB or whatever size you actually want (20 GB is the recommended minimum). Note that 50 GB = 51200 MB.



Click Shrink to start the shrinkoperation on the volume

Now that we have space for a 50 GB volume, restart and boot off of the Windows 8 DVD or Bootable USB Media.


We go through the installation procedure as follows. Select your regional settings and click next,



Then click "Install now"



Accept the EULA and start a Custom Installation,



Select the 50 GB of unallocated space that we created and click next



Wait for the install to complete (or grab a cup of coffee or a donut)...



After the reboot, the boot loader should show the older Windows release and the new Windows 8 option that we just installed.



You might also like
Navigating the Windows 8 User Interface
How to Create USB Windows 8 Installation Media (also works for Windows Server 2012, Windows 7, Windows Server 2008 R2)

How to Create Bootable USB Installation Media for Windows 8 and Windows Server 2012

There are a number of reasons to install Windows off of USB Media instead of using a DVD. Some of them include
  • Installing from USB Media is usually faster than an optical drive
  • Some newer PCs (like an Ultrabook that I just bought) do not have optical drives of any kind
  • Perhaps you ran out of blank DVDs and the store is closed...
Since this procedure involves formatting a flash drive, the reader is cautioned to back up all of the data on the system (you'll see why later) and to make sure that anything that needs to be kept is backed up off of the flash drive. To perform this process, you will need access to Windows 8 media (either in ISO format or DVD) and you will also need a flash drive (> 6 GB).

.

To start the process, open a command prompt with an administrative authentication token,



If your command prompt is not pinned to the start menu, simply type cmd into the search bar, then right click the command prompt that appears and select "run as administrator." Then type diskpart and press enter. You should be here at this point,



Enter "list disk" and hit enter. It should be pretty clear form the sizes which disk is the flash drive. For me, it is Disk 3. Be sure to select the right disk, or you will destroy all of the data on one of the other system disks (this would be very bad for most people). For me, it is Disk 3 because I am using an 8 GB flash drive



Next, type "select disk 3" while substituting 3 for the right disk number on your system.



Now type "Clean" and hit enter. At this point all of the data will be gone from the disk (though it could still be recovered by a forensic analyst/data recovery company)



If you selected the wrong disk, you have a big problem now... If you selected the right disk, you can create a new partition by typing "create partition primary" and hit enter



This should be partition 1, but type "list partition" to be sure.



Now select partition 1 and format the partition as a FAT partition.



Mark the partition as active and we are ready to copy files over,



Mount the Windows 8 or Windows Server 2012 ISO and copy all of the files on the ISO to the newly created/formatted volume.




At this point, you now have bootable Windows 8 or Windows Server 2012 USB media.

Wednesday, September 26, 2012

Adding Multiple Mail Accounts in Microsoft Mail for Windows 8

The mail application in the release preview versions of Windows did not support adding mail accounts for IMAP/POP accounts. In the Windows 8 RTM release, the Mail App supports adding e-mail accounts for Hotmail, Live, MSN, Exchange, Office365, and Outlook.com, Google/Gmail, Yahoo, and a custom account type that allows IMAP/POP accounts to be added. To add an account, access the settings by pointing your mouse or tapping the top right or bottom right corners of the App



Note that you have to be in the Mail app to see the right settings. Then click Accounts




From here, you can select the right type of account to add




If you are adding an IMAP/POP account to Windows Mail in Windows 8, you can either enter your e-mail/password and have the app try to find the right settings, or you can view more details and specify server names/ports and SSL/TLS settings.



That's all there is to it.

You might also like:
Navigating the Windows 8 User Interface