I am having a problem return a list so that i would be able to save it in a file and then load it so that the weights are saved and be retrieved another time. Sorry for the stupid question but how can i call and save the weights List from the SaveNetwork method , i cant grasp really what i can do to solve the problem. I know that i havent created a new instance of List weights however if i do that i will loose the current weights which are stored in this list.
public class Neuron
{
private double bias; // Bias value.
private double error; // Sum of error.
private double input; // Sum of inputs.
private double gradient = 5; // Steepness of sigmoid curve.
private double learnRate = 0.01; // Learning rate.
private double output = double.MinValue; // Preset value of neuron.
public List<Weight> weights; // Collection of weights to inputs.
public Neuron() { }
public Neuron(Layer inputs, Random rnd)
{
weights = new List<Weight>();
foreach (Neuron input in inputs)
{
Weight w = new Weight();
w.Input = input;
w.Value = rnd.NextDouble() * 2 - 1;
weights.Add(w);
}
}
public static void SaveNetwork(string path)
{
FileStream FS = new FileStream(path, FileMode.Create);
BinaryFormatter BF = new BinaryFormatter();
BF.Serialize(FS,/* The List in this case is List weights ***/ );
FS.Close();
}
public void LoadNetwork(string path)
{
FileStream FS = new FileStream(path, FileMode.Open);
BinaryFormatter BF = new BinaryFormatter();
weights = (List<Weight>)BF.Deserialize(FS);
FS.Close();
}
Update for this--I am using a similar hierarchical structure as the code below which was taken from Dynamic Notions blog which explains how to create a Neural Network. What i want to achieve is that after that the Neural Network has learnt i want to be able to save the List weights so that i would be able to load the weights if the program is stopped in order to skip the training of the network. So basically from the class network i want to access this list which is in Neural Class without creating a new instance in a new method else i will only get an empty List. Hope that its clearer coz i didnt know how to explain it better... Many thanks
public class Network{
//some variables..
[STAThread]
static void Main()
{
new Network();
}
public Network()
{
LoadPatterns();
Initialise();
Train();
Test();
}
private void Train()
{
double error;
do
{
error = 0;
foreach (Pattern pattern in _patterns)
{
double delta = pattern.Output - Activate(pattern);
AdjustWeights(delta);
error += Math.Pow(delta, 2);
}
Console.WriteLine("Iteration {0}\tError {1:0.000}", _iteration, error);
_iteration++;
if (_iteration > _restartAfter) Initialise();
} while (error > 0.1);
}
private void Test()
{
}
// Must be able to call and save the List<Weight> From here
private double Activate(Pattern pattern)
{
}
private void AdjustWeights(double delta)
{
_output.AdjustWeights(delta);
foreach (Neuron neuron in _hidden)
{
neuron.AdjustWeights(_output.ErrorFeedback(neuron));
}
}
private void Initialise()
{
_inputs = new Layer(_inputDims);
_hidden = new Layer(_hiddenDims, _inputs, _rnd);
_output = new Neuron(_hidden, _rnd);
_iteration = 0;
Console.WriteLine("Network Initialised");
}
private void LoadPatterns()
{
}
}
public class Layer : List<Neuron>
{
public Layer(int size)
{
for (int i = 0; i < size; i++)
base.Add(new Neuron());
}
public Layer(int size, Layer layer, Random rnd)
{
for (int i = 0; i < size; i++)
base.Add(new Neuron(layer, rnd)); //this is where Neuron class is instantiated
}
}
public class Neuron
{
//some other vars
private List<Weight> _weights; // This is the list in question.
public Neuron() { }
public Neuron(Layer inputs, Random rnd)
{
_weights = new List<Weight>();
foreach (Neuron input in inputs)
{
Weight w = new Weight();
w.Input = input;
w.Value = rnd.NextDouble() * 2 - 1;
_weights.Add(w);
}
}
}
public class Weight
{
public Neuron Input;
public double Value;
}
Remove the static keyword from SaveNetwork() and use weights where you have your comment.
Related
I have 5 Picture Boxes in my application, and I update them at the same time.
I want them to display 5 different Images and my programs code is right, but for some reason the picture boxes show all the same image...
Here's the code:
private System.Drawing.Bitmap DiceOne;
private System.Drawing.Bitmap DiceTwo;
private System.Drawing.Bitmap DiceThree;
private System.Drawing.Bitmap DiceFour;
private System.Drawing.Bitmap DiceFive;
private System.Drawing.Bitmap DiceSix;
public void Prepare()
{
for (int i = 0; i < 5; i++)
Dices[i] = new Dice();
DiceOne = Properties.Resources.Würfel_1;
DiceTwo = Properties.Resources.Würfel_2;
DiceThree = Properties.Resources.Würfel_3;
DiceFour = Properties.Resources.Würfel_4;
DiceFive = Properties.Resources.Würfel_5;
DiceSix = Properties.Resources.Würfel_6;
}
public void Roll()
{
foreach (Dice dice in Dices)
dice.RollTheDice();
View.SuspendLayout();
View.diceOnePictureBox.Image = DiceNumberToBmp(Dices[0].GetLastRolled());
View.diceOnePictureBox.Update();
View.diceTwoPictureBox.Image = DiceNumberToBmp(Dices[1].GetLastRolled());
View.diceOnePictureBox.Update();
View.diceThreePictureBox.Image = DiceNumberToBmp(Dices[2].GetLastRolled());
View.diceOnePictureBox.Update();
View.diceFourPictureBox.Image = DiceNumberToBmp(Dices[3].GetLastRolled());
View.diceOnePictureBox.Update();
View.diceFivePictureBox.Image = DiceNumberToBmp(Dices[4].GetLastRolled());
View.diceOnePictureBox.Update();
View.ResumeLayout(false);
}
private System.Drawing.Bitmap DiceNumberToBmp(int number)
{
switch(number)
{
case 1:
return DiceOne;
case 2:
return DiceTwo;
case 3:
return DiceThree;
case 4:
return DiceFour;
case 5:
return DiceFive;
case 6:
return DiceSix;
default:
return null;
}
}
I've read some familier posts on the internet before, and tried to solve with with SuspendLayout, ResumeLayout, Updating the PictureBox.... Nothing worked for me.
My Dice class:
using System;
namespace KniffelGUI.Model
{
public class Dice
{
private int LastRolled;
public Dice()
{
RollTheDice();
}
public Dice(int fakeRoll)
{
LastRolled = fakeRoll;
}
public int RollTheDice()
{
LastRolled = new Random().Next(6) + 1;
return LastRolled;
}
public int GetLastRolled()
{
return LastRolled;
}
}
}
The problem is in your Dice class, as suggested earlier by Barry O'Kane.
Change it to:
public class Dice
{
private int LastRolled;
private static Random R = new Random();
public Dice()
{
RollTheDice();
}
public Dice(int fakeRoll)
{
LastRolled = fakeRoll;
}
public int RollTheDice()
{
LastRolled = R.Next(6) + 1;
return LastRolled;
}
public int GetLastRolled()
{
return LastRolled;
}
}
Your symptom was occurring because of this line:\
LastRolled = new Random().Next(6) + 1;
When you create an instance of Random with the default constructor, it uses the current time as the seed. When you create multiple instances in rapid succession, they end up with the same seed and therefore won't get different numnbers.
By declaring it as static, all instances of your class will use the same Random instance and get a different number upon each call.
I am attempting to write a program for an assignment that Pops and adds the first 2 items in a Stack. The program has a Pop method, but I would like to know how to call the method within the Add method. This Add is supposed to Pop the top two items in a stack, get their sum, and Push that sum to the stack. In my code below I call the Pop method twice inside the Add method, but when I display the stack, the stack still has all of the original values. Is there something more/else I need to go to get the Pop method to work?
class StackEmptyException : ApplicationException
{
public StackEmptyException(String message) : base(message)
{
}
}
class MathStack
{
private int[] dataStack;
private int size;
private int top = -1;
public bool IsEmpty()
{
return top == -1;
}
public bool IsFull()
{
return top == size - 1;
}
public void Push(int i)
{
dataStack[++top] = i;
}
public int Pop()
{
if (IsEmpty())
throw new StackEmptyException
("Stack empty -- cannot pop");
else
return dataStack[top--];
}
public int Top()
{
if (IsEmpty())
throw new StackEmptyException
("Stack empty -- top undefined");
else
return dataStack[top];
}
public MathStack()
{
dataStack = new int[10];
}
public MathStack(int s)
{
size = 10;
dataStack = new int[size];
}
public void LoadStack(int v)
{
dataStack[++top] = v;
}
public void Display()
{
int[] display = new int[dataStack.Length];
for (int i = 0; i < dataStack.Length; i++)
{
display[i] = dataStack[i];
Console.WriteLine("{0}", display[i]);
}
}
public void Add()
{
int add1 = dataStack[0];
int add2 = dataStack[1];
Pop();
Pop();
int sum = add1 + add2;
Console.WriteLine("Sum: {0}", sum);
}
}
class Program
{
static void Main(string[] args)
{
MathStack stack1 = new MathStack();
stack1.Push(9);
stack1.Push(8);
stack1.Push(7);
stack1.Push(6);
stack1.Push(5);
stack1.Push(4);
stack1.Push(3);
stack1.Push(2);
stack1.Push(1);
stack1.Push(0);
stack1.Display();
stack1.Add();
stack1.Display();
Console.ReadLine();
}
}
There are two things wrong with your code.
First, the Display method displays the whole array. Except that since you're not physically removing the items from the array, you need to stop at the index top:
public void Display()
{
if (IsEmpty())
{
Console.WriteLine("Empty");
return;
}
for (int i = 0; i <= top; i++)
{
Console.WriteLine(dataStack[i]);
}
}
The second issue is your Add. From what I understand, you want to pop the last two items, sum them, and push the result. In your implementation, you are actually summing the first two items (not the last two). A better version would be:
public void Add()
{
int add1 = Pop();
int add2 = Pop();
int sum = add1 + add2;
Console.WriteLine("Sum: {0}", sum);
Push(sum);
}
Notice how I do not directly access dataStack. If your API is correctly implemented, it should not be needed.
I have issue (I think) with derived class. When I add some points to my list in Form 1, I can see count and iterate through listA, and it seems its okay. I have below code:
/* Add points to lists */
class A {
private Point _singlePoint;
protected List<Point> _listA = new List<Point>();
protected List<Point> _listB = new List<Point>();
//properties
public List<Point> listA {
get { return _listA; }
set { _listA = value; }
}
public Point singlePoint {
get { return _singlePoint; }
set { _singlePoint = value; }
}
public virtual void addToListA(Point a) { }
}
class B : A {
public override void addToListA(Point a) {
_listA.Add(a);
}
}
public partial class Form1 : Form {
A _myPoints = new B();
private void drawPoint()
{
for (int i = 0; i < int.Parse(txtBoxPointsCount.Text); i++)
{
_myPoints.singlePoint = new Point(rnd.Next(100, 300), rnd.Next(100, 300));
_myPoints.addToListA(_myPoints.singlePoint);
}
foreach(Point p in _myPoints.listA)
{
graph.FillEllipse(new SolidBrush(cPoint), p.X, p.Y, 6, 6);
}
}
}
In other class I want to do some math on points, but I got ArgumentOutOfRangeException
class D {
A _myPoints = new B();
public void calulations(int iterations) {
randomPoint = rnd.Next(0, _myPoints.listA.Count);
System.Windows.Forms.MessageBox.Show(_myPoints.listA.Count.ToString());
try {
for (int i = 0; i < _iterations; i++) {
//here some math
}
}
catch(ArgumentOutOfRangeException e) {
// here I got errors about no items in my list
}
} }
In class D, in MsgBox I got count = 0. Maybe I wrote classes in wrong way? Method drawPoint() is called before calculations().
Could you help? Thanks in advance :)
That is because you are operating two completely different objects,
You have created an object here
public partial class Form1 : Form
{
A _myPoints = new B();
and then in class D created another
class D
{
A _myPoints = new B();
So you are adding point to your first object and trying to access in other object.
I am new to programming and i would be delighted if someone could help me with the following problem.
I have problem with two methods.
First sum all of 50 random numbers in a list, second sort list with 50 random numbers.
I know how to do this when a list has for example four numbers{1,2,3,8} , but not with 50 random numbers.
It will be nice to use a constructor to this two methods, but I don't now how to do this.
Any help would be much appreciated.
class Class1
{
var rand = new Random();
public Class1( ) // how to use a constructor ?
public static List<double> TotalSum()
{
var alist = new List<double>();
for (int i = 0; i < 50; i++)
{
alist.Add(rand.Next(10));
}
Console.WriteLine("Total sum:", alist);
}
public static List<double> Sort()
{
var slist = new List<double>();
for (int i = 0; i < 50; i++)
{
slist.Sort(rand.Next(10)); // rand.Next does not work with Sort
Console.WriteLine(slist);
}
}
class Program
{
static void Main(string[] args)
{
Class1 show = new Class1();
show.TotalSum();
show.Sort();
}
}
}
just use the 2 methods
list.Sum();
list.Sort();
I suggest that you use rand.Next(Environment.TickCount) to get better random numbers, but at the end you need to use a different primitive value to store the result
class Program
{
static void Main(string[] args)
{
var array = Class1.Sort();
PrintArray(array);
Console.WriteLine();
Console.WriteLine("Total sum: {0}", Class1.TotalSum());
Console.ReadLine();
}
static void PrintArray(List<double> array)
{
foreach (var a in array)
Console.WriteLine(a);
}
}
public class Class1
{
public static double TotalSum()
{
var rand = new Random();
var alist = new List<double>();
for (int i = 0; i < 50; i++)
{
alist.Add(rand.Next(10));
}
return alist.Sum();
}
public static List<double> Sort()
{
var rand = new Random();
var slist = new List<double>();
for (int i = 0; i < 50; i++)
{
slist.Add(rand.Next(10)); // rand.Next does not work with Sort
}
slist.Sort();
return slist;
}
}
I think I got what you mean. You want a class that holds random list of numbers and you need some functions.
Its better to give more suitable name to your class. for example "RandomList" would be good.
You can't use Console.WriteLine(list) to print items of list. You have to iterate through items and print them in the way you want.
You can't use var to define fields. You have to write the type explicitly.
static keyword in other word is one for all instances. So if you dont use static it would be one per instance. Instance is just the object that you create with the constructor. Its better to declare random number generator as static, but other methods and list field should remain non static.
With the use of Linq Sum() you can get the sum of all the items from list. If you dont want to use Linq then you have to iterate through list and add each item to value sum.
I commented the code to explain things.
class Program
{
static void Main(string[] args)
{
RandomList show = new RandomList(50, 10);
show.TotalSum();
show.Sort();
}
}
class RandomList
{
private static Random rand = new Random();
private List<double> _list; // this field holds your list
public RandomList(int length , int maxValuePerItem) // this is the constructor
{
_list = new List<double>();
// populate list
for (int i = 0; i < length; i++)
{
_list.Add(rand.Next(maxValuePerItem));
}
}
public void TotalSum()
{
Console.WriteLine("Total sum: {0}", _list.Sum()); // {0} is required to specify the place to put _list.Sum() inside string.
// without linq way
// int sum = 0;
// foreach(var i in _list) sum += i;
}
public void Sort()
{
_list.Sort();
foreach (var d in _list)
{
Console.Write(d + " , "); // you need to print this in the way you want.
}
}
}
A constructor is typically used to initialize some values. In your case, you should use it to initialize your list, that is, to load it with 50 random numbers. We will also change it so that the list is a property of the class.
Note that the methods shouldn't be static, since they are acting on a property of the class. We are also using the built-in methods of List (Sum() and Sort()) instead of rolling our own.
class Class1
{
var rand = new Random();
var alist;
public Class1() // constructor creates a new list and initializes it
{
alist = new List<double>();
for (int i = 0; i < 50; i++)
{
alist.Add(rand.Next(10));
}
}
public List<double> TotalSum()
{
Console.WriteLine("Total sum:", alist.Sum());
}
public List<double> Sort()
{
alist.Sort();
for (double num in alist)
{
Console.WriteLine(num.ToString());
}
}
class Program
{
static void Main(string[] args)
{
Class1 show = new Class1();
show.TotalSum();
show.Sort();
}
}
}
Because you asked how to use the constructor I tried to rewrite your code in a way that the constructor do something of usefull. I added a property and a local variable plus another function.
public class Class1
{
Random rand = new Random();
List<double> alist { get; set; }
public Class1(int howmany = 50)
{
alist = new List<double>();
for (var i = 0; i < howmany; i++)
{
alist.Add(rand.NextDouble());
}
}
public void Sort()
{
alist.Sort();
}
public void printTotalSum()
{
Console.WriteLine("Total sum: {0}", alist.Sum());
}
public void printList() {
Console.WriteLine("The list contains:");
for (int i = 0; i < alist.Count; i++)
{
Console.WriteLine(alist[i]);
}
}
}
class Program
{
static void Main(string[] args)
{
Class1 show = new Class1(10);
show.printTotalSum();
show.Sort();
show.printList();
}
}
I have class that draw three types of charts, and i want to update it by function public void GetData(PlotModel PlotModel). The main problem is that every series (AreaSeries,CandleStickSeries,HighLowSeries) has different interfaces. How can i update different types in function public void GetData(PlotModel PlotModel). What should i use Activator? Generic?
I think that something like is bad idea:
public void GetData(PlotModel PlotModel) {
while(true) {
System.Threading.Thread.Sleep(1000);
// Add new Item?
switch(PlotModel.Series.First().ToString()) {
case "OxyPlot.Series.AreaSeries":
Console.WriteLine("AreaSeries");
break;
case "OxyPlot.Series.CandleStickSeries":
Console.WriteLine("CandleStickSeries");
break;
case "OxyPlot.Series.HighLowSeries":
Console.WriteLine("HighLowSeries");
break;
}
}
}
Code:
namespace WpfApplication20 {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
DataContext = new PlotClass();
}
}
public class PlotClass {
public PlotModel PlotModel { get; set; }
public PlotClass() {
PlotModel = new PlotModel();
DrawCandleChart(PlotModel);
UpdateChartAsync(PlotModel);
}
public void DrawSimpleChart(PlotModel PlotModel) {
Random rnd = new Random();
LineSeries LS = new LineSeries();
for (int i=0;i<10;i++) {
LS.Points.Add(new DataPoint(i,rnd.NextDouble()));
}
PlotModel.Series.Add(LS);
PlotModel.InvalidatePlot(false);
}
public void DrawCandleChart(PlotModel PlotModel) {
Random rnd = new Random();
CandleStickSeries CSS = new CandleStickSeries();
for (int i=0;i<10;i++) {
CSS.Items.Add(new HighLowItem { Close = rnd.NextDouble(), High = rnd.NextDouble(), Low = rnd.NextDouble(), Open = rnd.NextDouble(), X = i });
}
PlotModel.Series.Add(CSS);
PlotModel.InvalidatePlot(false);
}
public void DrawHighLowChart(PlotModel PlotModel) {
Random rnd = new Random();
HighLowSeries HLS = new HighLowSeries();
for (int i = 0; i < 10; i++) {
HLS.Items.Add(new HighLowItem { Close = rnd.NextDouble(), High = rnd.NextDouble(), Low = rnd.NextDouble(), Open = rnd.NextDouble(), X = i });
}
PlotModel.Series.Add(HLS);
PlotModel.InvalidatePlot(false);
}
public void UpdateChartAsync(PlotModel PlotModel) {
Action<PlotModel> Update = new Action<PlotModel>(GetData);
IAsyncResult result = Update.BeginInvoke(PlotModel, null, null);
}
public void GetData(PlotModel PlotModel) {
while(true) {
System.Threading.Thread.Sleep(1000);
// Add new Item?
}
}
}
}
C# 4 and up offers a nice way of processing situations like this: use cast to dynamic, and call a method with one overload per subtype, like this:
private void Process(AreaSeries arSer) {
...
}
private void Process(CandleStickSeries csSer) {
...
}
private void Process(HighLowSeries hlSer) {
...
}
...
while(true) {
System.Threading.Thread.Sleep(1000);
Process((dynamic)PlotModel.Series.First());
// ^^^^^^^^^
}
The cast to dynamic makes the "magic" happen: C# will examine the run-time type of PlotModel.Series.First(), and dispatch to one of the three Process methods that you supplied.
There is a danger in this approach: if PlotModel.Series.First() happens to not match any of the overloads, you get a run-time exception. The compiler cannot perform static analysis to tell you that your call would not succeed. Consider adding a catch-all method for the common superclass of your plots, too, so that you could handle unexpected sub-types more gracefully.