tensorflow矩阵基础

预先定义好的数据不能满足要求,需要实时插入的数据

import tensorflow as tf
data1=tf.placeholder(tf.float32)
data2=tf.placeholder(tf.float32)
dataAdd=tf.add(data1.data2)
with tf.Session() as sess:
      print(sess.run(dataAdd,feed_dict={data1:1,data2:2}))
      #1 dataAdd 2 data(feed_dict={:,:})
import tensorflow as tf
data1=tf.constant([[6,6]])#一行两列
data2=tf.constant([[2],[2]])#两行一列
data3=tf.constant([[1,2],[3,4],[5,6]])#三行两列
print(data3.shape)
with tf.Session() as sess:
     print(sess.run(data3[0]))#打印第一行
     print(sess.run(data3[:,0]))#打印第一列

矩阵运算

import tensorflow as tf
data1 = tf.constant([[6,6]])#1*2类型
data2 = tf.constant([[2],
                     [2]])#2*1类型
data3 = tf.constant([[3,3]])
data4 = tf.constant([[1,2],
                     [3,4],
                     [5,6]])
matMul = tf.matmul(data1,data2)
matMul2 = tf.multiply(data1,data2)
matAdd = tf.add(data1,data3)
with tf.Session() as sess:
    print(sess.run(matMul))#1 维 M=1 N2. 1X2(MK) 2X1(KN) = 1
    print(sess.run(matAdd))#1行2列
    print(sess.run(matMul2))# 1x2 2x1 = 2x2
    print(sess.run([matMul,matAdd]))

结果
[[24]]
[[9 9]]
[[12 12]
[12 12]]
[array([[24]]), array([[9, 9]])]

特殊矩阵的初始化

import tensorflow as tf
mat0=tf.constant([0,0,0],[0,0,0])
#定义空矩阵可以用以下的方式
mat1=tf.zeros([2,3])
mat2=tf.ones([3,2])
#给矩阵填充一个固定的值
mat3=tf.fill([2,3],15)
#定义一个形状和mat3相同的全零矩阵
mat4=tf.zeros_like(mat3)
#等间距数据
mat5=tf.linspace(0.0,2.0,11)
#在[-1.2]范围内的随机数矩阵
mat6=tf.random_uniform([2,3],-1,2)

猜你喜欢

转载自blog.csdn.net/qq_30339595/article/details/86617733