gpt4 book ai didi

多元梯度下降的Java实现

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:38 24 4
gpt4 key购买 nike

我正在尝试用 Java 实现多元梯度下降算法(来自 AI coursera 类(class)),但我无法确定我的代码中的错误位置。

这是下面程序的输出:

Before train: parameters := [0.0, 0.0, 0.0] -> cost function := 2.5021875E9
After first iteration: parameters := [378.5833333333333, 2.214166666666667, 50043.75000000001] -> cost function := 5.404438291015627E9

如您所见,在第一次迭代后,这些值相差甚远。我做错了什么?

这是我要实现的算法:

enter image description here

还有代码:

    import java.util.*;

public class GradientDescent {

private double[][] trainingData;
private double[] means;
private double[] scale;

private double[] parameters;
private double learningRate;

GradientDescent() {
this.learningRate = 0D;
}

public double predict(double[] inp){
double[] features = new double[inp.length + 1];
features[0] = 1;
for(int i = 0; i < inp.length; i++) {
features[i+1] = inp[i];
}

double prediction = 0;
for(int i = 0; i < parameters.length; i++) {
prediction = parameters[i] * features[i];
}

return prediction;
}

public void train(){
double[] tempParameters = new double[parameters.length];
for(int i = 0; i < parameters.length; i++) {
tempParameters[i] = parameters[i] - learningRate * partialDerivative(i);
//System.out.println(tempParameters[i] + " = " + parameters[i] + " - " + learningRate + " * " + partialDerivative(i));
}

System.out.println("Before train: parameters := " + Arrays.toString(parameters) + " -> cost function := " + costFunction());
parameters = tempParameters;
System.out.println("After first iteration: parameters := " + Arrays.toString(parameters) + " -> cost function := " + costFunction());
}

private double partialDerivative(int index) {
double sum = 0;
for(int i = 0; i < trainingData.length; i++) {
double[] input = new double[trainingData[i].length - 1];
int j = 0;
for(; j < trainingData[i].length - 1; j++) {
input[j] = trainingData[i][j];
}
sum += ((predict(input) - trainingData[i][j]) * trainingData[i][index]);
}

return (1D/trainingData.length) * sum;
}

public double[][] getTrainingData() {
return trainingData;
}
public void setTrainingData(double[][] data) {
this.trainingData = data;
this.means = new double[this.trainingData[0].length-1];
this.scale = new double[this.trainingData[0].length-1];

for(int j = 0; j < data[0].length-1; j++) {
double min = data[0][j], max = data[0][j];
double sum = 0;
for(int i = 0; i < data.length; i++) {
if(data[i][j] < min) min = data[i][j];
if(data[i][j] > max) max = data[i][j];
sum += data[i][j];
}
scale[j] = max - min;
means[j] = sum / data.length;
}
}

public double[] getParameters() {
return parameters;
}
public void setParameters(double[] parameters) {
this.parameters = parameters;
}

public double getLearningRate() {
return learningRate;
}
public void setLearningRate(double learningRate) {
this.learningRate = learningRate;
}

/** 1 m i i 2
* J(theta) = ----- * SUM( h (x ) - y )
* 2*m i=1 theta
*/
public double costFunction() {
double sum = 0;

for(int i = 0; i < trainingData.length; i++) {
double[] input = new double[trainingData[i].length - 1];
int j = 0;
for(; j < trainingData[i].length - 1; j++) {
input[j] = trainingData[i][j];
}
sum += Math.pow(predict(input) - trainingData[i][j], 2);
}

double factor = 1D/(2*trainingData.length);
return factor * sum;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder("hypothesis: ");
int i = 0;
sb.append(parameters[i++] + " + ");
for(; i < parameters.length-1; i++) {
sb.append(parameters[i] + "*x" + i + " + ");
}
sb.append(parameters[i] + "*x" + i);

sb.append("\n Feature scale: ");
for(i = 0; i < scale.length-1; i++) {
sb.append(scale[i] + " ");
}
sb.append(scale[i]);

sb.append("\n Feature means: ");
for(i = 0; i < means.length-1; i++) {
sb.append(means[i] + " ");
}
sb.append(means[i]);

sb.append("\n Cost fuction: " + costFunction());

return sb.toString();
}

public static void main(String[] args) {

final double[][] TDATA = {
{200, 2, 20000},
{300, 2, 41000},
{400, 3, 51000},
{500, 3, 61500},
{800, 4, 41000},
{900, 5, 141000}
};

GradientDescent gd = new GradientDescent();
gd.setTrainingData(TDATA);
gd.setParameters(new double[]{0D,0D,0D});
gd.setLearningRate(0.00001);
gd.train();
//System.out.println(gd);
//System.out.println("PREDICTION: " + gd.predict(new double[]{300, 2}));
}
}

编辑:

我更新了代码以使其更具可读性,并尝试将其映射到 Douglas 使用的符号。我认为它现在工作得更好了,但仍有一些我不完全理解的阴暗区域。

似乎如果我有多个参数(如下例所示,房间数和面积),则预测与第二个参数(在本例中为面积)密切相关,并且改变影响不大第一个参数(房间数)。

这是对 {2, 200} 的预测:

PREDICTION: 200000.00686158828

这是对 {5, 200} 的预测:

PREDICTION: 200003.0068315415

如您所见,这两个值之间几乎没有任何区别。

我尝试将数学转化为代码的尝试是否仍然存在错误?

这是更新后的代码:

import java.util.*;

public class GradientDescent {

private double[][] trainingData;
private double[] means;
private double[] scale;

private double[] parameters;
private double learningRate;

GradientDescent() {
this.learningRate = 0D;
}

public double predict(double[] inp) {
return predict(inp, this.parameters);
}
private double predict(double[] inp, double[] parameters){
double[] features = concatenate(new double[]{1}, inp);

double prediction = 0;
for(int j = 0; j < features.length; j++) {
prediction += parameters[j] * features[j];
}

return prediction;
}

public void train(){
readjustLearningRate();

double costFunctionDelta = Math.abs(costFunction() - costFunction(iterateGradient()));

while(costFunctionDelta > 0.0000000001) {
System.out.println("Old cost function : " + costFunction());
System.out.println("New cost function : " + costFunction(iterateGradient()));
System.out.println("Delta: " + costFunctionDelta);

parameters = iterateGradient();
costFunctionDelta = Math.abs(costFunction() - costFunction(iterateGradient()));
readjustLearningRate();
}
}

private double[] iterateGradient() {
double[] nextParameters = new double[parameters.length];
// Calculate parameters for the next iteration
for(int r = 0; r < parameters.length; r++) {
nextParameters[r] = parameters[r] - learningRate * partialDerivative(r);
}

return nextParameters;
}
private double partialDerivative(int index) {
double sum = 0;
for(int i = 0; i < trainingData.length; i++) {
int indexOfResult = trainingData[i].length - 1;
double[] input = Arrays.copyOfRange(trainingData[i], 0, indexOfResult);
sum += ((predict(input) - trainingData[i][indexOfResult]) * trainingData[i][index]);
}

return sum/trainingData.length ;
}
private void readjustLearningRate() {

while(costFunction(iterateGradient()) > costFunction()) {
// If the cost function of the new parameters is higher that the current cost function
// it means the gradient is diverging and we have to adjust the learning rate
// and recalculate new parameters
System.out.print("Learning rate: " + learningRate + " is too big, readjusted to: ");
learningRate = learningRate/2;
System.out.println(learningRate);
}
// otherwise we are taking small enough steps, we have the right learning rate
}

public double[][] getTrainingData() {
return trainingData;
}
public void setTrainingData(double[][] data) {
this.trainingData = data;
this.means = new double[this.trainingData[0].length-1];
this.scale = new double[this.trainingData[0].length-1];

for(int j = 0; j < data[0].length-1; j++) {
double min = data[0][j], max = data[0][j];
double sum = 0;
for(int i = 0; i < data.length; i++) {
if(data[i][j] < min) min = data[i][j];
if(data[i][j] > max) max = data[i][j];
sum += data[i][j];
}
scale[j] = max - min;
means[j] = sum / data.length;
}
}

public double[] getParameters() {
return parameters;
}
public void setParameters(double[] parameters) {
this.parameters = parameters;
}

public double getLearningRate() {
return learningRate;
}
public void setLearningRate(double learningRate) {
this.learningRate = learningRate;
}

/** 1 m i i 2
* J(theta) = ----- * SUM( h (x ) - y )
* 2*m i=1 theta
*/
public double costFunction() {
return costFunction(this.parameters);
}
private double costFunction(double[] parameters) {
int m = trainingData.length;
double sum = 0;

for(int i = 0; i < m; i++) {
int indexOfResult = trainingData[i].length - 1;
double[] input = Arrays.copyOfRange(trainingData[i], 0, indexOfResult);
sum += Math.pow(predict(input, parameters) - trainingData[i][indexOfResult], 2);
}

double factor = 1D/(2*m);
return factor * sum;
}

private double[] normalize(double[] input) {
double[] normalized = new double[input.length];
for(int i = 0; i < input.length; i++) {
normalized[i] = (input[i] - means[i]) / scale[i];
}

return normalized;
}

private double[] concatenate(double[] a, double[] b) {
int size = a.length + b.length;

double[] concatArray = new double[size];
int index = 0;

for(double d : a) {
concatArray[index++] = d;
}
for(double d : b) {
concatArray[index++] = d;
}

return concatArray;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder("hypothesis: ");
int i = 0;
sb.append(parameters[i++] + " + ");
for(; i < parameters.length-1; i++) {
sb.append(parameters[i] + "*x" + i + " + ");
}
sb.append(parameters[i] + "*x" + i);

sb.append("\n Feature scale: ");
for(i = 0; i < scale.length-1; i++) {
sb.append(scale[i] + " ");
}
sb.append(scale[i]);

sb.append("\n Feature means: ");
for(i = 0; i < means.length-1; i++) {
sb.append(means[i] + " ");
}
sb.append(means[i]);

sb.append("\n Cost fuction: " + costFunction());

return sb.toString();
}

public static void main(String[] args) {

final double[][] TDATA = {
//number of rooms, area, price
{2, 200, 200000},
{3, 300, 300000},
{4, 400, 400000},
{5, 500, 500000},
{8, 800, 800000},
{9, 900, 900000}
};

GradientDescent gd = new GradientDescent();
gd.setTrainingData(TDATA);
gd.setParameters(new double[]{0D, 0D, 0D});
gd.setLearningRate(0.1);
gd.train();
System.out.println(gd);
System.out.println("PREDICTION: " + gd.predict(new double[]{3, 600}));
}
}

最佳答案

看起来你的开始是合理的,但在将数学转换为代码时存在一些问题。请参阅以下数学。

The math

我采取了几个步骤来阐明数学和算法的收敛机制。

  1. 为了提高易读性,在符号中使用了更标准的逗号分隔下标,而不是使用括号上标来表示行。
  2. 已尝试对求和控制变量使用零基数以匹配 Java/C 索引约定,而不会在数学中引入错误。 (希望正确完成。)
  3. 进行了类(class) Material 中隐含的各种替换。
  4. 确定已发布代码中变量名称与数学表示之间的映射。

在那之后,很明显在求和循环中除了缺少加号之外还有更多的错误。偏导数似乎需要重写或重大修改以匹配类(class)概念。

请注意,k=0->n 的内部循环生成所有特征的点积,然后在 i=0->m-1 循环中应用以解释每个训练案例。

所有这些都必须包含在每次迭代 r 中。该外循环的循环标准不应是某个最大 r 值。一旦收敛充分完成,您将需要满足一些标准。


针对评论的补充说明:

由于 Martin Fowler 所说的 Symantic Gap,很难发现代码中的不协调之处。在这种情况下,它介于三件事之间。

  1. 数学表示
  2. 讲座术语
  3. 代码中的算法

重构成员变量并从 x 矩阵中分离出 y vector (如下所示)很可能有助于发现不协调之处。

private int countMExamples;  
private int countNFeatures;
private double[][] aX;
private double[] aY;
private double[] aMeans;
private double[] aScales;
private double[] aParamsTheta;
private double learnRate;

关于多元梯度下降的Java实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41144206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com