import numpy as np
import matplotlib.pyplot as plt
import os
import pickle
import tensorflow as tf
print(tf.__version__)
# python3.8, tf2.2.0
c = tf.zeros(shape=[3,3])
print(c)
tf.Tensor(
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]], shape=(3, 3), dtype=float32)
cc = tf.ones_like(c)
print(cc)
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]], shape=(3, 3), dtype=float32)
创建值一样的张量。
fill_var = tf.fill(dims=[2,3], value=6)
print(fill_var)
tf.Tensor(
[[6 6 6]
[6 6 6]], shape=(2, 3), dtype=int32)
创建随机变量
ran_var = tf.random.normal(shape=[4,4])
print(ran_var)
tf.Tensor(
[[ 0.33064103 1.4237585 0.02514779 1.6599239 ]
[-0.5071548 -0.13427742 -0.9813222 1.1622552 ]
[ 0.4360873 -0.13483302 -1.6884859 -0.23662743]
[ 1.3623153 0.2961406 -0.03932188 -1.1478075 ]], shape=(4, 4), dtype=float32)
创建一个常量张
con_var = tf.constant(value=[[3,4,3],[5,6,7], [7,8,9]])
print(con_var)
tf.Tensor(
[[3 4 3]
[5 6 7]
[7 8 9]], shape=(3, 3), dtype=int32)
lin_var = tf.linspace(start=1.0, stop=10.0, num=5)
print(lin_var)
tf.Tensor([ 1. 3.25 5.5 7.75 10. ], shape=(5,), dtype=float32)
range_var = tf.range(start=1, limit=10, delta=2)
print(range_var)
# 获得张量的numpy数组
a_numpy = range_var.numpy()
print(a_numpy)
print(type(a_numpy))
con_var = tf.constant(value=[[3,4,3],[5,6,7], [7,8,9]])
print(con_var)
con_plus = con_var+con_var
print('+', con_plus)
+
tf.Tensor(
[[ 6 8 6]
[10 12 14]
[14 16 18]], shape=(3, 3), dtype=int32)
con_var = tf.constant(value=[[3,4,3],[5,6,7], [7,8,9]])
con_mul = tf.matmul(con_var, con_var)
print('矩阵乘法\n', con_mul)
矩阵乘法
tf.Tensor(
[[ 50 60 64]
[ 94 112 120]
[124 148 158]], shape=(3, 3), dtype=int32)
con_var = tf.constant(value=[[3,4,3],[5,6,7], [7,8,9]])
con_dot = tf.multiply(con_var, con_var)
print('点乘', con_dot)
点乘
tf.Tensor(
[[ 9 16 9]
[25 36 49]
[49 64 81]], shape=(3, 3), dtype=int32)
con_var = tf.constant(value=[[3,4,3],[5,6,7], [7,8,9]])
con_trans = tf.linalg.matrix_transpose(con_var)
print('转置')
print(con_trans)
转置
tf.Tensor(
[[3 5 7]
[4 6 8]
[3 7 9]], shape=(3, 3), dtype=int32)
# 将12×1张量变成3*4的张量
b = tf.linspace(start=1.0, stop=10.0, num=12)
b_re = tf.reshape(b, [3,4])
b_re2 = tf.reshape(b, [3, -1])
#
print(b)
print(b_re)
print(b_re2)
错误:
TypeError: Cannot convert 10.0 to EagerTensor of dtype int32
tf.linspace(start=1, stop=10.0, num=12)的start和stop要是小数。
实现 y = x 2 y=x^2 y=x2在x=1处的导数
x = tf.Variable([8.0])
print(x)
# 获得导数公式
with tf.GradientTape() as tape:
y = x*x
# 计算x具体值的导数值。
grad = tape.gradient(y, x)
print(grad)
tf.Tensor([16.], shape=(1,), dtype=float32)
问题:
WARNING:tensorflow:The dtype of the target tensor must be floating (e.g. tf.float32) when calling GradientTape.gradient, got tf.int32