tensorflow的安装就不用多说了
直接pip install tensorflow=版本号
或者直接在VSCode终端conda install tensorflow可以快速安装最新版tensorflow
接下来我们来学习一些tensorflow的基本操作
Constant (常数)
import tensorflow as tf
x = tf.constant(100)
x
type(x)
<tf.Tensor ‘Const_3:0’ shape=() dtype=int32>
tensorflow.python.framework.ops.Tensor
Session (会话)
sess = tf.Session()
sess.run(x)
100
type(sess.run(x))
numpy.int32
Operation (操作)
x = tf.constant(2)
y = tf.constant(3)
with tf.Session() as sess:
print(sess.run(x+y))
print(sess.run(x-y))
print(sess.run(x*y))
print(sess.run(x/y))
Placeholder (占位符)
x = tf.placeholder(tf.int32)
y = tf.placeholder(tf.int32)
x
type(x)
<tf.Tensor ‘Placeholder:0’ shape= dtype=int32>
tensorflow.python.framework.ops.Tensor
定义操作
add = tf.add(x,y)
sub = tf.subtract(x,y)
mul = tf.multiply(x,y)
d = {x:20,y:30}
with tf.Session() as sess:
print(sess.run(add,feed_dict=d))
print(sess.run(sub,feed_dict=d))
print(sess.run(mul,feed_dict=d))
50
-10
600
import numpy as np
a = np.array([[5.0,5.0]])
b = np.array([[2.0],[2.0]])
a
a.shape
b
b.shape
array([[5., 5.]])
(1, 2)
array([[2.],
[2.]])
(2, 1)
矩阵乗积
mat1 = tf.constant(a)
mat2 = tf.constant(b)
matrix_multi = tf.matmul(mat1,mat2)
with tf.Session() as sess:
result = sess.run(matrix_multi)
print(result)
[[20.]]