如何在 TensorFlow 中执行线性回归并给出整数作为输出?
我的数据是:
Input = [
[1,2,1],
[2,2,2],
[1,1,1],
...
]
Output = [4,6,3,...]
输出只是一个整数,即输入维度的总和。 输出可以是任何之前未知的整数。
我能够成功地在 scikit-learn 线性回归中进行预测,以了解输出是输入的总和。
如何设计一个 Tensorflow 模型来学习这种行为,并将总和作为输出而不是一个二进制值?
要在 TensorFlow 中执行线性回归并获得整数作为输出,您可以修改模型的架构。您将需要使用强制整数预测的自定义损失函数。这是分步指南:
import tensorflow as tf
import numpy as np
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
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))
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)
model.fit(input_data, output_data, epochs=1000) # Adjust the number of epochs as needed
predictions = model.predict(input_data)
模型现在应该提供近似输入维度总和的整数预测。