Tensorflow简单计算操作

常数操作以及变量操作,操作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简单计算操作)