Python 如何在tensorflow中训练线性模型?

Python 如何在tensorflow中训练线性模型?,python,tensorflow,Python,Tensorflow,我在CSV中生成了一些输入数据,其中“awesomeness”是“age*10”。看起来是这样的: age, awesomeness 67, 670 38, 380 32, 320 69, 690 40, 400 写一个tensorflow模型可以从“年龄”预测“惊人”,这应该很简单,但我不能让它工作 当我运行培训时,我得到的输出是: accuracy: 0.0 <----------------------------------- What!?? accuracy/baseline_

我在CSV中生成了一些输入数据,其中“awesomeness”是“age*10”。看起来是这样的:

age, awesomeness
67, 670
38, 380
32, 320
69, 690
40, 400
写一个tensorflow模型可以从“年龄”预测“惊人”,这应该很简单,但我不能让它工作

当我运行培训时,我得到的输出是:

accuracy: 0.0 <----------------------------------- What!??
accuracy/baseline_label_mean: 443.8
accuracy/threshold_0.500000_mean: 0.0
auc: 0.0
global_step: 6000
labels/actual_label_mean: 443.8
labels/prediction_mean: 1.0
loss: -2.88475e+09
precision/positive_threshold_0.500000_mean: 1.0
recall/positive_threshold_0.500000_mean: 1.0
几点注意:

  • 本文所基于的原始示例教程位于此处

  • 注意,我使用的是DNNClassifier,而不是LinearClassifier,因为我特别想处理连续输入变量

  • 许多示例仅使用“预制”数据集,已知这些数据集可用于示例;我的数据集是手动生成的,绝对不是随机的

  • 我已验证csv加载程序是否将数据正确加载为int64值

  • 训练和测试数据生成相同,但具有不同的值;但是,使用data.training作为测试数据仍然会返回0%的准确度,因此毫无疑问有些东西不起作用,这不仅仅是过度拟合


首先,您描述的是回归任务,而不是分类任务。因此,使用DNNClassier和LinearClassifier都是错误的。这也使得准确性成为判断模型是否有效的错误数量。我建议你仔细阅读这两种不同的背景,例如《统计学习的要素》一书中的内容

但这里有一个简短的答案来回答你的问题。假设你有一个线性模型

awesomeness_predicted = slope * age
其中
slope
是要从数据中学习的参数。假设您有数据
age[0],…,age[N]
和相应的awesomeness值
a_data[0],…,a_data[N]
。为了确定你的模型是否运行良好,我们将使用均方误差,即

error = sum((a_data[i] - a_predicted[i])**2 for i in range(N))
您现在要做的是从随机猜测坡度开始,然后使用“渐变下降”逐步改进。下面是一个纯tensorflow的完整工作示例

import tensorflow as tf
import numpy as np

DTYPE = tf.float32

## Generate Data
age = np.array([67, 38, 32, 69, 40])
awesomeness = 10 * age

## Generate model
# define the parameter of the model
slope = tf.Variable(initial_value=tf.random_normal(shape=(1,), dtype=DTYPE))
# define the data inputs to the model as variable size tensors
x = tf.placeholder(DTYPE, shape=(None,))
y_data = tf.placeholder(DTYPE, shape=(None,))
# specify the model
y_pred = slope * x
# use mean squared error as loss function
loss = tf.reduce_mean(tf.square(y_data - y_pred))
target = tf.train.AdamOptimizer().minimize(loss)

## Train Model
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(100000):
        _, training_loss = sess.run([target, loss],
                                    feed_dict={x: age, y_data: awesomeness})
    print("Training loss: ", training_loss)
    print("Found slope=", sess.run(slope))

首先,您描述的是回归任务,而不是分类任务。因此,使用DNNClassier和LinearClassifier都是错误的。这也使得准确性成为判断模型是否有效的错误数量。我建议你仔细阅读这两种不同的背景,例如《统计学习的要素》一书中的内容

但这里有一个简短的答案来回答你的问题。假设你有一个线性模型

awesomeness_predicted = slope * age
其中
slope
是要从数据中学习的参数。假设您有数据
age[0],…,age[N]
和相应的awesomeness值
a_data[0],…,a_data[N]
。为了确定你的模型是否运行良好,我们将使用均方误差,即

error = sum((a_data[i] - a_predicted[i])**2 for i in range(N))
您现在要做的是从随机猜测坡度开始,然后使用“渐变下降”逐步改进。下面是一个纯tensorflow的完整工作示例

import tensorflow as tf
import numpy as np

DTYPE = tf.float32

## Generate Data
age = np.array([67, 38, 32, 69, 40])
awesomeness = 10 * age

## Generate model
# define the parameter of the model
slope = tf.Variable(initial_value=tf.random_normal(shape=(1,), dtype=DTYPE))
# define the data inputs to the model as variable size tensors
x = tf.placeholder(DTYPE, shape=(None,))
y_data = tf.placeholder(DTYPE, shape=(None,))
# specify the model
y_pred = slope * x
# use mean squared error as loss function
loss = tf.reduce_mean(tf.square(y_data - y_pred))
target = tf.train.AdamOptimizer().minimize(loss)

## Train Model
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(100000):
        _, training_loss = sess.run([target, loss],
                                    feed_dict={x: age, y_data: awesomeness})
    print("Training loss: ", training_loss)
    print("Found slope=", sess.run(slope))
有关使用tflearn解决此问题的信息,请参见

""" Multiple Regression/Multi target Regression Example

The input features have 10 dimensions, and target features are 2 dimension.

"""

from __future__ import absolute_import, division, print_function

import tflearn
import numpy as np

# Regression data- 10 training instances
#10 input features per instance.
X=np.random.rand(10,10).tolist()
#2 output features per instance
Y=np.random.rand(10,2).tolist()

# Multiple Regression graph, 10-d input layer
input_ = tflearn.input_data(shape=[None,10])
#10-d fully connected layer
r1 = tflearn.fully_connected(input_,10)
#2-d fully connected layer for output
r1 = tflearn.fully_connected(r1,2)
r1 = tflearn.regression(r1, optimizer='sgd', loss='mean_square',
                                        metric='R2', learning_rate=0.01)

m = tflearn.DNN(r1)
m.fit(X,Y, n_epoch=100, show_metric=True, snapshot_epoch=False)

#Predict for 1 instance
testinstance=np.random.rand(1,10).tolist()
print("\nInput features:  ",testinstance)
print("\n Predicted output: ")
print(m.predict(testinstance))
有关使用tflearn解决此问题的信息,请参见

""" Multiple Regression/Multi target Regression Example

The input features have 10 dimensions, and target features are 2 dimension.

"""

from __future__ import absolute_import, division, print_function

import tflearn
import numpy as np

# Regression data- 10 training instances
#10 input features per instance.
X=np.random.rand(10,10).tolist()
#2 output features per instance
Y=np.random.rand(10,2).tolist()

# Multiple Regression graph, 10-d input layer
input_ = tflearn.input_data(shape=[None,10])
#10-d fully connected layer
r1 = tflearn.fully_connected(input_,10)
#2-d fully connected layer for output
r1 = tflearn.fully_connected(r1,2)
r1 = tflearn.regression(r1, optimizer='sgd', loss='mean_square',
                                        metric='R2', learning_rate=0.01)

m = tflearn.DNN(r1)
m.fit(X,Y, n_epoch=100, show_metric=True, snapshot_epoch=False)

#Predict for 1 instance
testinstance=np.random.rand(1,10).tolist()
print("\nInput features:  ",testinstance)
print("\n Predicted output: ")
print(m.predict(testinstance))

有几件事我想说。 假设您正确加载了数据:

-这看起来像一个回归任务,您正在使用一个分类器。我并不是说它根本不起作用,但就像这样,你给每个年龄段的人贴上了标签,并且对整个批次进行了训练,每个时代都非常不稳定

-你得到了巨大的损失,你的梯度爆炸。有了这个玩具数据集,您可能需要调整超参数,如隐藏的神经元、学习速率和纪元数。尝试记录每个历元的损失值,看看这是否是问题所在


-最后一个建议是,使用一个更简单的模型来处理数据,可能适合您的任务,比如a,然后再放大

我想说几件事。 假设您正确加载了数据:

-这看起来像一个回归任务,您正在使用一个分类器。我并不是说它根本不起作用,但就像这样,你给每个年龄段的人贴上了标签,并且对整个批次进行了训练,每个时代都非常不稳定

-你得到了巨大的损失,你的梯度爆炸。有了这个玩具数据集,您可能需要调整超参数,如隐藏的神经元、学习速率和纪元数。尝试记录每个历元的损失值,看看这是否是问题所在


-最后一个建议是,使用一个更简单的模型来处理数据,可能适合您的任务,比如a,然后再放大。。。你能澄清一下这是如何推广到更复杂的模型的吗?这似乎特别适用于拟合线性模块,我已经知道y=k*x;我知道这就是我所问的,很公平,但这似乎挫败了在你已经需要知道数据集是什么的情况下尝试对数据集进行训练的目的……?这就是机器学习的工作原理(有一些统计分支处理非参数模型,但这是一个完全不同的野兽)。该模型与实际应用程序的唯一区别在于,后者通常涉及更复杂和更具表现力的模型。但你说你想要一个线性模型,所以这就是你得到的;)陛下你能澄清一下这是如何推广到更复杂的模型的吗?这似乎特别适用于拟合线性模块,我已经知道y=k*x;我知道这就是我所问的,很公平,但这似乎挫败了在你已经需要知道数据集是什么的情况下尝试对数据集进行训练的目的……?这就是机器学习的工作原理(有一些统计分支处理非参数模型,但这是一个完全不同的野兽)。该模型与实际应用程序的唯一区别在于,后者通常涉及更复杂和更具表现力的模型。但你说你想要一个线性模型,所以这就是你得到的;)