tensorflow 基础教程

目录

用GPU进行TensorFlow计算加速

 

创建基本变量,和类似与 numpy的函数

实现变量自动加1操作

tensorflow格式和numpy格式转换

placeholder 用法(这里为什么可以不用初始化变量,加了也没有错,。。。)

构建一个线性点,用直线拟合数据

基本简单逻辑回归做手写数字分类

二、常用操作符和基本数学函数大多数运算符都进行了重载操作,使我们可以快速使用 (+ - * /) 等,但是有一点不好的是使用重载操作符后就不能为每个操作命名了。

 


用GPU进行TensorFlow计算加速,(有很多讲究,使用GPU要详看)

https://www.jianshu.com/p/26ac409dfb38

import tensorflow as tf
 # 通过tf.device将运算指定到特定的设备上。 
with tf.device('/cpu:0'): #变量存储一定放在cpu上面
    a = tf.constant([1.0, 2.0, 3.0], shape=[3], name='a') 
    b = tf.constant([1.0, 2.0, 3.0], shape=[3], name='b') 
with tf.device('/gpu:0'): #操作运算可以放到GPU上面
    c = a + b 
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) 
print (sess.run(c))

创建基本变量,和类似与 numpy的函数

import tensorflow as tf
import numpy as np

w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])

contact0 = tf.zeros([3,4],tf.int32)
contact0_ = tf.zeros_like(contact0) #像contact0 一样的形状的0阵
constan_ = tf.constant([1,2,3,4,5,6,7])
shuff = tf.random_shuffle(constan_) #洗牌操作
linspace_ = tf.linspace(10.0,12.0,6, name= 'linspace')  #10打头,12,结尾,一共6个数字
range_ = tf.range(1,10,2) #这个range和Python的用法一样
norm = tf.random_normal([2,3],mean=-1,stddev=4) #创建随机数,满足正态分布

y = tf.matmul(w,x)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    # print(y.eval()) # print(sess.run(y))
    print(shuff.eval())
    #a =  np.array(sess.run(constan_)) #tensor 结构和numpy结构可以来回转换
    print()

实现变量自动加1操作

----------------------------------------------------------加1 操作
import tensorflow as tf
import numpy as np

state = tf.Variable(0)
new_value = tf.add(state,tf.constant(1))
update = tf.assign(state,new_value)  # 赋值操作,

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(state)) # 这一步只是打印原始值
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
    print()

tensorflow格式和numpy格式转换

----------------------------------------------------------numpy 和 tensor格式的转换
import tensorflow as tf
import numpy as np
a = np.array([[1,2,3],
              [4,5,6]])
tensor = tf.convert_to_tensor(a)
#a =  np.array(sess.run(constan_)) #tensor 结构和numpy结构可以来回转换
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(tensor)) # 这一步只是打印原始值

placeholder 用法(这里为什么可以不用初始化变量,加了也没有错,。。。)

import tensorflow as tf
import numpy as np
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
    print(sess.run([output], feed_dict={input1:[7.],input2:[2.]}))

构建一个线性点,用直线拟合数据

---------------------------------------------------------直线拟合
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

num_points = 1000
vectors_set = []

for i in range(num_points):
    x1 = np.random.normal(0.0,0.55)
    y1 = x1*0.1 +0.3+np.random.normal(0.0,0.03)
    vectors_set.append([x1,y1])

x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]

-----------------------------------构建模型
# 生成1x1的矩阵,【-1,1】之间的随机数
W = tf.Variable(tf.random_uniform([1],-1.0,1.0),name='W')
b = tf.Variable(tf.zeros([1],name='b'))

y = W*x_data+b   #可以进行操作符重载吗?

loss = tf.reduce_mean(tf.square(y-y_data),name='loss')
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss,name='train')

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print('W = ',sess.run(W),'b = ',sess.run(b),'loss = ',sess.run(loss))
    for step in range(20):
        sess.run(train)
        print('W = ',sess.run(W),'b = ',sess.run(b),'loss = ',sess.run(loss))
    plt.scatter(x_data, y_data, c='r')
    plt.plot(x_data,sess.run(W)*x_data+sess.run(b))
    plt.show()

基本简单逻辑回归做手写数字分类

----------------------------------------------------基本逻辑回归代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#-----------------------------导入数据
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/',one_hot=True)

trainimg  = mnist.train.images
trainlabel = mnist.train.labels
testimg  = mnist.test.images
testlabel = mnist.test.labels
#----------------------------------显示数字
for i in range(5):
    curr_img = np.reshape(trainimg[i,:],(28,28))
    curr_label = np.argmax(trainlabel[i,:])
    plt.matshow(curr_img,cmap = plt.get_cmap('gray'))
    plt.title(''+ str(i)+'th Training Data'+'Label is' + str(curr_label))
    # plt.show()
# ----------------------------------定义模型
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
# tf.matmul(x,W)
actv = tf.nn.softmax(tf.matmul(x,W)+b) # ????
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv),reduction_indices=1))

learning_rate =0.01
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

pred = tf.equal(tf.argmax(actv,1),tf.argmax(y,1))   #argmax actv 最大值的索引 1,:代表行的索引
# 预测值和真实值的索引是否相等,最大值索引是否相等

accr = tf.reduce_mean(tf.cast(pred,'float')) #cast将pred转换float类型


init = tf.global_variables_initializer()

training_epochs =50
batch_size  =100
display_step   =5
sess = tf.Session()
sess.run(init)
#--------------------------开始执行
for epoch in range(training_epochs):
    avg_cost = 0.
    num_batch = int(mnist.train.num_examples/batch_size)
    for i in range(num_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        sess.run(optm,feed_dict={x:batch_xs,y:batch_ys})
        feeds ={x:batch_xs,y:batch_ys}
        avg_cost += sess.run(cost,feed_dict=feeds)/num_batch

    if epoch % display_step == 0:
        feeds_train ={x:batch_xs,y:batch_ys}
        feeds_test = {x:mnist.test.images, y:mnist.test.labels}
        train_acc = sess.run(accr,feed_dict=feeds_train)
        test_acc = sess.run(accr,feed_dict=feeds_test)
        print('Epoch:%03d/%03d cost:%.9f train_acc:%.3f test_acc:%.3f'
              % (epoch, training_epochs,avg_cost,train_acc,test_acc))

    # plt.show()

二、常用操作符和基本数学函数
大多数运算符都进行了重载操作,使我们可以快速使用 (+ - * /) 等,但是有一点不好的是使用重载操作符后就不能为每个操作命名了。


# 算术操作符:+ - * / %
tf.add(x, y, name=None)        # 加法(支持 broadcasting)
tf.subtract(x, y, name=None)   # 减法
tf.multiply(x, y, name=None)   # 乘法
tf.divide(x, y, name=None)     # 浮点除法, 返回浮点数(python3 除法)
tf.mod(x, y, name=None)        # 取余


# 幂指对数操作符:^ ^2 ^0.5 e^ ln
tf.pow(x, y, name=None)        # 幂次方
tf.square(x, name=None)        # 平方
tf.sqrt(x, name=None)          # 开根号,必须传入浮点数或复数
tf.exp(x, name=None)           # 计算 e 的次方
tf.log(x, name=None)           # 以 e 为底,必须传入浮点数或复数


# 取符号、负、倒数、绝对值、近似、两数中较大/小的
tf.negative(x, name=None)      # 取负(y = -x).
tf.sign(x, name=None)          # 返回 x 的符号
tf.reciprocal(x, name=None)    # 取倒数
tf.abs(x, name=None)           # 求绝对值
tf.round(x, name=None)         # 四舍五入
tf.ceil(x, name=None)          # 向上取整
tf.floor(x, name=None)         # 向下取整
tf.rint(x, name=None)          # 取最接近的整数
tf.maximum(x, y, name=None)    # 返回两tensor中的最大值 (x > y ? x : y)
tf.minimum(x, y, name=None)    # 返回两tensor中的最小值 (x < y ? x : y)


# 三角函数和反三角函数
tf.cos(x, name=None)
tf.sin(x, name=None)
tf.tan(x, name=None)
tf.acos(x, name=None)
tf.asin(x, name=None)
tf.atan(x, name=None)


# 其它
tf.div(x, y, name=None)  # python 2.7 除法, x/y-->int or x/float(y)-->float
tf.truediv(x, y, name=None) # python 3 除法, x/y-->float
tf.floordiv(x, y, name=None)  # python 3 除法, x//y-->int
tf.realdiv(x, y, name=None)
tf.truncatediv(x, y, name=None)
tf.floor_div(x, y, name=None)
tf.truncatemod(x, y, name=None)
tf.floormod(x, y, name=None)
tf.cross(x, y, name=None)
tf.add_n(inputs, name=None)  # inputs: A list of Tensor objects, each with same shape and type


--------------------------------------------------------------------------------

z = -x  # z = tf.negative(x)
z = x + y  # z = tf.add(x, y)
z = x - y  # z = tf.subtract(x, y)
z = x * y  # z = tf.mul(x, y)
z = x / y  # z = tf.div(x, y)
z = x // y  # z = tf.floordiv(x, y)
z = x % y  # z = tf.mod(x, y)
z = x ** y  # z = tf.pow(x, y)
z = x @ y  # z = tf.matmul(x, y)
z = x > y  # z = tf.greater(x, y)
z = x >= y  # z = tf.greater_equal(x, y)
z = x < y  # z = tf.less(x, y)
z = x <= y  # z = tf.less_equal(x, y)
z = abs(x)  # z = tf.abs(x)
z = x & y  # z = tf.logical_and(x, y)
z = x | y  # z = tf.logical_or(x, y)
z = x ^ y  # z = tf.logical_xor(x, y)
z = ~x  # z = tf.logical_not(x)
z = x[begin:end]  # z = tf.slice(x, [begin], [end-begin])
--------------------- 

 

猜你喜欢

转载自blog.csdn.net/weixin_42053726/article/details/85222217
今日推荐