python - 使用 Tensorflow 泊松回归模型进行预测

标签 python tensorflow regression poisson

希望使用 Tensorflow 的输出来预测 Tensorflow 模型 - 请参阅下面的引用资料以获取扩展的代码示例。如何使用 session 来使用 X_train 进行预测?

import tensorflow as tf
import numpy as np
import pandas as pd

def gen_data(N = 10000):
    data = np.random.uniform(-1, 1, (N, 3))
    data = sm.add_constant(data)
    data = pd.DataFrame(data, columns = ['intercept', 'Var1', 'Var2', 'Var3'])
    lam = np.exp(-2*data['intercept'] + data['Var1'] - 0.5*data['Var2'] + 0.3*data['Var3'] )
    resp = np.random.poisson(lam = lam)
    data['lam'] = lam
    data['resp'] = resp
    return data

dtrain = gen_data()
dtrain.head(5)

# Original
X_train = tf.constant(dtrain[['intercept', 'Var1', 'Var2', 'Var3']].as_matrix(), name = 'X', dtype=tf.float32)
y = tf.constant(value = list(dtrain['resp']), dtype = tf.float32, name='y', shape=(dtrain.shape[0], 1))
w = tf.Variable(tf.zeros([4, 1]))
y_hat = tf.exp(tf.matmul(X_train, w))
loss_function = tf.reduce_mean(-y*tf.log(y_hat)+y_hat)

# # w/Intercept
# X_train = tf.constant(dtrain[['Var1', 'Var2', 'Var3']].as_matrix(), name = 'X', dtype=tf.float32)
# y = tf.constant(value = list(dtrain['resp']), dtype = tf.float32, name='y', shape=(dtrain.shape[0], 1))
# w = tf.Variable(tf.zeros([3, 1]))
# b = tf.Variable(tf.zeros([1]))
# y_hat = tf.add(tf.matmul(X_train, w), b)
# loss_function = tf.nn.log_poisson_loss(targets=y, log_input= y_hat, compute_full_loss = True)

train_step = tf.train.AdamOptimizer(0.001).minimize(loss_function)
init = tf.global_variables_initializer()
session = tf.InteractiveSession()
session.run(init)

for i in range(10000):
    session.run(train_step)

print(w.eval())

输出(以 [0] 位置作为截距):

[[-1.98130631]
 [ 1.00653005]
 [-0.49286723]
 [ 0.27313855]]

这会引发错误:

pred_y = session.run(y_hat, feed_dict={X:dtrain[['Var1', 'Var2', 'Var3']].as_matrix()})

    # fig, ax = plt.subplots()
    # ax.scatter(test_y, pred_y)
    # # ax.plot([test_y.min(), test_y.max()], [test_y.min(), test_y.max()], 'k--', lw=3)
    # ax.set_xlabel('Measured')
    # ax.set_ylabel('Predicted')
    # plt.show()

错误输出:

ValueError: Cannot feed value of shape (10000, 3) for Tensor 'Placeholder:0', which has shape '(?, 14)'

引用号:https://github.com/gorkemozkaya/Data-Science-Notebooks/blob/master/Poisson%20regression%20with%20Tensorflow.ipynb

最佳答案

您尚未为 X 定义占位符。

关于python - 使用 Tensorflow 泊松回归模型进行预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940189/

相关文章:

用于组装的 python curl

python - Django AttributeError 模型对象没有属性 'filter'

python-3.x - TF2.0 : Translation model: Error when restoring the saved model: Unresolved object in checkpoint (root). 优化器.iter:属性

r - 系数表在秩缺陷拟合中没有 NA 行;如何插入它们?

python - Pandas - 滚动斜率计算

C++ ARMA方法与回归分析

python - MessagePack 和消息帧

python - 在 Python 中执行 *nix 二进制文件

tensorflow - tensorflow 中的常规模型检查点和保存的模型有什么区别?

python - 在处理 MNIST 数据集时 opencv 中出现大小错误