美文网首页
[莫烦python笔记]Tensorflow

[莫烦python笔记]Tensorflow

作者: jenye_ | 来源:发表于2019-04-30 23:47 被阅读0次

    待更新


    第一个例子

    import tensorflow as tf
    import numpy as np
    
    # create data
    x_data = np.random.rand(100).astype(np.float32)
    y_data = x_data*0.1 + 0.3
    
    Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
    biases = tf.Variable(tf.zeros([1]))
    
    y = Weights*x_data + biases
    loss = tf.reduce_mean(tf.square(y-y_data))
    
    optimizer = tf.train.GradientDescentOptimizer(0.5)
    train = optimizer.minimize(loss)
    
    # init = tf.initialize_all_variables() # tf 马上就要废弃这种写法
    init = tf.global_variables_initializer()  # 替换成这样就好
    
    sess = tf.Session()
    sess.run(init)          # Very important
    
    for step in range(201):
        sess.run(train)
        if step % 20 == 0:
            print(step, sess.run(Weights), sess.run(biases))
    

    Session 控制

    import tensorflow as tf
    
    matrix1 = tf.constant([[3, 3]])
    matrix2 = tf.constant([[2],
                           [2]])
    product = tf.matmul(matrix1,matrix2)  # matrix multipy np.dot(m1,m2)
    
    #mehtod1
    # sess = tf.Session()
    # result = sess.run(product)
    # print(result)
    # sess.close()
    
    # [[12]]
    
    #method 2
    with tf.Session() as sess:
        result2 = sess.run(product)
        print(result2)
    
    # [[12]]
    
    

    变量

    import numpy as np
    import tensorflow as tf
    state = tf.Variable(0,name='counter')
    one = tf.constant(1)
    
    new_value = tf.add(state,one)
    update = tf.assign(state,new_value)
    
    init = tf.global_variables_initializer() # must have if define variable
    
    with tf.Session() as sess:
        sess.run(init)
        for _ in range(3):
            sess.run(update)
            print(sess.run(state))
    

    相关文章

      网友评论

          本文标题:[莫烦python笔记]Tensorflow

          本文链接:https://www.haomeiwen.com/subject/wlobnqtx.html