3.20
1. Codebase for “Time-series prediction” with RNN, GRU, LSTM and Attention
https://github.com/jsyoon0823/Time-series-prediction
※ 占位符函数
tf.placeholder(dtype, shape=None, name=None)
parameter 解释:
- dtype,数据类型。
- shape,数据形状。默认为None,一维值。也可以是多维值([None, 2], 表示只知道列数,行数未知
- name:占位符名称,optional
使用该函数的原因与tensorflow的特性有关:静态图
在编写程序时,首先构筑整个系统的graph,此时图中的节点是未经初始化的,代码并未生效,这一点和python的其他数值计算库(如Numpy等)不同,graph为静态的。在实际的运行时,启动一个session,程序才会真正的运行。placeholder()函数是在神经网络构建graph的时候在模型中的占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存。等建立session,在会话中,运行模型的时候通过feed_dict()函数向占位符输入数据。通常用来获取模型的输入数据。
import tensorflow as tf
import numpy as np
input1 = tf.placeholder(tf.float32, [], name='input1') #为输入数据input1定义占位符
input2 = tf.placeholder(tf.float32, [], name='input2') #为input2定义占位符
output = tf.multiply(input1, input2)
with tf.Session() as sess:
data_dict = {input1:[3.], input2: [4.]}
print(sess.run(output, feed_dict=data_dict)) #通过sess.run中的feed_dict赋值
※ tf.map_fn函数
map_fn(fn, elems, dtype=None, parallel_iterations=None, back_prop=True,
swap_memory=False, infer_shape=True, name=None)
参数:
- fn:函数,可用lambda形式表示
- elems:数据
- dtype:输出数据的形式
函数功能: map on the list of tensors unpacked from elems on dimension 0.
elems = np.array([1, 2, 3, 4, 5, 6])
squares = map_fn(lambda x: x * x, elems)
# squares == [1, 4, 9, 16, 25, 36]
elems = (np.array([1, 2, 3]), np.array([-1, 1, -1]))
alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64)
# alternate == [-1, 2, -3]
elems = np.array([1, 2, 3])
alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64))
# alternates[0] == [1, 2, 3]
# alternates[1] == [-1, -2, -3]
einsum函数
https://blog.csdn.net/zzq060143/article/details/89107567
result = einsum("xx,xxx,xx->xx",arg1,arg2,arg3)
xx等表示占位符,具体内容为张量维度。 einsum处理的是可变数量的输入。
einsum在numpy中实现为np.einsum,在PyTorch中实现为torch.einsum,在TensorFlow中实现为tf.einsum,均使用一致的签名einsum(equation, operands),其中equation是表示爱因斯坦求和约定的字符串,而operands则是张量序列(在numpy和TensorFlow中是变长参数列表,而在PyTorch中是列表)。
示例
final_hidden_state = tf.einsum('ijk,ijl->jkl', a_values,
all_hidden_states)
a_values 维度为ijk, all_hidden_states维度为ijl, 两个张量做乘法,得到output的维度为jkl
何为张量
1. Array Definition: Tensor = mlti-dimensional array of numbers ARE ABSOLUTE WRONG
2. Tensor = an object that is invariant under a change of coordinates, and has components that change in a special, predictable way under a change of coordinates.
3. Tensor = a collection of vectors and covectors combined together using the tensor product. (Abstract Definition)
- AI definition: A tensor is a generalization of vectors and matrices to potentially higher dimensions.
张量是多维数组,目的是把向量、矩阵推向更高的维度。