TensorFlow入门(一)基本用法

本例子主要是按照 tensorflow的中文文档来学习 tensorflow 的基本用法。按照文档说明,主要存在的一些问题:

  • 1.就是 Session() 和 InteractiveSession() 的用法。后者用 Tensor.eval() 和 Operation.run() 来替代了 Session.run(). 其中更多的是用 Tensor.eval(),所有的表达式都可以看作是 Tensor.
  • 2.另外,tf的表达式中所有的变量或者是常量都应该是 tf 的类型。
  • 3.只要是声明了变量,就得用 sess.run(tf.global_variables_initializer()) 或者 x.initializer.run() 方法来初始化才能用。

例一:平面拟合

通过本例可以看到机器学习的一个通用过程:1.准备数据 -> 2.构造模型(设置求解目标函数) -> 3.求解模型

import tensorflow as tf
import numpy as np

# 1.准备数据:使用 NumPy 生成假数据(phony data), 总共 100 个点.
x_data = np.float32(np.random.rand(2, 100)) # 随机输入
y_data = np.dot([0.100, 0.200], x_data) + 0.300

# 2.构造一个线性模型
b = tf.Variable(tf.zeros([1]))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b

# 3.求解模型
# 设置损失函数:误差的均方差
loss = tf.reduce_mean(tf.square(y - y_data))
# 选择梯度下降的方法
optimizer = tf.train.GradientDescentOptimizer(0.5)
# 迭代的目标:最小化损失函数
train = optimizer.minimize(loss)


############################################################
# 以下是用 tf 来解决上面的任务
# 1.初始化变量:tf 的必备步骤,主要声明了变量,就必须初始化才能用
init = tf.global_variables_initializer()


# 设置tensorflow对GPU的使用按需分配
config  = tf.ConfigProto()
config.gpu_options.allow_growth = True
# 2.启动图 (graph)
sess = tf.Session(config=config)
sess.run(init)

# 3.迭代,反复执行上面的最小化损失函数这一操作(train op),拟合平面
for step in xrange(0, 201):
    sess.run(train)
    if step % 20 == 0:
        print step, sess.run(W), sess.run(b)

# 得到最佳拟合结果 W: [[0.100  0.200]], b: [0.300]
0 [[ 0.27467242  0.81889796]] [-0.13746099]
20 [[ 0.1619305   0.39317462]] [ 0.18206716]
40 [[ 0.11901411  0.25831661]] [ 0.2642329]
60 [[ 0.10580806  0.21761954]] [ 0.28916073]
80 [[ 0.10176832  0.20532639]] [ 0.29671678]
100 [[ 0.10053726  0.20161074]] [ 0.29900584]
120 [[ 0.100163    0.20048723]] [ 0.29969904]
140 [[ 0.10004941  0.20014738]] [ 0.29990891]
160 [[ 0.10001497  0.20004457]] [ 0.29997244]
180 [[ 0.10000452  0.20001349]] [ 0.29999167]
200 [[ 0.10000138  0.2000041 ]] [ 0.29999748]

例二:两个数求和

input1 = tf.constant(2.0)
input2 = tf.constant(3.0)
input3 = tf.constant(5.0)

intermd = tf.add(input1, input2)
mul = tf.multiply(input2, input3)

with tf.Session() as sess:
    result = sess.run([mul, intermd])  # 一次执行多个op
    print result
    print type(result)
    print type(result[0])   
[15.0, 5.0]
<type 'list'>
<type 'numpy.float32'>

1.变量,常量

1.1 用 tensorflow 实现计数器,主要是设计了 在循环中调用加法实现计数

# 创建变量,初始化为0
state = tf.Variable(0, name="counter")

# 创建一个 op , 其作用是时 state 增加 1
one = tf.constant(1) # 直接用 1 也就行了
new_value = tf.add(state, 1)
update = tf.assign(state, new_value)


# 启动图之后, 运行 update op
with tf.Session() as sess:
    # 创建好图之后,变量必须经过‘初始化’ 
    sess.run(tf.global_variables_initializer())
    # 查看state的初始化值
    print sess.run(state)
    for _ in range(3):
        sess.run(update)  # 这样子每一次运行state 都还是1
        print sess.run(state)
0
1
2
3

1.2 用 tf 来实现对一组数求和,再计算平均

h_sum = tf.Variable(0.0, dtype=tf.float32)
# h_vec = tf.random_normal(shape=([10]))
h_vec = tf.constant([1.0,2.0,3.0,4.0])
# 把 h_vec 的每个元素加到 h_sum 中,然后再除以 10 来计算平均值
# 待添加的数
h_add = tf.placeholder(tf.float32)
# 添加之后的值
h_new = tf.add(h_sum, h_add)
# 更新 h_new 的 op
update = tf.assign(h_sum, h_new)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # 查看原始值
    print 's_sum =', sess.run(h_sum)
    print "vec = ", sess.run(h_vec)

    # 循环添加
    for _ in range(4):
        sess.run(update, feed_dict={h_add: sess.run(h_vec[_])})
        print 'h_sum =', sess.run(h_sum)

#     print 'the mean is ', sess.run(sess.run(h_sum) / 4)  # 这样写 4  是错误的, 必须转为 tf 变量或者常量
    print 'the mean is ', sess.run(sess.run(h_sum) / tf.constant(4.0))
 s_sum = 0.0
vec =  [ 1.  2.  3.  4.]
h_sum = 1.0
h_sum = 3.0
h_sum = 6.0
h_sum = 10.0
the mean is  2.5

1.3 只用一个变量来实现计数器

上面的计数器是 TensorFlow 官方文档的例子,但是让人觉得好臃肿,所以下面我写了个更加简单的,只需要定义一个变量和一个加1的操作(op)。通过for循环就能够实现了。

# 如果不是 assign() 重新赋值的话,每一次 sess.run()都会把 state再次初始化为 0.0
state = tf.Variable(0.0, tf.float32)
# 通过 assign 操作来改变state的值。
add_op = tf.assign(state, state+1)

sess.run(tf.global_variables_initializer())
print 'init state ', sess.run(state)
for _ in xrange(3):
    sess.run(add_op)
    print sess.run(state)
init state  0.0
1.0
2.0
3.0

这样子和我们平时实现计数器的方法基本上就 一致了。我们要重点理解的是, TensorFlow 中通过 tf.assign(ref, value) 的方式来把 value 值赋给 ref 变量。这样子,每一次循环的时候,ref 变量才不会再做定义时候的初始化操作。

2. InteractiveSession() 的用法

InteractiveSession() 主要是避免 Session(会话)被一个变量持有

a = tf.constant(1.0)
b = tf.constant(2.0)
c = a + b

# 下面的两种情况是等价的
with tf.Session():
    print c.eval()

sess = tf.InteractiveSession()
print c.eval()
sess.close()
3.0
3.0
a = tf.constant(1.0)
b = tf.constant(2.0)
c = tf.Variable(3.0)
d = a + b

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())

###################
# 这样写是错误的
# print a.run()  
# print d.run()

####################

# 这样才是正确的
print a.eval()   
print d.eval()

# run() 方法主要用来
x = tf.Variable(1.2)
# print x.eval()  # 还没初始化,不能用
x.initializer.run()  # x.initializer 就是一个初始化的 op, op才调用run() 方法
print x.eval()

sess.close()
1.0
3.0
1.2

2.1 怎样使用 tf.InteractiveSession() 来完成上面 1.2 中 求和 、平均 的操作呢?

h_sum = tf.Variable(0.0, dtype=tf.float32)
# h_vec = tf.random_normal(shape=([10]))
h_vec = tf.constant([1.0,2.0,3.0,4.0])
# 把 h_vec 的每个元素加到 h_sum 中,然后再除以 10 来计算平均值
# 待添加的数
h_add = tf.placeholder(tf.float32)
# 添加之后的值
h_new = tf.add(h_sum, h_add)
# 更新 h_new 的 op
update = tf.assign(h_sum, h_new)

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print 's_sum =', h_sum.eval()
print "vec = ", h_vec.eval()
print "vec = ", h_vec[0].eval()


for _ in range(4):
    update.eval(feed_dict={h_add: h_vec[_].eval()})
    print 'h_sum =', h_sum.eval()
sess.close()
s_sum = 0.0
vec =  [ 1.  2.  3.  4.]
vec =  1.0
h_sum = 1.0
h_sum = 3.0
h_sum = 6.0
h_sum = 10.0

3.使用feed来对变量赋值

这些需要用到feed来赋值的操作可以通过tf.placeholder()说明,以创建占位符。 

下面的例子中可以看出 session.run([output], …) 和 session.run(output, …) 的区别。前者输出了 output 的类型等详细信息,后者只输出简单结果。

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.0], input2:[2.0]})
[array([ 14.], dtype=float32)]
with tf.Session() as sess:
    result = sess.run(output, feed_dict={input1:[7.0], input2:[2.0]})
    print type(result)
    print result
<type 'numpy.ndarray'>
[ 14.]
with tf.Session() as sess:
    result = sess.run(output, feed_dict={input1:7.0, input2:2.0})
    print type(result)
    print result
<type 'numpy.float32'>
14.0
with tf.Session() as sess:
    print sess.run([output], feed_dict={input1:[7.0, 3.0], input2:[2.0, 1.0]})
[array([ 14.,   3.], dtype=float32)]
with tf.Session() as sess:
    print sess.run(output, feed_dict={input1:[7.0, 3.0], input2:[2.0, 1.0]})
[ 14.   3.]
作者:Jerr__y 发表于2017/2/25 16:37:06  原文链接
阅读:899 评论:1  查看评论
 
[原]numpy 常用操作

numpy提供了ndarray和matrix两种类型的数据,为我们进行科学运算提供了非常便捷的运算工具。相对来说,我觉得其实还是MATLAB对于矩阵运算的支持更加直观易操作,但是作为Python使用者,怎能不把numpy用熟用透呢。

在numpy中,同样一种操作可能提供了很多种不同的方式,具体怎么来实现完全是使用者个人习惯。对于和我一样的菜鸟,我觉得最好是从一开始就养成较好的操作习惯。

numpy的二维数组能够很好地实现矩阵的各种功能,而且比matrix要灵活,速度也更快(refer:numpy教程:矩阵matrix及其运算)。因此,在二者通用的情况下,我选择使用array来实现。

下面的内容主要是学习了numpy的教程之后,结合我自己在平时的使用中可能经常遇到的一些操作问题做一下总结,方便自己记住。一些比较少用的操作就先不管了,就算忘了再去查就好了。

numpy官方教程: https://docs.scipy.org/doc/numpy-dev/user/quickstart.html 
numpy官方教程中文翻译: NumPy的详细教程

1. 创建数组和数组变形

import numpy as np
# 创建数组
a = np.array([1,2,3,4,5,6])
print a
# 直接给a.shape赋值是最简单的变形方式
a.shape = (2,3)
print '变形之后:'
print a
[1 2 3 4 5 6]
[[1 2 3]
 [4 5 6]]
a.ravel() # 拉直数组
array([1, 2, 3, 4, 5, 6])

2.数组拼接

A = np.floor(np.random.randn(2,3) * 10)
print 'A:\n', A
B = np.floor(np.random.randn(2,3) * 10)
print 'B:\n', B
A:
[[ -2.   3. -10.]
 [  5.   4.   7.]]
B:
[[-14.  -7.   3.]
 [ 10.   6.  -8.]]
# 按第一个轴拼接
print '按行拼接:'
print np.vstack([A,B])
# 按第二个轴拼接
print '按列拼接:'
print np.hstack([A,B])
按行拼接:
[[ -2.   3. -10.]
 [  5.   4.   7.]
 [-14.  -7.   3.]
 [ 10.   6.  -8.]]
按列拼接:
[[ -2.   3. -10. -14.  -7.   3.]
 [  5.   4.   7.  10.   6.  -8.]]

3. 基本操作和基本运算

np.exp(2)
7.3890560989306504
np.exp2(2)
4.0
np.sqrt(4)
2.0
np.sin([2,3])
array([ 0.90929743,  0.14112001])
np.log(2)
0.69314718055994529
np.log10(2)
0.3010299956639812
np.log2(2)
1.0
np.max([1,2,3,4])
4

4.二维数组完成矩阵操作

A = np.array([[1, 2], [-1, 4]])
B = np.array([[2, 0], [3, 4]])
print '对应元素想乘:'
print A * B
print '矩阵乘法:'
print np.dot(A, B) # 或者 A.dot(B)
对应元素想乘:
[[ 2  0]
 [-3 16]]
矩阵乘法
[[ 8  8]
 [10 16]]
# 线性代数
from numpy import linalg
# 求A的转置
print 'A的转置:'
print A.transpose()

# 求A的逆矩阵
print 'A的逆矩阵:'
print linalg.inv(A)

# 特征值和特征向量
eigenvalues, eigenvectors = linalg.eig(A)
print 'A 的特征值:'
print eigenvalues # 特征值
print 'A 的特征向量:'
print eigenvectors # 特征向量
A的转置:
[[ 1 -1]
 [ 2  4]]
A的逆矩阵:
[[ 0.66666667 -0.33333333]
 [ 0.16666667  0.16666667]]
A 的特征值:
[ 2.  3.]
A 的特征向量:
[[-0.89442719 -0.70710678]
 [-0.4472136  -0.70710678]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值