Reputation: 825
To better illustrate my question, I hereby use a very simple regression model (1 second run even by Gradient Descent).
I want to use a class reg_model()
to contain my model. But when I run below code, I got the error TypeError: 'type' object is not subscriptable
.
The error is from sess.run([reg_model['train_step'], reg_model['mean_square_loss']], feed_dict={x: training_set_inputs, yLb: training_set_outputs})
. If I modified this code into sess.run([train_step, mean_square_loss], feed_dict={x: training_set_inputs, yLb: training_set_outputs})
, and then remove the definition class reg_model():
, then my code works well.
But I really want to use reg_model()
to store the model, so that it can be a well defined object itself. How can I modify my code to achieve this?
import tensorflow as tf
import numpy as np
# values of training data
training_set_inputs =np.array([[0,1,2],[0,0,2],[1,1,1],[1,0,1]])
training_set_outputs =np.array([[1],[0],[1],[0]])
learning_rate = 0.5
class reg_model():
# containers and operations
x = tf.placeholder(tf.float32, [None, 3])
W = tf.Variable(tf.zeros([3, 1]))
B = tf.Variable(tf.zeros([1]))
yHat = tf.nn.sigmoid(tf.matmul(x, W) + B)
yLb = tf.placeholder(tf.float32, [None, 1])
mean_square_loss = tf.reduce_mean(tf.square(yLb - yHat))
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(mean_square_loss)
# use session to execute graphs
with tf.Session() as sess:
init=tf.global_variables_initializer()
sess.run(init)
# start training
for i in range(10000):
sess.run([reg_model['train_step'], reg_model['mean_square_loss']], feed_dict={x: training_set_inputs, yLb: training_set_outputs})
# do prediction
x0=np.float32(np.array([[0.,1.,0.]]))
y0=tf.nn.sigmoid(tf.matmul(x0,W) + B)
print('%.15f' % sess.run(y0))
Upvotes: 2
Views: 2518
Reputation: 2087
You should use reg_model.train_step
and reg_model.mean_square_loss
, not reg_model['train_step']
and reg_model['mean_square_loss']
Upvotes: 1