数据流图、张量及数据类型
数据流图
import tensorflow as tf
# 定义数据流
a = tf.constant(2, name="input_a")
b = tf.constant(5, name="input_b")
c = tf.add(a,b,name="c")
d = tf.constant(8, name="input_d")
e = tf.multiply(c,d,name="e")
# 通过session告诉c++运行数据流图
sess = tf.Session()
out = sess.run(e)
print(out)
# 通过tensorboard查看数据流图
writer = tf.summary.FileWriter("./log",sess.graph)
#sess.graph是一个默认属性,每一个session都有一个graph属性。
通过网页查看数据流图:
(tensorflow1.13-gpu) D:\Code\PycharmProjects\Rcommendation_realize\tensorflow1.13_learn\begin>tensorboard --logdir=./log
然后在浏览器打开localhost:6006
张量
可以看成n维的矩阵
输入的都是一个批次一个批次的数据 [n张图片,高,宽,rgb]
tensorflow支持的数据类型:
tf.float32, tf.int32, tf.bool, tf.string
经常用numpy为tensorflow提供数据源
session
feed_dict可以覆盖数据流图中tensor的值。用途:train的时候输入一个数据,test通过feed_dict改变
a = tf.constant(2)
b = tf.constant(3)
c = tf.add(a, b)
sess = tf.Session()
out = sess.run(c,feed_dict={
a:20}) # feed_dict可以覆盖数据流图中tensor的值。用途:train的时候输入一个数据,test通过feed_dict改变
print(out)
sess.close()
占位符:先定义好,运行时用feed_dict填充
a = tf.placeholder(tf.float32,shape=[3],name="shuru")
b = tf.reduce_prod(a) # 对a做累乘
c = tf.reduce_sum(a) # 累加
d = tf.add(b,c)
with tf.Session() as sess:
out = sess.run(d, feed_dict={
a:[2,3,4]})
print(out)
变量:后续需要不断更新的,一般用于权重和偏置
# 变量
weight = tf.Variable(2, name="quanzhong")
weight = tf.Variable(tf.random_normal([128,10]), name="quanzhong")
weight = tf.Variable(tf.truncated_normal([128,10]), name="quanzhong") # 更加规整,不会偏离中心值
bias = tf.Variable(tf.zeros([10]))
# 运行时必需要先初始化变量
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
线性回归
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
data_x = np.linspace(0,10,30) # 从0到10之间取30个数字
data_y = data_x*3 +7 + np.random.normal(0,1,30)
print(data_x)
print(data_y)
# plt.scatter(data_x, data_y)
# plt.show()
# 1、定义参数
# 2、输入训练参数
# 3、执行推断
# 4、计算损失
# 5、训练模型
# 6、评估
w = tf.Variable(1., name="quanzhong") # 1会被识别为int32,1.会被识别为float32
b = tf.Variable(0., name="pianzhi")
x = tf.placeholder(tf.float32, shape=None) # None:任意形状。[None]:一维,任意个。[None,3]:任意行,3列
y = tf.placeholder(tf.float32, shape=[None])
pred = tf.multiply(x,w) + b # 预测值
loss = tf.reduce_sum(tf.squared_difference(pred, y)) # squared_difference计算预测值pred和实际值y的差平方,reduce_sum计算总和并降成标量
# 梯度下降
learn_rate = 0.0001
train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(loss) # 定义学习率,最小化损失值。
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(10000):
sess.run(train_step, feed_dict={
x:data_x, y:data_y})
if i % 1000 == 0:
print(sess.run([loss,w,b],feed_dict

最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



