DL1-tensorflow之基础操作

import tensorflow as tf

创建变量和执行

w = tf.Variable([[0.5, 2.0]])   #行向量
x = tf.Variable([[2.0], [1.0]]) #列向量
y = tf.matmul(w, x)

执行之前必须对变量进行初始化, 创建Session()

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(y.eval())
[[3.]]

一些常见的初始化操作

a = tf.zeros([2,3], float)
b = tf.ones([3,4], float)
c = tf.zeros_like(a)
d = tf.ones_like(b)
e = tf.constant([1,2,3,4,5])
f = tf.constant(-2, shape=[2,3])
g = tf.linspace(4.0,6.0,3, name='linspace')
h = tf.range(1,10,3)

shuffle洗牌

#生成2行3列符合均值为-1,且方差为4的正态分布数据
norm = tf.random_normal([2,3],mean=-1, stddev=9)

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

sess = tf.Session()
print(sess.run(norm))
print(sess.run(shuffle))
[[ 5.744781   4.8351593 -3.1881056]
 [-9.752258   8.690398  -8.590118 ]]
[[3 4]
 [5 6]
 [1 2]]

赋值操作

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))
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
0
1
2
3

数据保存 tf.train.Saver()

w = tf.Variable([[0.5, 2.0]])   #行向量
x = tf.Variable([[2.0], [1.0]]) #列向量
y = tf.matmul(w, x)

init_op = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(init_op)
    # 模型中进行一些操作,然后保存数据到磁盘
    save_path = saver.save(sess, 'F://PythonAI//DeepLearning')
    print ('Model saved in file:', save_path)
Model saved in file: F://PythonAI//DeepLearning
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.]]
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)
with tf.Session() as sess:
    print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))
[array([14.], dtype=float32)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值