我有3个类,Node,HiddenLayer和InputNode类。
我的HiddenLayer和InputNode类是Node类的子类,它们将从Node类(多态)共享output()方法。
我的问题是:为什么我的对象在HiddenLayer类中返回0?
附上我的代码:
的 Node.java 的
public class Node {
protected double number;
public double output(){
return number;
}
}
的 HiddenLayer.java 的
public class HiddenLayer extends Node {
protected Node[] input;
public HiddenLayer(Node[] nodes) {
this.input = nodes;
}
//Some activation functions which can be called upon.
class ActivationFunction {
//Sigmoid activation function
public double sigmoid(double x) {
return (1.0 / (1 + Math.pow(Math.E, -x)));
}
public double deriveSigmoid(double d){
return d * (1.0 - d);
}
// Hyperbolic Tan Activation Function
public double hyperTanFunction(double x) {
return (Math.pow(Math.E, x) - Math.pow(Math.E, -x)) / (Math.pow(Math.E, x) + Math.pow(Math.E, -x));
}
public double deriveHyperTanFunction(double d){
return (1.0 - Math.pow(hyperTanFunction(d), 2.0));
}
}
//Output method for the HiddenNode class which will sum up all the input nodes for
//a specific hidden node
public double output(){
/*Here we will be implementing the following function
* Sigma(x[i] * weights[i]) = net
* Pass net into the hyberbolic tangent function to get an output between -1 to 1
* We will pass net into the activation function in the train method of Neural Network
*/
//Store inputs into s temp double array.
double[] tempArray = new double[input.length];
for (int j = 0; j < input.length; j++){
tempArray[j] = input[j].output();
System.out.println(tempArray[j]);
}
//Setup a double sum variable to represent net
double net = 0;
//Setup for loop to loop over input nodes array for a hidden node
for (int i = 0; i < tempArray.length; i++){
net = net + tempArray[i];
}
return net;
}
public static void main(String[] args) {
InputNode node1 = new InputNode(28);
InputNode node2 = new InputNode(0);
InputNode node3 = new InputNode(165);
InputNode node4 = new InputNode(30);
InputNode node5 = new InputNode(0);
InputNode node6 = new InputNode(0);
InputNode node7 = new InputNode(0);
InputNode[] nodes = {node1, node2, node3, node4, node5, node6, node7};
HiddenLayer h1 = new HiddenLayer(nodes);
h1.output();
}
}
的 InputNode.java 的
public class InputNode extends Node {
//Declare a double variable to represent the holding value for InputNode
private double value;
public InputNode(double value) {
}
//Create method to initialize input nodes
public void set(double tempValue){
this.value = tempValue;
}
public double get(){
return value;
}
//Override method from Node class
//This method will grab the sum of all input node values.
public double output(){
return number;
}
}
答案 0 :(得分:1)
嗯,就Java而言,你只是在为程序提供0
。
采取这一行:
tempArray[j] = input[j].output();
output
将为0.0 initial value upon construction will be 0.0
。原因是:output
使用字段number
来返回其值,并且由于您的代码中没有任何地方明确地将number
分配给某个值,因此它将始终返回{{ 1}}。
要修复它,根据您的逻辑或所需的操作,您应该在0.0
的构造上初始化它...
InputNode
...或public InputNode(double value) {
number = value;
}
的构造 - 强迫您使用上述构造函数:
Node