一、遇到的问题
(1)Tensorflow2.0中没有相关模块
在编译的时候,会出现以下的问题,找你很久,才找到解决方法。
问题:
1)AttributeError: module 'tensorflow' has no attribute 'Session'
2)AttributeError: module 'tensorflow' has no attribute 'matrix_determinant'
解决方法:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.Session()tf.compat.v1.matrix_determinant()
也就是说:需要添加'compat.v1'
二、基础记录
1.创建张量
tf.constant()
参数是NumPy数组时,默认的浮点数是64,则tf.cinstan(np.array(1.0,2.0)),输出的类型是dtype=tf.float64;也就是说我们在使用数组作为参数时,tf.constant也接收了它的类型;所以在创建时就要确定好它的类型。
2.数据转换
tf.cast()函数将数据进行类型转换:低精度向高精度转换,否则一溢出。
tf.convert_to_tensor():将数据转换成tensor张量形式;
3.特殊的张量
1)创建全0张量和全1张量
tf.zeros(shape,dtype = tf.float32)
tf.ones(shape,dtype = tf.float32)
2)元素值都相同的张量
tf.fill([2,3],9)
tf.constant(6,[2,3])
3)创建随机数张量--正态分布
tf.random.normal(shape,mean,stddev,dtype) :
tf.random.truncated_normal() :返回一个截断的正态分布
tf.random.set_seed() :设置随机种子
tf.random.uniform() :创建均匀分布的张量
tf.random.shutffle() :随机打乱
4)创建序列---tf.range()
4.查看张量的属性
print(a.ndim);
print(a.dtype);
tf.shape(a);
tf.size();
tf.rank();
5.总结:
1)创建张量--小结
2)在Tensorflow中,所有的运算都是在张量中进行的;Numpy仅仅是输入和输出来使用;
张量运行在CPU、GPU和TPU;而NumPy数组只能在CPU中运行;
附录:
手写数字的代码
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
mnist = tf.keras.datasets.mnist
(train_x, train_y),(test_x,test_y) = mnist.load_data()
train_x[0]
plt.axis("off")
plt.imshow(train_x[44],cmap="gray")
plt.title(train_y[44])
plt.show()