希望使用来自Tensorflow的输出预测Tensorflow模型 - 请参阅下面的参考文献以获取扩展代码示例。如何使用会话预测使用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)'
答案 0 :(得分:1)
您尚未为X定义占位符。