TensorFlow常用操作

本文介绍了使用TensorFlow进行张量操作的基本方法,包括初始化张量、循环操作、数据类型转换等核心技能,并提供了详细的代码示例。

  初始化数据:

# -*- coding: utf-8 -*-
import tensorflow as tf

a = tf.zeros([3, 4], tf.int32)
# [[0 0 0 0]
#  [0 0 0 0]
#  [0 0 0 0]]

b = tf.zeros_like(a) #按照a的结构
# [[0 0 0 0]
#  [0 0 0 0]
#  [0 0 0 0]]

c = tf.ones_like(a) #按照a的结构
# [[1 1 1 1]
#  [1 1 1 1]
#  [1 1 1 1]]

d = tf.constant([1, 2, 3, 4, 5, 6, 7])
# [1 2 3 4 5 6 7]

e = tf.constant(-1.0, shape=[2, 3])
# [[-1. -1. -1.]
#  [-1. -1. -1.]]

f = tf.linspace(10.0, 12.0, 3, name="linspace")
# [ 10.  11.  12.]

g = tf.range(start=3, limit=18, delta=3)
# [ 3  6  9 12 15]


norm = tf.random_normal([2, 3], mean=-1, stddev=4,seed=1) #高斯分布
# [[ -4.24527264   4.93839502  -0.73868251]
#  [-10.7708168   -0.60300636   1.36489725]]

c = tf.constant([[1, 2], [3, 4], [5, 6]]) #shuffle
shuff = tf.random_shuffle(c)


with tf.Session() as sess: 
    print (sess.run(g))

 

  循环打印:

# -*- coding: utf-8 -*-
import tensorflow as tf

state = tf.Variable(0) #初始化
new_value = tf.add(state, tf.constant(1)) #加一
update = tf.assign(state, new_value) #更新

with tf.Session() as sess: 
    sess.run(tf.global_variables_initializer()) #在会话里初始化全局变量
    print(sess.run(state))    #打印state
    for _ in range(3):
        sess.run(update)    #执行循环
        print(sess.run(state))  #打印state
        # 0
        # 1
        # 2
        # 3

 

  numpy转TensorFlow格式:

# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
    print(sess.run(ta))
# [[ 0.  0.  0.]
#  [ 0.  0.  0.]
#  [ 0.  0.  0.]]

 

转载于:https://www.cnblogs.com/itmorn/p/8158263.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值