Python 无法为张量层提供值

Python 无法为张量层提供值,python,tensorflow,neural-network,Python,Tensorflow,Neural Network,我正在运行以下代码。我知道我们可以使用Keras。我试图学习tensorflow并使用它开发简单的2层神经网络 错误:值错误:无法为具有形状“(?,50)”的张量“layer-1/dropout/mul_1:0”输入形状(1001024)的值 将numpy导入为np np.随机种子(456) 导入tensorflow作为tf tf.set_random_seed(456) 将matplotlib.pyplot作为plt导入 作为dc导入deepchem 从sklearn.metrics导入准确性

我正在运行以下代码。我知道我们可以使用Keras。我试图学习tensorflow并使用它开发简单的2层神经网络

错误:值错误:无法为具有形状“(?,50)”的张量“layer-1/dropout/mul_1:0”输入形状(1001024)的值

将numpy导入为np
np.随机种子(456)
导入tensorflow作为tf
tf.set_random_seed(456)
将matplotlib.pyplot作为plt导入
作为dc导入deepchem
从sklearn.metrics导入准确性\u分数
def eval_tox21_超参数(n_hidden=50,n_layers=2,learning_rate=0.001,
辍学概率=0.5,n个时代=45,批量大小=100,
权重(正=真):
打印(“-------------------------------------------------------------”)
打印(“模型超参数”)
打印(“n\u隐藏=%d”%n\u隐藏)
打印(“n\u层=%d”%n\u层)
打印(“学习率=%f”%learning\u rate)
打印(“n个时代=%d”%n个时代)
打印(“批次大小=%d”%batch\u大小)
打印(“正权重=%s”%str(正权重))
打印(“辍学问题=%f”%辍学问题)
打印(“-------------------------------------------------------------”)
d=1024
graph=tf.graph()
使用graph.as_default():
_,(列车,有效,测试),u=dc.molnet.load_tox21()
列车X,列车y,列车w=train.X,train.y,train.w
valid\u X,valid\u y,valid\u w=valid.X,valid.y,valid.w
测试X,测试y,测试w=test.X,test.y,test.w
#删除额外任务
列车y=列车y[:,0]
valid_y=valid_y[:,0]
测试y=测试y[:,0]
列车w=列车w[:,0]
valid_w=valid_w[:,0]
测试w=测试w[:,0]
#生成张量流图
使用tf.name\u范围(“占位符”):
x=tf.占位符(tf.float32,(无,d))
y=tf.placeholder(tf.float32,(无,))
w=tf.placeholder(tf.float32,(无,))
keep_prob=tf.placeholder(tf.float32)
对于范围内的层(n_层):
打印(“当前图层为”,图层)
使用tf.name\u作用域(“层-%d”%layer):
W=tf.Variable(tf.random_normal((d,n_hidden)))
b=tf.Variable(tf.random_normal((1,n_隐藏)))
打印(“x_隐藏形状{}和W形状{}”。格式(x.shape,W.shape))
x_hidden=tf.nn.relu(tf.matmul(x,W)+b)
#申请退学
x_hidden=tf.nn.dropout(x_hidden,keep_prob)
x=x_隐藏
d=n_隐藏
使用tf.name_范围(“输出”):
W=tf.Variable(tf.random_normal((n_hidden,1)))
b=tf.变量(tf.随机_正态((1,1)))
打印(“输出W形状{}和x_隐藏形状{}”。格式(W.shape,x_隐藏.shape))
y_logit=tf.matmul(x_隐藏,W)+b
#sigmoid给出的类概率为1
y_one_prob=tf.sigmoid(y_logit)
#四舍五入P(y=1)将给出正确的预测。
y_pred=tf.round(y_one_prob)
打印(“y pred shape{}”.format(y_pred.shape))
具有tf.name_范围(“损失”):
#计算每个数据点的交叉熵项
y_expand=tf.expand_dims(y,1)
打印(“y展开形状{}”.format(y_展开.shape))
熵=tf.nn.sigmoid\u交叉\u熵\u与逻辑(逻辑=y\u逻辑,标签=y\u扩展)
打印(“熵形状{}”.format(熵形状))
#乘以重量
如果重量为正:
w_expand=tf.expand_dims(w,1)
熵=w_展开*熵
打印(“熵权发布形状{}”.format(entropy.shape))
#合计所有捐款
l=tf.减少总和(熵)
使用tf.name_范围(“optim”):
训练op=tf.train.AdamOptimizer(学习率)。最小化(l)
具有tf.name_范围(“摘要”):
tf.汇总。标量(“损失”,l)
merged=tf.summary.merge_all()
#hyperparam_str=“d-%d-隐藏-%d-lr-%f-n\U时期-%d-批次大小-%d-重量位置-%s”%(
#d,n_隐藏,学习率,n_时代,批量大小,str(重量正)
#train_writer=tf.summary.FileWriter('/tmp/fcnet func-'+hyperparam_str,
#tf.get_default_graph())
N=列车形状[0]
使用tf.Session()作为sess:
sess.run(tf.global\u variables\u initializer())
步长=0
对于范围内的历元(n_历元):
pos=0
而pos
您面临的错误或困难是什么?错误如说明所示。谢谢
    import numpy as np
    np.random.seed(456)
    import  tensorflow as tf
    tf.set_random_seed(456)
    import matplotlib.pyplot as plt
    import deepchem as dc
    from sklearn.metrics import accuracy_score

    def eval_tox21_hyperparams(n_hidden=50, n_layers=2, learning_rate=.001,
                               dropout_prob=0.5, n_epochs=45, batch_size=100,
                               weight_positives=True):

      print("---------------------------------------------")
      print("Model hyperparameters")
      print("n_hidden = %d" % n_hidden)
      print("n_layers = %d" % n_layers)
      print("learning_rate = %f" % learning_rate)
      print("n_epochs = %d" % n_epochs)
      print("batch_size = %d" % batch_size)
      print("weight_positives = %s" % str(weight_positives))
      print("dropout_prob = %f" % dropout_prob)
      print("---------------------------------------------")

      d = 1024
      graph = tf.Graph()
      with graph.as_default():
        _, (train, valid, test), _ = dc.molnet.load_tox21()
        train_X, train_y, train_w = train.X, train.y, train.w
        valid_X, valid_y, valid_w = valid.X, valid.y, valid.w
        test_X, test_y, test_w = test.X, test.y, test.w

        # Remove extra tasks
        train_y = train_y[:, 0]
        valid_y = valid_y[:, 0]
        test_y = test_y[:, 0]
        train_w = train_w[:, 0]
        valid_w = valid_w[:, 0]
        test_w = test_w[:, 0]

        # Generate tensorflow graph
        with tf.name_scope("placeholders"):
          x = tf.placeholder(tf.float32, (None, d))
          y = tf.placeholder(tf.float32, (None,))
          w = tf.placeholder(tf.float32, (None,))
          keep_prob = tf.placeholder(tf.float32)
        for layer in range(n_layers):
          print("present layer is ", layer)
          with tf.name_scope("layer-%d" % layer):
            W = tf.Variable(tf.random_normal((d, n_hidden)))
            b = tf.Variable(tf.random_normal((1, n_hidden)))
            print("x_hidden shape {} and W shape {}".format(x.shape, W.shape))
            x_hidden = tf.nn.relu(tf.matmul(x, W) + b)
            # Apply dropout
            x_hidden = tf.nn.dropout(x_hidden, keep_prob)
            x = x_hidden
            d = n_hidden
        with tf.name_scope("output"):
          W = tf.Variable(tf.random_normal((n_hidden, 1)))
          b = tf.Variable(tf.random_normal((1,1)))
          print("output W shape {} and x_hidden shape {} ".format(W.shape, x_hidden.shape))
          y_logit = tf.matmul(x_hidden, W) + b
          # the sigmoid gives the class probability of 1
          y_one_prob = tf.sigmoid(y_logit)
          # Rounding P(y=1) will give the correct prediction.
          y_pred = tf.round(y_one_prob)
          print("y pred shape {}".format(y_pred.shape))
        with tf.name_scope("loss"):
          # Compute the cross-entropy term for each datapoint
          y_expand = tf.expand_dims(y, 1)
          print("y expand shape {} ".format(y_expand.shape))
          entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=y_logit, labels=y_expand)
          print("entropy  shape {} ".format(entropy.shape))
          # Multiply by weights
          if weight_positives:
            w_expand = tf.expand_dims(w, 1)
            entropy = w_expand * entropy
            print("entropy weight postives  shape {} ".format(entropy.shape))
          # Sum all contributions
          l = tf.reduce_sum(entropy)

        with tf.name_scope("optim"):
          train_op = tf.train.AdamOptimizer(learning_rate).minimize(l)

        with tf.name_scope("summaries"):
          tf.summary.scalar("loss", l)
          merged = tf.summary.merge_all()

        #hyperparam_str = "d-%d-hidden-%d-lr-%f-n_epochs-%d-batch_size-%d-weight_pos-%s" % (
        #    d, n_hidden, learning_rate, n_epochs, batch_size, str(weight_positives))
        #train_writer = tf.summary.FileWriter('/tmp/fcnet-func-' + hyperparam_str,
        #                                     tf.get_default_graph())
        N = train_X.shape[0]
        with tf.Session() as sess:
          sess.run(tf.global_variables_initializer())
          step = 0
          for epoch in range(n_epochs):
            pos = 0
            while pos < N:
              batch_X = train_X[pos:pos+batch_size]
              batch_y = train_y[pos:pos+batch_size]
              batch_w = train_w[pos:pos+batch_size]
              feed_dict = {x: batch_X, y: batch_y, w: batch_w, keep_prob: dropout_prob}
              _, summary, loss = sess.run([train_op, merged, l], feed_dict=feed_dict)
              #print("epoch %d, step %d, loss: %f" % (epoch, step, loss))
              train_writer.add_summary(summary, step)

              step += 1
              pos += batch_size

          # Make Predictions (set keep_prob to 1.0 for predictions)
          valid_y_pred = sess.run(y_pred, feed_dict={x: valid_X, keep_prob: 1.0})

        weighted_score = accuracy_score(valid_y, valid_y_pred, sample_weight=valid_w)
        print("Valid Weighted Classification Accuracy: %f" % weighted_score)
      return weighted_score

    if __name__ == "__main__":
      score = eval_tox21_hyperparams()