tensorflow基础

点击这里->这有tensorflow方法api

导入TensorFlow模块,查看下当前模块的版本

import tensorflow as tf

print(tf.__version__)

# 创建名为hello_constant的TensorFlow对象
hello_constant = tf.constant('Hello World!')

tensorflow是一种图计算框架,所有的计算操作被声明为图(graph)中的节点(Node)
即使只是声明一个变量或者常量,也并不执行实际的操作,而是向图中增加节点
我们来看一上前面安装TensorFlow的时候的测试代码

with tf.Session() as sess:
    
    # 在session中运行tf.constant 操作
    output = sess.run(hello_constant)
    
    print(output)
Tensor

在 TensorFlow 中,数据不是以整数,浮点数或者字符串形式存在的。
这些值被封装在一个叫做 tensor 的对象中。
在 hello_constant = tf.constant(‘Hello World!’) 代码中, hello_constant是一个 0 维度的字符串 tensor。
tensors 还有很多不同大小:

# A 是一个0维的 int32 tensor
A = tf.constant(1234) 
# B 是一个1维的  int32 tensor
B = tf.constant([123,456,789]) 
 # C 是一个2维的  int32 tensor
C = tf.constant([ [123,456,789], [222,333,444] ])

with tf.Session() as sess:
    out_A = sess.run(A)
    out_B = sess.run(B)
    out_C = sess.run(C)
    
    print('\n', out_A, '\n', '----------', '\n', out_B, '\n', '----------', '\n', out_C)

================
1234 
 ---------- 
 [123 456 789] 
 ---------- 
 [[123 456 789]
 [222 333 444]]

TensorFlow 的 api 构建在 computational graph(计算图) 的概念上,它是一种对数学运算过程进行可视化的一种方法。让我们把你刚才运行的 TensorFlow 的代码变成一个图:
一个 “TensorFlow Session” 是用来运行图的环境。这个 session 负责分配 GPU(s) 和/或 CPU(s) 包括远程计算机的运算。让我们看看怎么使用它:

with tf.Session() as sess:
    output = sess.run(hello_constant)
    print(output)
=============
b'Hello World!'   

constant运算
我们先计算一个线性函数,y=wx+b

w = tf.constant([[1., 2.]])
x = tf.constant([[3.], [4.]])
b = tf.constant(.9)

y = tf.add(tf.matmul(w, x), b)

# 变量必须要初始化后才能使用
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(y.eval())
================
[[11.9]]    

计算图中所有的数据均以tensor来存储和表达。 tensor是一个高阶张量,二阶张量为矩阵,一阶张量为向量,0阶张量为一个数(标量)。

a = tf.constant(0, name='num_B')
b = tf.constant(1)
c = tf.constant([[1, 2],[3, 4]])
print(a)
print(b)
print(c)
===============
Tensor("num_B:0", shape=(), dtype=int32)
Tensor("Const_11:0", shape=(), dtype=int32)
Tensor("Const_12:0", shape=(2, 2), dtype=int32)

其他计算操作也同样如此。 tensorflow中的大部分操作都需要通过tf.xxxxx的方式进行调用。

c = tf.add(a,b)
print(c)
==========
Tensor("Add_1:0", shape=(), dtype=int32)

从加法开始, tf.add() 完成的工作与你期望的一样。它把两个数字,两个 tensor,返回他们的和。减法和乘法同样也是直接调用对应的接口函数

x = tf.subtract(10, 4) # 6
y = tf.multiply(2, 5)  # 10
mat_a = tf.constant([[1, 1, 1], [3, 3, 3]])
mat_b = tf.constant([[2, 2, 2],[5, 5, 5]], name='mat_b')

mul_a_b = mat_a * mat_b
tf_mul_a_b = tf.multiply(mat_a, mat_b)
tf_matmul_a_b = tf.matmul(mat_a, tf.transpose(mat_b), name='matmul_with_ab')

print(mul_a_b)
print(tf_mul_a_b)
print(tf_matmul_a_b)

with tf.Session() as sess:
    mul_value, tf_mul_value, tf_matmul_value = sess.run([mul_a_b, tf_mul_a_b, tf_matmul_a_b])
    
print(mul_value)
print(tf_mul_value)
print(tf_matmul_value)
===============
Tensor("mul_1:0", shape=(2, 3), dtype=int32)
Tensor("Mul_2:0", shape=(2, 3), dtype=int32)
Tensor("matmul_with_ab:0", shape=(2, 2), dtype=int32)

[[ 2  2  2]
 [15 15 15]]
[[ 2  2  2]
 [15 15 15]]
[[ 6 15]
 [18 45]]

我们再举几个具体的实例来看看

a = tf.constant(2)
b = tf.constant(3)
x = tf.add(a, b)
with tf.Session() as sess:
    with tf.device("/gpu:0"):
        print(sess.run(x))
===========
5        

设备用字符串进行标识. 目前支持的设备包括:
“/cpu:0”: 机器的 CPU.
“/gpu:0”: 机器的第一个 GPU, 如果有的话.
“/gpu:1”: 机器的第二个 GPU, 以此类推.

a = tf.constant([2, 2], name='a')
b = tf.constant([[0, 1], [2, 3]], name='b')
x = tf.multiply(a, b, name='dot_product')
with tf.Session() as sess:
	print(sess.run(x))
===============
[[0 2]
 [4 6]]	
a = tf.constant([[2, 2],[1, 4]], name='a')
b = tf.constant([[0, 1], [2, 3]], name='b')
x = tf.multiply(a, b, name='dot_product')
y = tf.matmul(a, b, name='mat_mul')
with tf.Session() as sess:
	print(sess.run(x))
	print(sess.run(y))
===========
[[ 0  2]
 [ 2 12]]
[[ 4  8]
 [ 8 13]]
各式各样的常量
x = tf.zeros([2, 3], tf.int32)
y = tf.zeros_like(x, optimize=True)

print(y)

with tf.Session() as sess:
    print(sess.run(y))
==========
Tensor("zeros_like:0", shape=(2, 3), dtype=int32)


[[0 0 0]
 [0 0 0]]
t_0 = 19 
x = tf.zeros_like(t_0) # ==> 0
y = tf.ones_like(t_0) # ==> 1

with tf.Session() as sess:
    print(sess.run([x]))
    print(sess.run([y]))

=========
[0]
[1]
变量
# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")

# 创建一个 op, 其作用是使 state 增加 1

one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value) # 赋值

# 启动图后, 变量必须先经过`初始化` (init) op 初始化,
# 首先必须增加一个`初始化` op 到图中.
init = tf.global_variables_initializer()

# 启动图, 运行 op
with tf.Session() as sess:
    # 运行 'init' 
    sess.run(init)
    # 打印 'state' 的初始值
    print(sess.run(state))
    # 运行 op, 更新 'state', 并打印 'state'
    for _ in range(7):
        sess.run(update)
        print(sess.run(state))
============
0
1
2
3
4
5
6
7       

例如:求导也是一个运算

x = tf.Variable(2.0)
y = 2.0 * (x ** 3)
z = 3.0 + y ** 2
grad_z = tf.gradients(z, y) # 返回 sum(dz/dy)	 但是要注意,z,y都不可以是变量(Variable)
with tf.Session() as sess:
    sess.run(x.initializer)
    print(sess.run(grad_z))
===========    
[32.0]    

一次性初始化所有变量

my_var = tf.Variable(2, name="my_var") 

my_var_times_two = my_var.assign(2 * my_var)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(my_var_times_two))
    print(sess.run(my_var_times_two))
    print(sess.run(my_var_times_two))
==============
4
8
16

在前面我们都是采用,先赋值再计算的方法,但是在我们的工作过程中,我会遇到先定义变量,后赋值的情况。 如果你想用一个非常量 non-constant 该怎么办?这就是 tf.placeholder() 和 feed_dict 派上用场的时候了。我们来看看如何向 TensorFlow 传输数据的基本知识。
tf.placeholder()
当你你不能把数据赋值到 x 在把它传给 TensorFlow。因为后面你需要你的 TensorFlow 模型对不同的数据集采取不同的参数。这时你需要 tf.placeholder()!
数据经过 tf.session.run() 函数得到的值,由 tf.placeholder() 返回成一个 tensor,这样你可以在 session 开始跑之前,设置输入。
Session’s feed_dict 功能

x = tf.placeholder(tf.string)

with tf.Session() as sess:
    out = sess.run(x, feed_dict={x: 'Hello World'})
    print(out)
==========
Hello World

用 tf.session.run() 里 feed_dict 参数设置占位 tensor。上面的例子显示 tensor x 被设置成字符串 “Hello, world”。当然你也可以用 feed_dict 设置多个 tensor。
placeholder是一个占位符,它通常代表着从外界输入的值。 其中None代表着尚不确定的维度。

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)]    
把numpy转换成Tensor
import numpy as np
a = np.zeros((3,3))
print(a)
print('----------------')
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
     print(sess.run(ta))
=================     
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
----------------
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]     
类型转换

为了让特定运算能运行,有时会对类型进行转换。例如,你尝试下列代码,会报错:

tf.subtract(tf.constant(2.0),tf.constant(1))
报错!

只是因为常量 1 是整数,但是常量 2.0 是浮点数 subtract 需要他们能相符。
在这种情况下,你可以让数据都是同一类型,不仅数据类型要对应而且类型大小也要对应,比如int32对应int32,或者强制转换一个值到另一个类型。这里,我们可以把 2.0 转换成整数再相减,这样就能得出正确的结果:

number = tf.subtract(tf.cast(tf.constant(2.0), tf.int32), tf.constant(1))   # tf.cast将张量转换为新类型。
with tf.Session() as sess:
    print(sess.run(number))

tensorboard 了解图结构/可视化利器

import tensorflow as tf
a = tf.constant(2, name='A')
b = tf.constant(3, name='B')
x = tf.add(a,b, name='addAB')
with tf.Session() as sess:
    print(sess.run(x))
    #写到日志文件里
    writer = tf.summary.FileWriter('logs/add_test', sess.graph)
    #关闭writer
writer.close()

===================
启动 TensorBoard
在命令端运行:tensorboard --logdir="./logs" --port 7007
切记:路径不要有中文!!!!不要有中文!!!!
然后打开Google浏览器访问:http://localhost:7007/ 不行的话就粘贴命令行出现的地址到浏览器
TensorFlow实现线性回归
import numpy as np
import os
import tensorflow as tf
import matplotlib.pyplot as plt

#设置生成的图像尺寸和去除警告
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'	
plt.rcParams["figure.figsize"] = (14, 8)  # 生成的图像尺寸

n_observations = 100
xs = np.linspace(-3, 3, n_observations)
ys = 0.8*xs + 0.1 + np.random.uniform(-0.5, 0.5, n_observations)
plt.scatter(xs, ys)
plt.show()

#准备好placeholder
X = tf.placeholder(tf.float32, name='X')
Y = tf.placeholder(tf.float32, name='Y')

#初始化参数/权重
W = tf.Variable(tf.random_normal([1]), name='weight')
tf.summary.histogram('weight', W)
b = tf.Variable(tf.random_normal([1]), name='bias')
tf.summary.histogram('bias', b)

#计算预测结果
Y_pred = tf.add(tf.multiply(X, W), b)

#计算损失值函数
loss = tf.square(Y - Y_pred, name='loss')
tf.summary.scalar('loss', tf.reshape(loss, []))

#初始化optimizer
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

#指定迭代次数,并在session里执行graph
n_samples = xs.shape[0]
init = tf.global_variables_initializer()
with tf.Session() as sess:
    # 记得初始化所有变量
    sess.run(init)
    merged = tf.summary.merge_all()
    writer = tf.summary.FileWriter('./logs/linear_regression', sess.graph)

    # 训练模型
    for i in range(50):
        total_loss = 0
        for x, y in zip(xs, ys):
            # 通过feed_dic把数据灌进去
            _, loss_value, merged_summary = sess.run([optimizer, loss, merged], feed_dict={X: x, Y: y})
            total_loss += loss_value
        if i % 5 == 0:
            print('Epoch {0}: {1}'.format(i, total_loss / n_samples))
            writer.add_summary(merged_summary, i)

    # 关闭writer
    writer.close()

    # 取出w和b的值
    W, b = sess.run([W, b])

print(W, b)
print("W:"+str(W[0]))
print("b:"+str(b[0]))
==========
Epoch 0: [0.9697559]
Epoch 5: [0.08127738]
Epoch 10: [0.08127795]
Epoch 15: [0.08127795]
Epoch 20: [0.08127795]
Epoch 25: [0.08127795]
Epoch 30: [0.08127795]
Epoch 35: [0.08127795]
Epoch 40: [0.08127795]
Epoch 45: [0.08127795]    



[0.7579985] [0.1127253]
W:0.7579985
b:0.1127253
保存神经网络参数
import tensorflow as tf

# 保存神经网络参数
def save_para():
    # 定义权重参数
    W = tf.Variable([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name='weights')
    # 定义偏置参数
    b = tf.Variable([[1, 2, 3]], dtype=tf.float32, name='biases')
    # 参数初始化
    init = tf.global_variables_initializer()
    # 定义保存参数的saver
    saver = tf.train.Saver()

    with tf.Session() as sess:
        sess.run(init)
        # 保存session中的数据
        save_path = saver.save(sess, './save_net.ckpt')
        # 输出保存路径
        print('Save to path: ', save_path)


save_para()

读取神经网络参数
def restore_pare():
    W = tf.Variable(np.arange(6).reshape((2,3)),dtype=tf.float32,name='weights')
    b = tf.Variable(np.arange(3).reshape((1,3)),dtype=tf.float32,name='biases')
    saver = tf.train.Saver()
    with tf.Session() as sess:
        save_path = saver.restore(sess,'saver/save_net.ckpt')
        print('weights:',sess.run(W))
        print('biases:',sess.run(b))
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值