Trouble loading the training dataset in LibSVMSharp - c#

If anyone is familiar with libSVM (https://www.csie.ntu.edu.tw/~cjlin/libsvm/), I am working with libSVMsharp, which is the same thing, in a C# wrapper, I believe.
On their github, they give the following example of how to write a simple classification, using the SVM:
SVMProblem problem = SVMProblemHelper.Load(#"dataset_path.txt");
SVMProblem testProblem = SVMProblemHelper.Load(#"test_dataset_path.txt");
SVMParameter parameter = new SVMParameter();
parameter.Type = SVMType.C_SVC;
parameter.Kernel = SVMKernelType.RBF;
parameter.C = 1;
parameter.Gamma = 1;
SVMModel model = SVM.Train(problem, parameter);
double target[] = new double[testProblem.Length];
for (int i = 0; i < testProblem.Length; i++)
target[i] = SVM.Predict(model, testProblem.X[i]);
double accuracy = SVMHelper.EvaluateClassificationProblem(testProblem, target);
That all makes perfect sense, loading in the training data with its path specified, and same with the test data...Well, that's where I run into problems.
I wanted to test this out in C# just to ensure my full understanding of how this works, before implementing it in a larger project that I've been working on. I have a small program called Program.cs (very original, I know), and in the SAME FOLDER, I have train.txt and test.txt. So we have a folder that contains Program.cs, train.txt, and test.txt, along with some other standard stuff that is created when you make a project in Visual Studio.
So that snippet of my code looks like this:
SVMProblem trainingSet = SVMProblemHelper.Load(#"train.txt");
SVMProblem testSet = SVMProblemHelper.Load(#"test.txt");
trainingSet = trainingSet.Normalize(SVMNormType.L2);
testSet = testSet.Normalize(SVMNormType.L2);
and so on. However, when I run this, it basically says that the variable "trainingSet" is null, because SVMProblemHelper never actually managed to load train.txt.
I feel like there is a glaringly obvious solution to this, but I'm completely lost. I'm not entirely sure what's going wrong, here. In the SVMProblemHelper.Load function, it basically says that it will set the variable (in this case, trainingSet) equal to null if it cannot find the file in question. But how is it not finding the file? It's in the same directory as the .cs file. I'm not sure what I'm missing but I can't figure it out.
Any help is gladly welcomed!

Related

Spotfire C# SDK: Why the Remove() method of ColoringCollection object doesnt seem to work?

I have pretty annoying problem. :)
visual = context.ActiveVisualReference;
TablePlot tablePlot = visual.As<TablePlot>();
colorings = tablePlot.Colorings;
categories = colorings.GetCategories();
coloring1 = colorings.GetColoringForCategory(categories[0]);
coloring2 = colorings.GetColoringForCategory(categories[1]);
coloring3 = colorings.GetColoringForCategory(categories[2]);
category2 = categories[2];
bool removed = colorings.Remove(coloring2);
This is the C# code I execute at the custom Tool level and the problem is that I do not see any effect within the Web Professional (using 5.5)
of the Remove method execution.
According to the documentation the method should remove the custom coloring from visualisation and it does NOT.
Perhaps it is needed to call some method that refreshes view but I didnt manage to locate it.
Please help. :)
http://stn.spotfire.com/dxp/html/M_Spotfire_Dxp_Application_Visuals_ConditionalColoring_ColoringCollection_Remove.htm
Have you tried tablePlot.Colorings = colorings at the end of your code ? What is the value of "removed" at the end of your code ?
In ironPython this one works:
from Spotfire.Dxp.Application.Visuals import TablePlot
print myVisual.Title
myTablePlot = myVisual.As[TablePlot]();
print myTablePlot.Title
myColorings = myTablePlot.Colorings;
myCategories = myColorings.GetCategories();
print myCategories.Count
myColorings.Remove(myColorings.GetColoringForCategory(myCategories[1]))

LineSeries.cs not found

I am trying to create a graph with C# and the WPF chartingToolkit, I have the following code:
LineSeries lineSeries1 = new LineSeries();
lineSeries1.Title = region;
lineSeries1.DependentValuePath = "Value";
lineSeries1.IndependentValuePath = "Key";
lineSeries1.ItemsSource = points;
this.Graph.Series.Add(lineSeries1);
where points is a Dictionary<string, int> created in earlier code. This code compiles fine and runs fine until it reaches the line LineSeries lineSeries1 = new LineSeries();. Upon reaching this line it throws a Source Not Found: LineSeries.cs not found exception. I have tried putting it as System.Windows.Controls.DataVisualization.Charting.LineSeries lineseries1 = new System.Windows.Controls.DataVisualization.Charting.LineSeries(); but that failed to fix the issue. Everywhere I look for examples of how to do this it is written exactly how I have it.
EDIT:
It works perfectly without the debugger. The problem only exists with it.
The debugger was looking for a source file but was not able to find it. This will have been either because you don't have it available or because the version of the source you have does not exactly match the version which was compiled into your library.
If the latter is the case, you can work around it by going to Tools -> Options -> Debugging and unchecking the "Require source files to exactly match the original version" option.

Fellow Oak DICOM - changing image window level

I am not an experienced programmer, just need to add a DICOM viewer to my VS2010 project. I can display the image in Windows Forms, however can't figure out how to change the window center and width. Here is my script:
DicomImage image = new DicomImage(_filename);
int maxV = image.NumberOfFrames;
sbSlice.Maximum = maxV - 1;
image.WindowCenter = 7.0;
double wc = image.WindowCenter;
double ww = image.WindowWidth;
Image result = image.RenderImage(0);
DisplayImage(result);
It did not work. I don't know if this is the right approach.
The DicomImage class was not created with the intention of it being used to implement an image viewer. It was created to render preview images in the DICOM Dump utility and to test the image compression/decompression codecs. Maybe it was a mistake to include it in the library at all?
It is difficult for me to find fault in the code as being buggy when it is being used for something far beyond its intended functionality.
That said, I have taken some time to modify the code so that the WindowCenter/WindowWidth properties apply to the rendered image. You can find these modifications in the Git repo.
var img = new DicomImage(fileName);
img.WindowCenter = 2048.0;
img.WindowWidth = 4096.0;
DisplayImage(img.RenderImage(0));
I looked at the code and it looked extremely buggy. https://github.com/rcd/fo-dicom/blob/master/DICOM/Imaging/DicomImage.cs
In the current buggy implementation setting the WindowCenter or WindowWidth properties has no effect unless Dataset.Get(DicomTag.PhotometricInterpretation) is either Monochrome1 or Monochrome2 during Load(). This is already ridiculous, but it still cannot be used because the _renderOptions variable is only set in a single place and is immediately used for the _pipeline creation (not giving you chance to change it using the WindowCenter property). Your only chance is the grayscale _renderOptions initialization: _renderOptions = GrayscaleRenderOptions.FromDataset(Dataset);.
The current solution: Your dataset should have
DicomTag.WindowCenter set appropriately
DicomTag.WindowWidth != 0.0
DicomTag.PhotometricInterpretation == Monochrome1 or Monochrome2
The following code accomplishes that:
DicomDataset dataset = DicomFile.Open(fileName).Dataset;
//dataset.Set(DicomTag.WindowWidth, 200.0); //the WindowWidth must be non-zero
dataset.Add(DicomTag.WindowCenter, "100.0");
//dataset.Add(DicomTag.PhotometricInterpretation, "MONOCHROME1"); //ValueRepresentations tag is broken
dataset.Add(new DicomCodeString(DicomTag.PhotometricInterpretation, "MONOCHROME1"));
DicomImage image = new DicomImage(dataset);
image.RenderImage();
The best solution: Wait while this buggy library is fixed.

FOP and IKVM in .NET - Images Not Working

UPDATE2: I got it working completely now! Scroll way down to find out how...
UPDATE: I got it working! Well... partially. Scroll down for the answer...
I'm trying to get my FO file to show an external image upon transforming it to PDF (or RTF for that matter, but I'm not sure whether RTFs are even capable of displaying images (they are)) with FOP, but I can't seem to get it working. (The question asked here is different than mine.)
I am using IKVM 0.46.0.1 and have compiled a FOP 1.0 dll to put in .NET; this code worked fine when I didn't try to add images:
private void convertFoByMimetype(java.io.File fo, java.io.File outfile, string mimetype)
{
OutputStream output = null;
try
{
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
// configure foUserAgent as desired
// Setup outputput stream. Note: Using BufferedOutputStream
// for performance reasons (helpful with FileOutputStreams).
output = new FileOutputStream(outfile);
output = new BufferedOutputStream(output);
// Construct fop with desired output format
Fop fop = fopFactory.newFop(mimetype, foUserAgent, output);
// Setup JAXP using identity transformer
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // identity transformer
// Setup input stream
Source src = new StreamSource(fo);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
}
catch (Exception ex)
...
}
However, when I (or rather a DocBook2FO transformation) added the following code:
<fo:external-graphic src="url(images/interface.png)" width="auto" height="auto" content-width="auto" content-height="auto" content-type="content-type:image/png"></fo:external-graphic>
into the FO file, the image did not show. I read through a bit of the FAQ on Apache's site, which says:
3.3. Why is my graphic not rendered?
Most commonly, the external file is not being found by FOP. Check the
following:
Empty or wrong baseDir setting.
Spelling errors in the file name (including using the wrong case).
...
Other options did not seem to be my case (mainly for the reason below - "The Weird Part"). I tried this:
...
try
{
fopFactory.setBaseURL(fo.getParent());
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
foUserAgent.setBaseURL(fo.getParent());
FOURIResolver fourir = fopFactory.getFOURIResolver();
foUserAgent.setURIResolver(fourir);
// configure foUserAgent as desired
...
with no avail.
The Weird Part
When I use the command-line implementation of FOP, it works fine and displays my image with no problem. (I don't want to go the run-command-line-from-program route, because I don't want to force the users to install Java AND the .NET framework when they want to use my program.)
The png file is generated from GDI+ from within my application (using Bitmap.Save). I also tried different png files, but none of them worked for me.
Is there anything I might be missing?
Thanks a bunch for getting this far
UPDATE and possible answer
So I might have figured out why it didn't work. I put some time into studying the code (before I basically just copypasted it without thinking about it much). The problem is indeed in the wrong basedir setting.
The key is in this chunk of code:
// Setup JAXP using identity transformer
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // identity transformer
// Setup input stream
Source src = new StreamSource(fo);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
What happens here is an identity transformation, which routes its own result into an instance of FOP I've created before. This effectively changes the basedir of the routed FO into that of the application's executable. I have yet to figure out how to do this without a transformation and route my input directly into FOP, but for the moment I worked around this by copying my images into the executable's directory.
Which is where another problem came in. Now whenever I try to execute the code, I get an exception at the line that says transformer.transform(src, res);, which confuses the pants out of me, because it doesn't say anything. The ExceptionHelper says:
java.lang.ExceptionInInitializerError was caught
and there is no inner exception or exception message. I know this is hard to debug just from what I wrote, but I'm hoping there might be an easy fix.
Also, this e-mail seems vaguely related but there is no answer to it.
UPDATE2
Finally, after a few sleepless nights, I managed to get it working with one of the simplest ways possible.
I updated IKVM, compiled fop with the new version and replaced the IKVM references with the new dlls. The error no longer occurs and my image renders fine.
I hope this helps someone someday
I'm using very similar code, although without the FOUserAgent, Resolvers, etc. and it works perfectly.
Did you try setting the src attribute in the XSLT without the url() function?
What might help you diagnose the problem further are the following statements:
java.lang.System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog")
java.lang.System.setErr(New java.io.PrintStream(New TraceStream(TraceStream.Level.Error)))
java.lang.System.setOut(New java.io.PrintStream(New TraceStream(TraceStream.Level.Info)))
Where TraceStream is a .NET implementation of a java.io.OutputStream which writes to your favorite logger.
I posted a version for the Common.Logging package at http://pastebin.com/XH1Wg7jn.
Here's a post not to leave the question unanswered, see "Update 1" and "Update 2" in the original post for the solution.

Programmatically add new iteration in TFS

I can manually add a new iteration to a team project in TFS by right clicking on the project and going to Team Project Settings > Areas and Iterations > Iterations tab.
Is there an example out there of how to do this programmatically using their API?
Thanks!
After some experimentation based on taylonr's link, here's what I came up with as a minimal solution for adding an iteration, in case any one else runs into this:
public void AddIteration(string projectName, string iterationName)
{
using (var tfsCollection = new TfsTeamProjectCollection(new Uri(tfsServerUrl), getTfsCredentials()))
{
tfsCollection.Authenticate();
var css = tfsCollection.GetService<ICommonStructureService>();
string rootNodePath = string.Format("\\{0}\\Iteration", projectName);
var pathRoot = css.GetNodeFromPath(rootNodePath);
css.CreateNode(iterationName, pathRoot.Uri);
}
}
Does this tutorial solve your problem?
http://blogs.microsoft.co.il/blogs/shair/archive/2009/01/30/tfs-api-part-10-add-area-iteration-programmatically.aspx
Google-Fu "tfs api add iteration"
From glancing at his code, (and using TFS) it looks like iterations are getting treated as hierarchies. That's why you see things like "Release1\Sprint2" etc... you can have them nested deep... deep down they're probably just a path and that's why he's using the add path etc

Categories