tensorflow学习笔记 + 程序 (一)tf基础

1 会话

1.1 基础例程

import tensorflow as tf 

# 创建一个常量矩阵
m1 = tf.constant([[3,3]])
# 创建一个常量矩阵
m2 = tf.constant([[2],[3]])

# 创建一个矩阵乘法的op,将m1和m2传入
product = tf.matmul(m1,m2)

# print(product)  #输出# Tensor("MatMul:0", shape=(1, 1), dtype=int32)
# 只是定义了op,并没有放在session(会话)中执行,故而结果为0


# 定义一个会话,启动默认的图
sess = tf.Session() # 使用默认的会话
result = sess.run(product)
# 启动会话(即4,6,9行只是定义,并没有执行,run之后才取生成了3个op)

# 查看结果
print("矩阵乘法结果 = ",result)
# 关闭会话
sess.close()


# 输出结果
'''
矩阵乘法结果 =  [[15]]
'''

1.2 一般定义方法

'''
with tf.Session() as sess:
    result = sess.run(product)
    print("矩阵乘法结果 = ",result)

'''
# 此时不需要关闭会话了,with内语句执行完毕后会话自动关闭

2 变量

2.1 基础例程

import tensorflow as tf 

# 定义变量矩阵
x = tf.Variable([1,2])
# 定义常量矩阵
a = tf.constant([3,3])
# 定义减法运算
sub = tf.subtract(x,a)
# 定义加法运算
add = tf.add(x,sub)

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

with tf.Session() as sess:
    sess.run(init) # 变量初始化
    # 这里也可以直接 sess.run(tf.global_variables_initializer())
    print("减法 : ",sess.run(sub))
    print("加法 : ",sess.run(add))


# 输出结果
''' 矩阵加减法对应位置相运算
减法 :  [-2 -1]
加法 :  [-1  1]
'''

2.2 循环变量自增

import tensorflow as tf 

# 创建一个变量,初始化为0
state = tf.Variable(0)
# 创建一个op,使变量自增1
new_value = tf.add(state,1)
# 调用一个赋值的操作(将新的值赋值给state)
update = tf.assign(state,new_value)
# 全部变量初始化
init = tf.global_variables_initializer()
# 定义会话
with tf.Session() as sess:
    sess.run(init)
    # print(sess.run(state)) # 如果有这句话的话就是0 1 2 3 4 5 了...
    for _ in range(5):
        sess.run(update)
        print(sess.run(state))
        # 相当于输出state的值


# 输出结果
'''
1
2
3
4
5
'''

3 Fetch and Feed

3.1 Fetch

# Fetch : 在会话中能执行多个op

import tensorflow as tf

# 定义三个常量
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)

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

with tf.Session() as sess:
    result = sess.run([add,mul]) # 同时执行但从实际输出也可以看出其是有先后的
    print("结果 : ",result)


# 输出结果
'''
结果 :  [7.0, 21.0]
'''

3.2 Feed

# Feed : 先以占位符的形式创建变量,在用时再给变量赋值

import tensorflow as tf

# 创建两个占位符
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:[7.],input2:[2.]}))


# 输出结果
'''
结果 :  [14.]
'''

4 简单线性函数拟合

4.1 基础实例

import tensorflow as tf
import numpy as np 

# 生成一百个随机点
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))
# 定义一个梯度下降法来进行的优化器(学习率为0.2)
optimizer = tf.train.GradientDescentOptimizer(0.2)
# 定义最小化代价函数
train = optimizer.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("运行次数 : ",step)
            print("[k,b] = ",sess.run([k,b]))


# 输出结果
'''
运行次数 :  0
[k,b] =  [array([0.05353429], dtype=float32), array([0.10002092], dtype=float32)]
运行次数 :  20
[k,b] =  [array([0.10323039], dtype=float32), array([0.19826433], dtype=float32)]
运行次数 :  40
[k,b] =  [array([0.10185491], dtype=float32), array([0.19900341], dtype=float32)]
运行次数 :  60
[k,b] =  [array([0.10106507], dtype=float32), array([0.19942777], dtype=float32)]
运行次数 :  80
[k,b] =  [array([0.10061155], dtype=float32), array([0.19967143], dtype=float32)]
运行次数 :  100
[k,b] =  [array([0.10035114], dtype=float32), array([0.19981134], dtype=float32)]
运行次数 :  120
[k,b] =  [array([0.10020163], dtype=float32), array([0.19989167], dtype=float32)]
运行次数 :  140
[k,b] =  [array([0.10011578], dtype=float32), array([0.19993779], dtype=float32)]
运行次数 :  160
[k,b] =  [array([0.10006648], dtype=float32), array([0.19996428], dtype=float32)]
运行次数 :  180
[k,b] =  [array([0.10003818], dtype=float32), array([0.1999795], 
dtype=float32)]
运行次数 :  200
[k,b] =  [array([0.10002191], dtype=float32), array([0.19998823], dtype=float32)]
'''

4.2 加点绘图

import tensorflow as tf
import numpy as np 
import matplotlib.pyplot as plt 

# 生成一百个随机点
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))
# 定义一个梯度下降法来进行的优化器
optimizer = tf.train.GradientDescentOptimizer(0.2)
# 定义最小化代价函数
train = optimizer.minimize(loss)

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

with tf.Session() as sess: 
    sess.run(init)
    for step in range(400):
        sess.run(train)
        if step % 20 == 0:
            print("运行次数 : ",step)
            print("[k,b] = ",sess.run([k,b]))
    k,b = sess.run([k,b])

# 绘图
plt.figure(num=1,figsize=(6,6))
plt.scatter(x_data,y_data)
plt.plot(x_data,k*x_data + b,'r',label='Predicted data')

plt.legend()
plt.show()

效果:

发布了6 篇原创文章 · 获赞 0 · 访问量 235

猜你喜欢

转载自blog.csdn.net/k903161661/article/details/104231282