美文网首页
Tensorflow简单计算操作

Tensorflow简单计算操作

作者: 菜囧爱学习 | 来源:发表于2019-02-11 21:17 被阅读0次

    常数操作以及变量操作,操作cpu、gpu选择

    # -*- coding: utf-8 -*-
    """
    Created on Mon Feb 11 20:20:44 2019
    
    @author: Administrator
    TF矩阵操作,gpu/cpu选择
    """
    import tensorflow as tf
    #常数矩阵操作
    #def constant(value, dtype=None, shape=None, name="Const", verify_shape=False):
    with tf.device('/cpu:0'):
        sess = tf.Session()
        t3 = tf.constant([1,2,3,4],tf.float32,shape=[2,2])
        t4 = tf.constant([1,2],tf.float32,shape=[2,1])
        print("t3=",t3,"t4=",t4)
        print("t3*t4=",sess.run(tf.matmul(t3,t4)))    
        #变量矩阵操作
        def weight(shape):
            init=tf.random_normal(shape=shape,dtype=tf.float32)
            return tf.Variable(init)
        t1  = weight([3,2])
        t2 = weight([2,2])
        sess.run(tf.initialize_all_variables())
        print("t1*t2=",sess.run(tf.matmul(t1,t2)))                             
        
        
    with tf.device('/gpu:0'):
        sess = tf.Session()
        t3 = tf.constant([1,2,3,4],tf.float32,shape=[2,2])
        t4 = tf.constant([1,2],tf.float32,shape=[2,1])
        print("t3=",t3,"t4=",t4)
        print("t3*t4=",sess.run(tf.matmul(t3,t4)))    
        #变量矩阵操作
        def weight(shape):
            init=tf.random_normal(shape=shape,dtype=tf.float32)
            return tf.Variable(init)
        t1  = weight([3,2])
        t2 = weight([2,2])
        sess.run(tf.initialize_all_variables())
        print("t1*t2=",sess.run(tf.matmul(t1,t2)))      
    

    相关文章

      网友评论

          本文标题:Tensorflow简单计算操作

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