我发现了两种方法来加载和保存ja gged数组。
1)使用BinaryFormatter作为西蒙陈建议上面。 下面是一个例子:
using system.IO;
using System.Runtime.Serialization.Formatters.Binary;
[System.Serializable]
class CudaNetwork {
public CudaResult[] results {get;set;}
}
[System.Serializable]
class CudaResult {
public double[] threshold {get;set;}
public double[,] weight { get; set; }
}
var myjaggedArr = new double[2][] { new double[3] { 1, 2, 3 }, new double[3] { 6, 7, 8 } };
var myjaggedArr2 = new double[2][,] { new double[2,3] { {10,10,10}, {20, 30,50} }, new double[2,3] { {60, 70, 80},{40,30,60} } };
var myclass = new CudaNetwork
{
results = new CudaResult[2]
};
myclass.results[0] = new CudaResult() { threshold = myjaggedArr[0],weight=myjaggedArr2[0] };
myclass.results[1] = new CudaResult() { threshold = myjaggedArr[1],weight=myjaggedArr2[1] };
var formatter = new BinaryFormatter();
using (
var file = File.Create("mydata.bin"))
{
formatter.Serialize(file, myclass);
}
using (
var file = File.OpenRead("mydata.bin"))
{
var obj = formatter.Deserialize(file);
}
2)还有另一种方法来做到这一点使用protobuf的。这里有一个例子: (你应该为protobuf的先加参考。)
using ProtoBuf;
using system.IO;
[ProtoContract]
class CudaNetwork {
[ProtoMember(1)]
public CudaResult[] results {get;set;}
}
[ProtoContract]
class CudaResult {
[ProtoMember(1)]
public double[] threshold {get;set;}
[ProtoMember(2)]
public double[] weight { get; set; }
}
var myjaggedArr = new double[2][] { new double[3] { 1, 2, 3 }, new double[3] { 6, 7, 8 } };
var myjaggedArr2 = new double[2][,] { new double[2,3] { {10,10,10}, {20, 30,50} }, new double[2,3] { {60, 70, 80},{40,30,60} } };
double[] tmp=new double[myjaggedArr2[0].Length];
Buffer.BlockCopy(myjaggedArr2[0],0,tmp,0,sizeof(double)*tmp.Length);
double[] tmp2=new double[myjaggedArr2[1].Length];
Buffer.BlockCopy(myjaggedArr2[1],0,tmp2,0,sizeof(double)*tmp2.Length);
myclass.results[0] = new CudaResult() { threshold = myjaggedArr[0],weight=tmp };
myclass.results[1] = new CudaResult() { threshold =myjaggedArr[1] ,weight=tmp2 };
using (var file = File.Create("trainedNetwork.bin")) {
Serializer.Serialize(file, myclass);
}
CudaNetwork cudaclass;
using (var file =File.OpenRead("trainedNetwork.bin"))
{
cudaclass = Serializer.Deserialize<CudaNetwork>(file);
}
使用protobuf的,我们应该只有一个 - 维数组;这就是为什么我使用Blockcopy来将二维数组转换为一维数组。
我相信有很多方法可以做到这一点。但到目前为止,我知道这两种方式。
如果您有2个或更多的数组,只需将它们包装在某个类或另一个集合中并将其序列化即可。 – Carsten 2014-09-01 04:28:02