搭建第一个神经网络 --Tensorflow

知识共享许可协议 版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons

1、基于Tensorflow的NN

用张量表示数据,用计算图搭建神经网络,用会话执行计算图,优化线上的权重(参数),得到模型。

2、张量(tensor)

张良就是多维数组(列表),张量可以表示0阶到n阶数组(列表)。用阶表示张量的维数,0阶张量就是标量,表示一个单独的数。

维数 名字 例子
0-D 0 标量scalar s = 123
1-D 1 向量vector v = [1,2,3]
2-D 2 矩阵matrix m = [[1,2,3],[,4,5,6],[7,8,9]]
n-D n 张量tensor t = [[[…
3、修改vim

[root@instance-mtfsf05r ~]# vim ~/.vimrc

在.vimrc文件中写入:

set ts = 4
ser nm

ts = 4表示在vim中缩进一个tab键缩进4个空格
nm在vim中显示行号

4、两个张量的加法
# coding:utf-8
# 实现两个张量的加法
import tensorflow as tf  # 导入tensorflow模块,简写为tf

a = tf.constant([1.0, 2.0])  # 定义张量a,constant方法用来定义常数
b = tf.constant([3.0, 4.0])  # 定义张量b
rs = a + b
print(rs)

控制台打印:Tensor(“add:0”, shape=(2,), dtype=float32)

add:0:表示张量的名字

add:节点

0:第0个输出

shape=(2,):维度信息

shape:维度

(2,):一维数组,长度为2

dtype=float32:表示数据类型

dtype:数据类型

float32:浮点型数据

5、计算图(Graph)

控制台打印:Tensor(“add:0”, shape=(2,), dtype=float32),只显示这个结果是张量,但并没有运算张量具体的值。计算图:搭建神经网络的计算过程,只搭建、不计算。

神经元的基本模型:
y = XW = x1 * w1 + x2 * w2
在这里插入图片描述
用张量运算描述这个神经元:

# coding:utf-8
# 实现两个张量的加法
import tensorflow as tf  # 导入tensorflow模块,简写为tf

x = tf.constant([[1.0, 2.0]])  # 定义张量a,constant方法用来定义常数
w = tf.constant([[3.0], [4.0]])  # 定义张量b
y = tf.matmul(x, w)
print(y)

控制台打印:Tensor(“MatMul:0”, shape=(1, 1), dtype=float32)
结果是一行一列的二维张量。

6、会话(Session)

会话用来执行计算图中的节点运算。
使用Session得到运算结果:

# coding:utf-8
# 实现两个张量的加法
import tensorflow as tf  # 导入tensorflow模块,简写为tf

x = tf.constant([[1.0, 2.0]])  # 定义张量a,constant方法用来定义常数
w = tf.constant([[3.0], [4.0]])  # 定义张量b
y = tf.matmul(x, w)
# print(y)
# 使用Session得到运算结果
with tf.Session() as sess:
    print(sess.run(y))  # [[11.]]

控制台打印:[[11.]]
即:1.03.0 + 2.04.0 = 11.0

猜你喜欢

转载自blog.csdn.net/Thanlon/article/details/93747497