安装好Tensorflow之后开始学习如何使用
使用ubuntu+python+vim学习Tensorflow
source ./venv/bin/activate
sudo vi a.py
a:py:
import tensorflow as tf
a = tf.constant([1,2])
print a
保存后,python a.py执行
Tensor(“Const:0”, shape=(2,), dtype=int32)
输出结果:
tensor 张量
Const:0张量名
shape = (2,) 第一行两个元素,即为一行两列的张量.
dtype = int32 数据类型为32位整型1
以上代码还可以改为
tf.constant(1)
tf.constant([1])
tf.constant([1,2],[2,3])
tf.constant([1.0,2.0],[2.0,3.0])
下面介绍几个概念
神经网络的意义是当你给出足够多的样本,可以使算法中的权重值足够准确,使得最后通过算法计算出的预测值非常接近真实值
从以上这句话,我们看得出神经网络的构成需要以下几样东西
1.样本:也就是输入,比如人脸图片
2.足够多的样本:比如人脸数据库
3.算法:比如人脸识别算法,可能通过脸部的特征判断男女
4.权重值:这个目前阶段咱还是靠想象,小白还没接触过算法。
5.预测值:输出
6.真实值:比如得到这张人脸是男的
那么我们写代码大概就是这么个框架
一段例子
这段例子来源于MOOC网课,人工智能实践:Tensorflow笔记中
实现的是:将(重量,体积)
输入到神经网络中,通过权重w1,w2计算得到了
预测值y_
最后与真实值Y比较
1 import tensorflow as tf
2 import numpy as np
3 BATCH_SIZE = 8
4 seed = 23455
5
6 rng = np.random.RandomState(seed)
7 X = rng.rand(32,2) //足够多的样本(32)
8 Y = [[int(x0+x1<1)] for (x0,x1) in X] //根据样本中体积+质量<1 则为合格样本Y赋值1
9 print "X is", X
10 print "Y is ", Y
11
12 x = tf.compat.v1.placeholder(tf.float32,shape=(None,2))
13 y_ = tf.compat.v1.placeholder(tf.float32,shape=(None,1))//预测值
14
15 w1 = tf.compat.v1.Variable(tf.random.normal([2,3],stddev=1,seed=1))//权重变量(需要通过样本训练优化的值)
16 w2 = tf.compat.v1.Variable(tf.random.normal([3,1],stddev=1,seed=1))//权重(需要通过样本训练优化的值)
17
18 a = tf.matmul(x,w1)
19 y = tf.matmul(a,w2)
20
21 loss = tf.reduce_mean(tf.square(y-y_))
22 train_step = tf.compat.v1.train.GradientDescentOptimizer(0.001).minimize(loss)
23 with tf.compat.v1.Session() as sess:
24 init_op = tf.global_variables_initializer()
25 sess.run(init_op)
26 print "w1 = \n" ,sess.run(w1)
27 print "w2 = \n", sess.run(w2)
28
29 STEPS = 3000
30 for i in range(STEPS):
31 start = (i*BATCH_SIZE)%32
32 end = start + BATCH_SIZE
33 sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
34 if i%500 == 0:
35 total_loss = sess.run(loss,feed_dict={x:X,y_:Y})
36 print("After %d training steps, loss on all data is %g" %(i,total_loss))
37 print "\nw1:\n",sess.run(w1)
38 print "w2:\n", sess.run(w2)