Tensorflow机器学习入门——常量、变量、placeholder和基本运算

一、这里列出了tensorflow的一些基本函数,比较全面:https://blog.csdn.net/M_Z_G_Y/article/details/80523834

二、这里是tensortflow的详细教程:http://c.biancheng.net/tensorflow/

三、下面程序是我学习常量、变量、placeholder和基本运算时形成的小函数

import tensorflow as tf

print(tf.__version__)#打印Tensorflow版本
print(tf.__path__)#打印Tensorflow安装路径

#3第一个tensorflow程序
def test3():
    message = tf.constant(‘Welcome to the exciting world of Deep Neural Networks!‘)
    with tf.Session() as sess:
        print(sess.run(message).decode())

#4程序结构
def test4(): 
    v_1=tf.constant([1,3,4,5])
    v_2=tf.constant([2,3,4,5])
    v_add=tf.add(v_1,v_2)
    with tf.Session() as sess:
        print(sess.run(v_add))
#5_1常量
def test5_1():
    con1 = tf.constant([4,3,2])
    zeros1= tf.zeros([2,3],tf.int32)
    zeros2=tf.zeros_like(con1)
    ones1=tf.ones([2,3],tf.int32)
    ones2=tf.ones_like(con1)
    nine1=tf.fill([2, 3], 9.0) 
    diag= tf.diag([1.0, 2.0, 3.0])
    line1 = tf.linspace(2.0,5.0,5)
    range1= tf.range(10)
    random1=tf.random_normal([2,3],mean=2,stddev=4,seed=12)#正态分布随机数组
    random2=tf.truncated_normal([2,3],stddev=3,seed=12)#结尾正态随机分布数组
    add1=tf.add(con1,zeros1)
    with tf.Session() as sess:
        print(‘con1:\n‘,sess.run(con1))
        print(‘zeros1:\n‘,sess.run(zeros1))
        print(‘zeros2:\n‘,sess.run(zeros2))
        print(‘ones1:\n‘,sess.run(ones1))
        print(‘ones2:\n‘,sess.run(ones2))
        print(‘line1:\n‘,sess.run(line1))
        print(‘range1:\n‘,sess.run(range1))
        print(‘random1:\n‘,sess.run(random1))
        print(‘random2:\n‘,sess.run(random2))
        print(‘add1:\n‘,sess.run(add1))
    
#5_2变量
def test5_2():
    matrix1=tf.Variable(tf.random_uniform([2,2],0,10,seed=0),name=‘weights‘)
    matrix2=tf.Variable(tf.random_uniform([2,2],0,10,seed=1),name=‘weights‘)
    add=tf.add(matrix1,matrix2)#加法
    subtract=tf.subtract(matrix1,matrix2)#减法
    product1= tf.matmul(matrix1,matrix2)#矩阵相乘
    product2=tf.scalar_mul(2,matrix1)#标量*矩阵
    product3=matrix1*matrix2#对应元素相乘,等同于tf.multiply()
    div=tf.div(matrix1,matrix2)#对应元素相除
    mod=tf.mod(matrix1,matrix2)#对应元素取模
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        print(‘matrix1:\n‘,sess.run(matrix1))
        print(‘matrix2:\n‘,sess.run(matrix2))
        print(‘add:\n‘,sess.run(add))
        print(‘subtract:\n‘,sess.run(subtract))
        print(‘product1:\n‘,sess.run(product1))
        print(‘product2:\n‘,sess.run(product2))
        print(‘product3:\n‘,sess.run(product3))
        print(‘div:\n‘,sess.run(div))
        print(‘mod:\n‘,sess.run(mod))

#5_3Placeholder
def test5_3():
    x=tf.placeholder(tf.float32,[None,5])
    y=x*2
    data=tf.random_uniform([4,5],0,10)
    with tf.Session() as sess:
        x_data=sess.run(data)
        print(sess.run(y,feed_dict={x:x_data}))
    
    
    
    
    
test5_2()