【问题标题】:Tensorflow 1.3 tutorial learning Tensorflow 2.0Tensorflow 1.3教程学习Tensorflow 2.0
【发布时间】:2019-11-03 18:35:09
【问题描述】:

我是 tensorflow 新手,正在尝试使用新版本 2.0。我了解 1.3 教程中发生的情况,但很多东西都被贬低了。如果有人可以让下面的代码与 2.0 版本一起使用,它将帮助我理解如何将教程中所做的转换为 tensorflow 上的新版本。

由于掠夺,所有被注释掉的东西都不起作用。 我不想使用任何低于 2.0 的 tensorflow 版本

n_features = 10
n_dense_neurons = 3

#x = tf.placeholder(tf.float32,(None, n_features))
W = tf.Variable(tf.random.normal([n_features,n_dense_neurons]))
b = tf.Variable(tf.ones([n_dense_neurons]))

#xW = tf.matmul(x,W)
#z = tf.add(xW,b)
#a = tf.sigmoid(z)

#init = tf.global_variables_initializer()

#with tf.Session() as sess:
    #sess.run(init)
    #layer_out = sess.run(a,feed_dict={x:np.random.random([1,n_features])}) 
#print(layer_out)   

【问题讨论】:

    标签: tensorflow2.0


    【解决方案1】:

    这很简单:忘记tf.Session 对象和tf.placeholder,只需逐行执行代码,它就可以工作! (这是 Eager Execution,这是 TensorFlow 2.0 中的默认设置)。

    因此,您不必声明占位符,而只需使用输入值(我添加了一个 tf.cast 操作,因为 np.random.random 返回一个双精度值,但 TensorFlow MatMul 操作适用于 tf.float32 值) .

    import numpy as np
    import tensorflow as tf
    
    n_features = 10
    n_dense_neurons = 3
    
    x = tf.cast(np.random.random([1,n_features]), tf.float32)
    W = tf.Variable(tf.random.normal([n_features,n_dense_neurons]))
    b = tf.Variable(tf.ones([n_dense_neurons]))
    
    xW = tf.matmul(x,W)
    z = tf.add(xW,b)
    a = tf.sigmoid(z)
    print(a)
    

    【讨论】:

      猜你喜欢
      • 2017-10-02
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 2018-10-08
      • 2017-03-02
      相关资源
      最近更新 更多