TensorFlow 中的线性回归

问题描述 投票:0回答:1

如何在 TensorFlow 中执行线性回归并给出整数作为输出?

我的数据是:

Input = [
[1,2,1],
[2,2,2],
[1,1,1],
...
]

Output = [4,6,3,...]

输出只是一个整数,即输入维度的总和。 输出可以是任何之前未知的整数。

我能够成功地在 scikit-learn 线性回归中进行预测,以了解输出是输入的总和。

如何设计一个 Tensorflow 模型来学习这种行为,并将总和作为输出而不是一个二进制值?

python tensorflow machine-learning linear-regression
1个回答
0
投票

要在 TensorFlow 中执行线性回归并获得整数作为输出,您可以修改模型的架构。您将需要使用强制整数预测的自定义损失函数。这是分步指南:

  1. 导入必要的库:
import tensorflow as tf
import numpy as np
  1. 准备您的数据:
input_data = np.array([
    [1, 2, 1],
    [2, 2, 2],
    [1, 1, 1],
    # Add more data points as needed
])

output_data = np.array([4, 6, 3])  # Integer outputs
  1. 创建一个强制整数预测的自定义损失函数。实现此目的的一种方法是定义一个损失,根据预测值与其舍入整数之间的差异来惩罚非整数预测:
def custom_loss(y_true, y_pred):
    y_pred_rounded = tf.round(y_pred)
    return tf.reduce_mean(tf.square(y_true - y_pred_rounded))
  1. 使用线性回归架构定义并编译 TensorFlow 模型:
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(3,)),  # Input shape matches your data
    tf.keras.layers.Dense(1)  # Linear regression layer with one output neuron
])

model.compile(optimizer='adam', loss=custom_loss)
  1. 使用输入和输出数据训练模型:
model.fit(input_data, output_data, epochs=1000)  # Adjust the number of epochs as needed
  1. 模型训练完成后,您就可以进行预测:
predictions = model.predict(input_data)

模型现在应该提供近似输入维度总和的整数预测。

© www.soinside.com 2019 - 2024. All rights reserved.