深度学习框架Tensorflow学习与应用(1到4)

本套视频基于: https://www.bilibili.com/video/av20542427?p=4

一. 02-1 创建图,启动图


# coding: utf-8

# In[4]:


import tensorflow as tf


# In[6]:


#创建一个常量op
m1 = tf.constant([[3,4]])
#创建一个常量op
m2 = tf.constant([[1],[5]])
#创建一个矩阵乘法op,把m1和m2传入
product = tf.matmul(m1,m2)
print(product)


# In[8]:


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


# In[9]:


#或者以下方法也可以,并且这样的方法,可以不用.close()
with tf.Session() as sess:
    #调用sess的run方法来执行矩阵乘法op
    #run(producy)触发了图中的3个op
    result = sess.run(product)
    print(result)

二. 02-2 变量


# coding: utf-8

# In[1]:


import tensorflow as tf


# In[2]:

x = tf.Variable([1,2])
a = tf.constant([3,3])
#增加一个减法op
sub = tf.subtract(x,a)
#增加一个加法op
add = tf.add(x,sub)

init = tf.global_variables_initializer()

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


# In[9]:

#创建一个变量,初始化为0
state = tf.Variable(0,name='counter')
#创建一个op,作用是使state加1
new_value = tf.add(state,1)
#tensorflow中不能直接用等号赋值,而要调用这个方法。
update = tf.assign(state,new_value)


#变量初始化
#并且这一步只能在变量已经声明之后
init = tf.global_variables_initializer()

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

三. 02-3 Fetch and Feed


# coding: utf-8

# In[6]:


import tensorflow as tf


# In[7]:


#Fetch
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([mul,add])
    print(result)


# In[8]:


#Feed
#创建占位符
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.]}))

四.  02-4 tensorflow简单示例


# coding: utf-8

# In[1]:


import tensorflow as tf
import numpy as np


# In[5]:


#使用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))
#定义一个梯度下降法来进行训练的优化器
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,sess.run([k,b]))

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值