tensorflow入门案例及解析

本文详细介绍TensorFlow中的基本操作,包括矩阵运算、变量定义、初始化、占位符使用、多操作并行执行、神经网络构建及训练等核心内容,适合初学者入门。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

案例一:

m1 = tf.constant([[3, 3]])  # 定义一个一行两列的矩阵,op1
m2 = tf.constant([[2], [3]])  # 定义一个两行一列的矩阵,op2
product = tf.matmul(m1, m2)  # 创建一个矩阵乘法,把m1和m2传入,op3

# 定义一个会话,启动默认图 # 方法一
sess = tf.Session()
# 调用sess的run方法来执行矩阵乘法op
# run(product)触发了图中3个op
result = sess.run(product)
print(result)
sess.close()

tf.constant函数参考:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-jabh2d30.html
tf.matmul函数参考:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-l5x72feg.html
定义三个opration,然后建立一个会话启动默认图,再通过run即可得到计算结果,也可以通过with语句,这样可以省去sess.close()操作。

# 不需要执行关闭的操作 # 方法二
with tf.Session() as sess:
    result = sess.run(product)
    print(result)

案例二:

x = tf.Variable([1, 2])  # 定义一个变量 op1
a = tf.constant([3, 3])  # 定义一个常数 op2
# 增加一个减去op
sub = tf.subtract(x, a)  # 创建一个减法操作 op3
# 增加一个加法op
add = tf.add(x, sub)   # 创建一个加法操作  op4

init = tf.global_variables_initializer()  # 全局变量初始化 op5

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(sub))
    print(sess.run(add))

tf.Variable参考链接:
https://www.jianshu.com/p/2b9e475391ab
当有定义变量时, 需要使用tf.global_variables_initializer()进行全局变量初始化。在建立的会话中,要先运行init这个操作op5, 然后分别运行op3和op4。

案例三:

# 创建一个变量初始化为0
state = tf.Variable(0, name='counter')  #op1
# 创建一个op 
new_value = tf.add(state, 1)   # op2
# 赋值op
update = tf.assign(state, new_value)  # op3
# 初始化变量
init = tf.global_variables_initializer()  # op4

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(state))
    for x in range(5):
        sess.run(update)
        print(sess.run(state))

tf.assign()赋值函数用法参照链接:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-b4x72chd.html

案例四

# Fetch  ##同时运行多个op
input1 = tf.constant(3.0)  #op1
input2 = tf.constant(2.0)  #op2
input3 = tf.constant(5.0)  #op3

add = tf.add(input2, input3)   #op4   
mul = tf.multiply(input1, add)  #op5

with tf.Session() as sess:
    result = sess.run([add, mul])  # [add, mul]顺序无所谓
    print(result)

sess.run()函数中同时运行多个操作,这里顺序不影响结果。

案例五

# 创建占位符
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)

with tf.Session() as sess:
    # feed的数据以字典的形式传入
    print(sess.run(output, feed_dict={input1: [8.], input2: [2.]}))

tf.placeholder()函数参照链接:
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-w7yt2fwc.html

案例六

# 用numpy生成100个随机点
x_data = np.random.rand(100)
y_data = x_data * 0.1 + 0.2

# 构建一个线性模型 
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k * x_data + b
# 二次代价函数
loss = tf.reduce_mean(tf.square(y_data - y))  # 误差的平方的平均值作为cost function
# 定义一个梯度下降法来进行训练的优化器
opt = tf.train.GradientDescentOptimizer(0.1)
# 定义一个最小化代价函数
train = opt.minimize(loss)
# 初始化变量
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for step in range(201):
        sess.run(train)
        if step % 20 == 0:
            print(sess.run([k, b]))

案例七

# 使用numpy生成200个随机点
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]  # [:, np.newaxis]生成200行一列的数据
noise = np.random.normal(0, 0.02, x_data.shape)
print(x_data.shape)
y_data = np.square(x_data) + noise  # y = x*x+noise

# 先定义两个placeholder
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])

# 定义两个神经网络中间层
Weights_L1 = tf.Variable(tf.random_normal([1, 10]))
biases_L1 = tf.Variable(tf.zeros([1, 10]))
Wx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)

# 定义神经网络输出层
Weights_L2 = tf.Variable(tf.random_normal([10, 1]))
biases_L2 = tf.Variable(tf.zeros([1, 1]))
Wx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

# 二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))
# 使用梯度下降法训练
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)  # 0.1是学习速率

with tf.Session() as sess:
    # 变量初始化
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step, feed_dict={x: x_data, y: y_data})
    # 获得预测值
    prediction_value = sess.run(prediction, feed_dict={x: x_data})
    # 画图
    plt.figure()
    plt.scatter(x_data, y_data)
    plt.plot(x_data, prediction_value, 'r-', lw=5)
    plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

象牙塔小明

您的鼓励是我最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值