线性回归-Tensorflow

时间:2019-01-07 18:17:48

标签: python tensorflow regression linear-regression linear

我正在使用Tensorflow学习深度学习和机器学习,我需要做出一个预测,即输入是直方图(每天),我以序号形式介绍日期(736608是2017-10-06)该输入所需的输出为8334.71。问题是经过一番迭代之后,损失又让我难忘了。

模型:

def create_model(self):
    input = tf.placeholder(dtype=tf.float32, name='input', shape=(None, 1))
    self.model = tf.layers.dense(inputs=input, units=1, name='output')

def get_training_data_from_elastic_result(self, file_path):
    result = {
        'data': np.array([], dtype=np.float32),
        'label': np.array([], dtype=np.float32)
    }
    input_json = json.load(open(file_path, 'r'))
    bucket_values = input_json['aggregations']['id']['date']['histogram']['buckets']
    for bucket in bucket_values:
        current_ordinal_date = datetime.fromtimestamp(float(bucket['key'] / 1000)).toordinal()
        result['data'] = np.append(arr=result['data'], values=current_ordinal_date)
        result['label'] = np.append(arr=result['label'], values=round(float(bucket['relevance_sum']['value']), 2))

    """Reshape to
    [
        [737051.],
        [737052.],
        [737053.]
    ]

    [
        [3108.11],
        [1499.51],
        [1327.35]
    ]
    """
    result['data'] = result['data'].reshape(-1, 1)
    result['label'] = result['label'].reshape(-1, 1)

    return result

def train(self, input_data, input_labels, learning_rate=0.1, num_steps=1000, display_steps=10):
        real_output = tf.placeholder(dtype=tf.float32, name='real_output', shape=(None, 1))
        loss = tf.losses.mean_squared_error(labels=real_output, predictions=self.model)
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss=loss)

        for step in range(num_steps):
            _, error_value = self.session.run([optimizer, loss], feed_dict={'input:0': input_data, 'real_output:0': input_labels})
            if (step + 1) % display_steps == 0:
                self.MODEL_LOGGER.info("Epoch: {epoch} Cost {cost}".format(
                    epoch=(step + 1),
                    cost=error_value
                ))

输出

INFO:model.model:Epoch: 1 Cost=1.06697175859e+12
INFO:model.model:Epoch: 2 Cost=1.25770053337e+34
INFO:model.model:Epoch: 3 Cost=inf
INFO:model.model:Epoch: 4 Cost=inf
INFO:model.model:Epoch: 5 Cost=inf
INFO:model.model:Epoch: 6 Cost=nan
INFO:model.model:Epoch: 7 Cost=nan

谢谢:)

0 个答案:

没有答案