TensorFlow入门简单操作(一)

安装TensorFlow:pip install tensorflow==1.14 -i https://pypi.tuna.tsinghua.edu.cn/simple

测试运行环境

import tensorflow as tf   # tensorflow2.0版本中的确没有Session这个属性。不能再使用import tensorflow as tf
hello = tf.constant('HELLO WORLD') # hello是一个操作对象(operation,简称op),op必须在tf平台下执行,才能产生结果
sess = tf.Session() # 定义一个执行对象
print(sess.run(hello))  # 指定在tf平台上执行hello这个op
sess.close()`

张量相加

import tensorflow as tf   # tensorflow2.0版本中的确没有Session这个属性。不能再使用import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'   # 调增警告级别
a = tf.constant(5.0) # 定义常量a
b = tf.constant(1.0) # 定义常量b
c = tf.add(a,b)
with tf.Session() as sess:
    print(sess.run(c))  # 执行计算

查看图对象

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

a = tf.constant(5.0) # 定义常量5.0
b = tf.constant(1.0) # 定义常量1.0
c = tf.add(a,b)# op,执行两个张量相加
graph = tf.get_default_graph()  # 获取缺省图
print(graph)
with tf.Session() as sess: # 不用考虑关闭
    print(sess.run(c))  # 执行计算
    print(a.graph)  # 通过tensor获取graph对象
    print(c.graph)  # 通过op获取graph对象
    print(sess.graph)  # 通过session获取graph对象

指定执行某个图

# 创建多个图,指定图运行
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # 调整警告级别
# a,b,c三个op存放于default_graph中

a = tf.constant(5.0)  # 定义常量a
b = tf.constant(1.0)  # 定义常量a
c = tf.add(a, b) # op,执行两个张量相加

# graph = tf.get_default_graph()  # 获取缺省图
# print(graph)
graph2 = tf.Graph()  #定义新的graph
print(graph2)
with graph2.as_default(): # 在指定图上创建op(向新的graph中添加op)
    d = tf.constant(11.0)

with tf.Session(graph=graph2) as sess:
    print(sess.run(d))  # 执行计算
    # print(sess.run(c))  # 报错

张量形状改变

# 张量形状
# 静态形状:初始形状,存储数据
#            一旦固定,不能修改
#              设置静态形状时不能跨阶
# 动态形状:运算过程中的形状
#          reshape函数,返回一个新张量
#          可以多次修改、跨阶修改,元素总数量保持一致

import tensorflow as tf
pld = tf.placeholder(tf.float32,[None,3])
print(pld)

#静态形状
pld.set_shape([4,3]) # ok
print(pld)
# pld.set_shape([3, 3]) #error,静态形状一旦固定就不能再设置静态形状

#动态形状
new_pld = tf.reshape(pld,[1,12])
print(new_pld)

# new_pld = tf.reshape(pld, [2, 4]) # error,元素的数量不匹配

with tf.Session() as sess:
    pass

张量的数学计算(重要)

# 数学计算示例
import tensorflow as tf

x = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
y = tf.constant([[4, 3], [3, 2]], dtype=tf.float32)

x_add_y = tf.add(x, y)  # 张量相加
x_mul_y = tf.matmul(x, y)  # 张量相乘
log_x = tf.log(x)  # log(x)

# reduce_sum: 此函数计算一个张量的各个维度上元素的总和
x_sum_1 = tf.reduce_sum(x, axis=[1]) #0-列方向 1-行方向

# segment_sum: 沿张量的片段计算总和
# 函数返回的是一个Tensor,它与data有相同的类型,与data具有相同的形状
# 但大小为 k(段的数目)的维度0除外
data = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=tf.float32)
segment_ids = tf.constant([0, 0, 0, 1, 1, 2, 2, 2, 2, 2], dtype=tf.int32)
x_seg_sum = tf.segment_sum(data, segment_ids)  # [6, 9, 40]

with tf.Session() as sess:
    print(x_add_y.eval())
    print(x_mul_y.eval())
    print(x_mul_y.eval())
    print(log_x.eval())
    print(x_sum_1.eval())
    print(x_seg_sum.eval())

变量使用实例

# 变量OP示例
import tensorflow as tf
# 创建普通张量
a = tf.constant([1, 2, 3, 4, 5])
# 创建变量
var = tf.Variable(tf.random_normal([2, 3], mean=0.0, stddev=1.0),
                  name="variable")

# 变量必须显式初始化, 这里定义的是初始化操作,并没有运行
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run([a, var]))

可视化

# 变量OP示例
import tensorflow as tf
''' 变量OP
1. 变量OP能够持久化保存,普通张量则不可
2. 当定义一个变量OP时,在会话中进行初始化
3. name参数:在tensorboard使用的时候显示名字,可以让相同的OP进行区分
'''
# 创建普通张量
a = tf.constant([1, 2, 3, 4, 5])
# 创建变量
var = tf.Variable(tf.random_normal([2, 3], mean=0.0, stddev=1.0),
                  name="variable")

b = tf.constant(3.0, name="a")
c = tf.constant(4.0, name="b")
d = tf.add(b, c, name="add")

# 变量必须显式初始化, 这里定义的是初始化操作,并没有运行
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
    # 将程序图结构写入事件文件
    fw = tf.summary.FileWriter("../summary/", graph=sess.graph)
    print(sess.run([a, var]))

第二步:启动tensorborad

tensorboard  --logdir="PycharmProjects/tensorflow_study/summary/"# 绝对路径,自己创建的一个文件夹

第三步:访问tensorborad主页

http://127.0.0.1:6006

在这里插入图片描述

实现线性回归(模型保存与加载)

# 模型保存示例
import tensorflow as tf
import os

# 第一步:创建数据
x = tf.random_normal([100, 1], mean=1.75, stddev=0.5, name="x_data")
y_true = tf.matmul(x, [[2.0]]) + 5.0  # 矩阵相乘必须是二维的

# 第二步:建立线性回归模型
# 建立模型时,随机建立权重、偏置 y = wx + b
# 权重需要不断更新,所以必须是变量类型. trainable指定该变量是否能随梯度下降一起变化
weight = tf.Variable(tf.random_normal([1, 1], name="w"),
                     trainable=True)  # 训练过程中值是否允许变化
bias = tf.Variable(0.0, name="b", trainable=True)  # 偏置
y_predict = tf.matmul(x, weight) + bias  # 计算 wx + b

# # 第三步:求损失函数,误差(均方差)
loss = tf.reduce_mean(tf.square(y_true - y_predict))

# # 第四步:使用梯度下降法优化损失
# 学习率是比价敏感的参数,过小会导致收敛慢,过大可能导致梯度爆炸
train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

# 收集损失值
tf.summary.scalar("losses", loss)
merged = tf.summary.merge_all() #将所有的摘要信息保存到磁盘

init_op = tf.global_variables_initializer()

saver = tf.train.Saver() #实例化Saver
with tf.Session() as sess:  # 通过Session运行op
    sess.run(init_op)
    print("weight:", weight.eval(), " bias:", bias.eval())     # 打印初始权重、偏移值
    fw = tf.summary.FileWriter("../summary/", graph=sess.graph) # 指定事件文件
    # 训练之前,加载之前训练的模型,覆盖之前的参数
    if os.path.exists("../model/linear_model/checkpoint"):
        saver.restore(sess, "../model/linear_model/")

    for i in range(500):  # 循环执行训练
        sess.run(train_op)  # 执行训练
        summary = sess.run(merged) # 运行合并后的tensor
        fw.add_summary(summary, i)
        print(i, ":", i, "weight:", weight.eval(), " bias:", bias.eval())

    saver.save(sess, "../model/linear_model/")

tensorboard --logdir报错 Not a TBLoader or TBPlugin subclass

1.pip list
2.卸载:pip uninstall tensorboard-plugin-wit

调用run方法时,可能会出现的错误和原因:
1.RuntimeError:Session处于无效(或关闭)
2.TypeError:fetches或feed_dict的键是不合适的值
3.ValueError:fetches或feed_dict的键无效或引用的值不存在

tensorflow的官方文档写的很好,要养成多看注释文档的好习惯

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值