Tensorflow入门之运算篇

第1关:Tensorflow基本运算

本关任务:编写一个函数,该函数有四个零阶Tensor参数,要求该函数使用Tensorflow的API先对它们两两求和,然后对和进行乘积计算。

# -*- coding: utf-8 -*-
import tensorflow as tf
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"]='3'

def simple_func(a,b,c,d):
    '''
    返回值:
    result: 一个标量值
    '''
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    tensor_a = tf.constant(a)
    tensor_b = tf.constant(b)
    tensor_c = tf.constant(c)
    tensor_d = tf.constant(d)
    e = tf.add(a,b)
    f = tf.add(c,d)
    g = tf.multiply(e,f)
    result = g.eval()


    # ********** End **********#

    # 返回result

    return result

a = int(input())
b = int(input())
c = int(input())
d = int(input())

init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
    print(simple_func(a,b,c,d))

第2关:Tensorflow常见矩阵操作

本关任务:编写一个函数,该函数传入一个值,然后生成一个3*3的常量方阵,即该矩阵的9个值都是这个传入的函数参数,然后给每个元素值加上该矩阵的对角元素之和,最后求出这个新矩阵的对角元素之和并返回。

# -*- coding: utf-8 -*-
import tensorflow as tf
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"]='3'

def count_trace(a):
    '''
    返回值:
    result: 一个标量值
    '''
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    A1 = tf.fill([3,3],a)
    t = tf.trace(A1)
    A2 = tf.fill([3,3],t)
    A3 = A1 + A2
    A3 = tf.trace(A3)
    result = A3.eval()

    # ********** End **********#
    # 返回result
    return result

init_op = tf.global_variables_initializer()
a = int(input())

with tf.Session() as sess:
    sess.run(init_op)
    print(count_trace(a))

第3关:Tensorflow数据广播机制

本关任务:编写一个能计算数组平均值和最大值的小程序。

# -*- coding: utf-8 -*-
import tensorflow as tf
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"]='3'

def broad_cast(t):
    tensor_a = tf.constant([[1, 3], [4, 5]])
    '''
    返回值:
    result: 一个标量值
    '''
    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    t1 =2 * t
    a = tf.constant([t,t1])
    A2 = a + tensor_a
    a = tf.expand_dims(a,1)
    A1 = a + tensor_a
    A = A1 + A2
    A = tf.trace(A)
    result = A.eval()
    # ********** End **********#
    # 返回result
    return result

init_op = tf.global_variables_initializer()

a = int(input())
with tf.Session() as sess:
    sess.run(init_op)
    print(broad_cast(a))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值