sess.run()时出现“ TypeError:'类型'对象不可下标”

时间:2019-03-18 01:21:39

标签: python tensorflow neural-network deep-learning

为了更好地说明我的问题,我在此使用一个非常简单的回归模型(甚至通过Gradient Descent运行1秒)。

我想使用类reg_model()来包含我的模型。但是当我运行下面的代码时,出现了错误TypeError: 'type' object is not subscriptable

错误来自sess.run([reg_model['train_step'], reg_model['mean_square_loss']], feed_dict={x: training_set_inputs, yLb: training_set_outputs})。如果我将此代码修改为sess.run([train_step, mean_square_loss], feed_dict={x: training_set_inputs, yLb: training_set_outputs}),然后删除定义class reg_model():,那么我的代码将运行良好。

但是我真的很想使用reg_model()来存储模型,以便它可以是一个定义良好的对象本身。如何修改我的代码来实现这一目标?

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))

1 个答案:

答案 0 :(得分:1)

您应该使用reg_model.train_stepreg_model.mean_square_loss,而不要使用reg_model['train_step']reg_model['mean_square_loss']