tensorflow学习(一)

本文介绍TensorFlow 2.0的基本操作,包括常量、变量的创建,矩阵运算,以及使用会话执行计算图。演示了如何通过Fetch和Feed进行数据输入,最后通过两个实例展示了线性模型和神经网络的构建与训练过程。

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

tensorflow学习(一)

认识基本操作

由于是2.0版本的,所以每次需要调用1.0版本的,因为网上大部分程序还是1.0版本写的,还是必须要会1.0版本的

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

#创建一个常量
m1 = tf.compat.v1.constant([[3,3]])
m2 = tf.compat.v1.constant([[2],[3]])
#创建一个矩阵乘法
product = tf.compat.v1.matmul(m1,m2)
print(product)
out:
Tensor("MatMul_4:0", shape=(1, 1), dtype=int32)
#创建一个会话,启动默认图
sess = tf.compat.v1.Session()
#调用sess的run方法来执行矩阵乘法
#run(product)触发了图中的三个op
result = sess.run(product)
print(result)
sess.close()
out:
[[15]]
with tf.compat.v1.Session() as sess:
    #调用sess的run方法来执行矩阵乘法
    #run(product)触发了图中的三个op
    result = sess.run(product)
    print(result)
out:
[[15]]
#创建一个变量,需要先初始化
x = tf.compat.v1.Variable([1,2])
a = tf.compat.v1.constant([3,3])
#创建一个减法op
sub = tf.compat.v1.subtract(x,a)
#创建一个加法op
add = tf.compat.v1.add(x,sub)
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    sess.run(init)  #全局变量初始化
    result = sess.run(sub)
    print(sess.run(sub))
    print(sess.run(add))
out:
[-2 -1]
[-1  1]
#创建一个变量初始化为0
state = tf.compat.v1.Variable(0,name='counter')
#创建一个op,变量加一
new_value = tf.compat.v1.add(state,1)
#创建一个赋值op
update = tf.assign(state,new_value)
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    sess.run(init)  #全局变量初始化
    print(sess.run(state))
    for _ in range(5):
        sess.run(update)
        print(sess.run(state))
out:
0
1
2
3
4
5
#Fetch
input1 = tf.compat.v1.constant(3.0)
input2 = tf.compat.v1.constant(2.0)
input3 = tf.compat.v1.constant(5.0)

add = tf.compat.v1.add(input2,input3)
mul = tf.compat.v1.multiply(input1,add)
with tf.compat.v1.Session() as sess:
    result = sess.run([mul,add])
    print(result)
out:
[21.0, 7.0]
#Feed
input1 = tf.compat.v1.placeholder(tf.float32)
input2 = tf.compat.v1.placeholder(tf.float32)
output = tf.compat.v1.multiply(input1,input2)
with tf.compat.v1.Session() as sess:
    print(sess.run(output,feed_dict={input1:[7],input2:[2.]}))
out:
[14.]

练习

x_data = np.random.rand(100)
y_data = x_data*0.1 + 0.2

#构造一个线性模型
b = tf.compat.v1.Variable(0.)
k = tf.compat.v1.Variable(0.)
y = k * x_data + b

#二次代价函数
loss = tf.compat.v1.reduce_mean(tf.compat.v1.square(y_data - y))

#定义一个梯度下降法来进行训练的优化器
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.2)
#最小化代价函数
train = optimizer.minimize(loss)

init = tf.compat.v1.global_variables_initializer()

with tf.compat.v1.Session() as sess:
    sess.run(init)
    for step in range(201):
        sess.run(train)
        if step % 20 == 0:
            print(step,sess.run([k,b]))
x_data = np.linspace(-0.5, 0.5,200)[:,np.newaxis]
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data) + noise
x = tf.compat.v1.placeholder(tf.float32,[None,1])
y = tf.compat.v1.placeholder(tf.float32,[None,1])

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

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

#二次代价函数
loss = tf.compat.v1.reduce_mean(tf.compat.v1.square(y-prediction))
#使用体肤下降法训练
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.compat.v1.global_variables_initializer()

with tf.compat.v1.Session() as sess:
    sess.run(init)
    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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值