Попытаться вручную пересчитать результаты множественной линейной регрессии с помощью tensorflow-java, но веса кажутся неJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Попытаться вручную пересчитать результаты множественной линейной регрессии с помощью tensorflow-java, но веса кажутся не

Сообщение Anonymous »

Я хотел бы использовать тензорный поток с Java. Чтобы быть уверенным, что я хорошо понимаю, я играю с небольшим простым вариантом использования.
Я создаю набор данных из 50 наблюдений с 6 функциями.
Основная формула: y = a1 * 1 + a2 * 1 + a3 * 1 + a4 * 1 + a5 * 1
Для
примера:

Код: Выделить всё

1 = 0.16*1 + 0.16*1 + 0.16*1 + 0.16*1 + 0.16*1

5 = 0.80*1 + 0.80*1 + 0.80*1 + 0.80*1 + 0.80*1

25 = 4.16*1 + 4.16*1 + 4.16*1 + 4.16*1 + 4.16*1
Поэтому я хотел бы получить результаты с весами, равными единице. Но приведенный ниже код возвращает мне веса, близкие к 6, как если бы он возвращал сумму моих ожидаемых весов, равных единице. Возможно, у меня неправильная конфигурация форм тензоров. Но если вместо этого пересчитать вручную я использую правильный способ прогнозирования, это будет хорошо. Но что, если меня интересует хорошо знать веса, а не просто делать прогнозы?
Приведенный ниже код взят отсюда, и идея состоит в том, чтобы добавить 6 функций для преобразования этого примера кода линейной регрессии. в образец кода множественной линейной регрессии.

Код: Выделить всё

package com.foo.bar;

import org.tensorflow.*;
import org.tensorflow.framework.optimizers.*;
import org.tensorflow.ndarray.Shape;
import org.tensorflow.op.*;
import org.tensorflow.op.core.*;
import org.tensorflow.op.math.*;
import org.tensorflow.types.*;

import java.util.*;
import java.util.stream.*;

public class HelloTensorFlow {

private static final int N = 50;
private static final float NFeaturesF = 6;
private static final int NFeatures = (int) NFeaturesF;

public static final float LEARNING_RATE = 0.01f;
public static final String WEIGHT_VARIABLE_NAME = "weight";
public static final String BIAS_VARIABLE_NAME = "bias";

public static void computeMLRExampleForStackoverflow() {

System.out.println("Begin of example with only 6 features: y = a1 * 1 + ...  + an * 1 ->5 = 0.80*1 + 0.80*1 + 0.80*1 + 0.80*1 + 0.80*1");
// Prepare the data
// 1 = 0.16*1 + 0.16*1 + 0.16*1 + 0.16*1 + 0.16*1
// 5 = 0.80*1 + 0.80*1 + 0.80*1 + 0.80*1 + 0.80*1
float[][] xValues = new float[N][NFeatures];
for (var i = 0; i < N; ++i) {
float[] xItem = new float[NFeatures];
for (var j = 0; j < xItem.length; ++j) {
xItem[j] = ((i + 1) / NFeaturesF);
}
xValues[i] = xItem;
}

float[] yValues = new float[N];
for (int i = 0; i < yValues.length; i++) {
yValues[i] = (float) ((float) (xValues[i][0] * 1) + (xValues[i][1] * 1) + (xValues[i][2] * 1) + (xValues[i][3] * 1) + (xValues[i][4] * 1) + (xValues[i][5] * 1));
}

try (Graph graph = new Graph()) {
Ops tf = Ops.create(graph);

// Define placeholders
Placeholder xData = tf.placeholder(TFloat32.class, Placeholder.shape(Shape.of(1, NFeatures))); // 6 features
Placeholder yData = tf.placeholder(TFloat32.class, Placeholder.shape(Shape.scalar()));

// Define variables
Variable weight = tf.withName(WEIGHT_VARIABLE_NAME).variable(tf.random.randomStandardNormal(tf.constant(Shape.of(1, NFeatures)), TFloat32.class));
Variable bias = tf.withName(BIAS_VARIABLE_NAME).variable(tf.constant(0f));

// Define the model function weight*x + bias
Mul mul = tf.math.mul(xData, weight);
Add yPredicted = tf.math.add(mul, bias);

// Define loss function MSE
Pow sum = tf.math.pow(tf.math.sub(yPredicted, yData), tf.constant(2f));
Div mse = tf.math.div(sum, tf.constant(2f * Nlmr));

// Back-propagate gradients to variables for training
Optimizer optimizer = new GradientDescent(graph, LEARNING_RATE);
Op minimize = optimizer.minimize(mse);

try (Session session = new Session(graph)) {

///// results before training operation
System.out.println("-- Results at the run 0.");
var tensor0 = session.runner()
.fetch(WEIGHT_VARIABLE_NAME)
.run().get(0);
try (TFloat32 weightValue = (TFloat32) tensor0) {
weightValue.scalars().forEach(value -> System.out.println("\tValue of weight: " + value.getFloat()));
}

/// Iteration
for (var iteration = 0; iteration  System.out.println("Value of weight: "  + value.getFloat()));
}
}

// After training
// Extract linear regression model weight and bias values
System.out.println("----- Results after the training iterations");
var tensorList0 = session.runner()
.fetch(WEIGHT_VARIABLE_NAME)
.fetch(BIAS_VARIABLE_NAME)
.run();
try (TFloat32 weightValue = (TFloat32) tensorList0.get(0);
TFloat32 biasValue = (TFloat32) tensorList0.get(1)) {
biasValue.scalars().forEach(value -> System.out.println("Bias is : " + value.getObject()));
weightValue.scalars().forEach(value -> System.out.println("Value of weight: " + value.getObject()));

System.out.println("-----Compute results computing MANUALLY the estimation using weights and bias");
int xIndexToPredict = 25;
float[] xToPredict = xValues[xIndexToPredict];
var testResults = biasValue.getFloat() +
xToPredict[0] * weightValue.getFloat(0, 0) +
xToPredict[1] * weightValue.getFloat(0, 1) +
xToPredict[2] * weightValue.getFloat(0, 2) +
xToPredict[3] * weightValue.getFloat(0, 3) +
xToPredict[4] * weightValue.getFloat(0, 4) +
xToPredict[5] * weightValue.getFloat(0, 5);
System.out.println("Predicted  index  is " + xIndexToPredict + ". The xValues is " + Arrays.toString(xValues[xIndexToPredict]).toString() + ". Y is " + yValues[xIndexToPredict] + ". Y_pred is " + testResults + ".");
}

// Compute results using tensorFlow session.
int xIndexToPredict = 25;
float[] xToPredict = xValues[xIndexToPredict];
float predictedY = 0f;
try (TFloat32 xTensor = TFloat32.vectorOf(xToPredict);
TFloat32 yTensor = TFloat32.scalarOf(predictedY);

TFloat32 yPredictedTensor = (TFloat32) session.runner()
.feed(xData.asOutput(), xTensor)
.feed(yData.asOutput(), yTensor)
.fetch(yPredicted)
.run().get(0)) {

predictedY = yPredictedTensor.getFloat();
System.out.println("-----Compute results using tensorFlow session.");
System.out.println("Predicted  index  is " + xIndexToPredict + ". The xValues is " + Arrays.toString(xValues[xIndexToPredict]).toString() + ". Y is " + yValues[xIndexToPredict] + ". Y_pred is " + predictedY + ".");
}

}
}
}
}

Этот код возвращается в консоль

Код: Выделить всё

-- Results at the run 0.
Value of weight: -0.2316753
Value of weight: 1.1006204
Value of weight: -0.019320484
Value of weight: 0.008380135
Value of weight: 0.6988849
Value of weight: -0.2371562
-- Results at run 1.
Value of weight: 4.7759395
Value of weight: 4.886012
Value of weight: 4.7934833
Value of weight: 4.795772
Value of weight: 4.852821
Value of weight: 4.7754865
.
.
.
-- Results at run 201.
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
----- Results after the training iterations
Bias is : 1.3781966E-5
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
Value of weight: 5.999997
-----Compute results computing MANUALLY the estimation using weights and bias
Predicted  index  is 25. The xValues is [4.3333335, 4.3333335, 4.3333335, 4.3333335, 4.3333335, 4.3333335]. **Y is 26.000002. Y_pred is 155.99994**.
-----Compute results using tensorFlow session.
Predicted  index  is 25. The xValues is [4.3333335, 4.3333335, 4.3333335, 4.3333335, 4.3333335, 4.3333335]. **Y is 26.000002.  Y_pred is 26.000002**.

Как видите, значения весов не равны 1, как ожидалось. Но оценка с помощью сессионного бегуна кажется хорошей. Очевидно, я что-то упускаю. Я думаю, это может быть связано с размерами тензоров и выполняемыми над ними операциями. Кто-нибудь может мне помочь, пожалуйста?

Подробнее здесь: https://stackoverflow.com/questions/791 ... on-with-te
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»