TensorFlow学习笔记:6、用Tensorflow计算a=(b+c)∗(c+2)

Tensorflow是基于graph的并行计算模型
举个例子,用Tensorflow计算a=(b+c)∗(c+2)
可以将算式拆分成一下:

d = b + c
e = c + 2
a = d * e

编程如下

# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 16:39:49 2019

@author: hadron
"""
# https://blog.csdn.net/hustqb/article/details/80222055
# Tensorflow是基于graph的并行计算模型
# 举个例子,用Tensorflow计算a=(b+c)∗(c+2)
# 可以将算式拆分成一下:
# d = b + c
# e = c + 2
# a = d * e

import numpy as np
import tensorflow as tf

# TensorFlow中,使用tf.constant()定义常量,值不可变

# 首先,创建一个TensorFlow常量,并赋值2
const = tf.constant(2.0, name='const')
# 两种方式创建变量b和c
# 使变量b可以接收任意值。TensorFlow中接收值的方式为占位符(placeholder),通过tf.placeholder()创建。
b = tf.placeholder(tf.float32, [None, 1], name='b')
#使用tf.Variable()定义变量,值可变。
c = tf.Variable(1.0, dtype=tf.float32, name='c')

# 创建operation
d = tf.add(b, c, name='d')
e = tf.add(c, const, name='e')
a = tf.multiply(d, e, name='a')

# Tensorflow 的变量必须先初始化,然后才有值
# 添加用于初始化变量的节点
init_op = tf.global_variables_initializer()
# 运行graph需要先调用tf.Session()函数创建一个会话(session)。session就是我们与graph交互的handle。
# session
with tf.Session() as sess:
	# 2. 运行init operation
	sess.run(init_op)
    # tensorflow里对于暂时不进行赋值的元素有一个称呼叫占位符
    # feed_dict就是用来赋值的,格式为字典型
	a_out = sess.run(a, feed_dict={b: np.arange(0, 10)[:, np.newaxis]})
	print("Variable a is {}".format(a_out))

print("----------") 
#np.arange(0, 10)生成一维数组[0 1 2 3 4 5 6 7 8 9]
print(np.arange(0, 10))    
#np.newaxis在这一位置增加一个一维,这一位置指的是np.newaxis所在的位置
print(np.arange(0, 10)[:, np.newaxis])

运行结果

Variable a is [[ 3.]
 [ 6.]
 [ 9.]
 [12.]
 [15.]
 [18.]
 [21.]
 [24.]
 [27.]
 [30.]]
----------
[0 1 2 3 4 5 6 7 8 9]
[[0]
 [1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]
 [8]
 [9]]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值