TensorFlow中的神经网络

一 TensorFlow的安装

  • 首先安装numpy,需要最新版

pip install numpy

  • 之后安装Tensorflow

pip install tensorflow


二 简单的TensorFlow例子

  • 让计算机自己预测y = 0.3x + b
import tensorflow as tf
import numpy as np

# create data

x_data = np.random.rand(100).astype(np.float32)#初始化100以内的值
y_data = x_data*0.1 + 0.3#根据随机的x值计算y值

### create tensorflow structure start ###
#这个是线性回归 y = Wx + b 其中W可能不是一个具体的数字,可能是一个矩阵,b为偏移量
Weights = tf.Variable(tf.random_uniform([2], -1.0, 1.0))#[1]是生成一个一维的数,范围在-0.1与1之间

biases = tf.Variable(tf.zeros([1]))#生成一个一维为0的数字

y = Weights*x_data + biases#这个是根据计算得到的曲线 反复计算用来学习

loss = tf.reduce_mean(tf.square(y-y_data))#计算估计的y与原先y的误差
optimizer = tf.train.GradientDescentOptimizer(0.5)#定义学习效率
train = optimizer.minimize(loss)#这个就是在训练

init = tf.initialize_all_variables()#初始化整个神经网络的结构
### create tensorflow structure end ###

sess = tf.Session()     #定义一个绘画类似指针的东西
sess.run(init)          # Very important指向了之前定义的神经网络 并且激活

for step in range(20000):
    sess.run(train)#真正的指向训练过程
    if step % 20 == 0:
        print(step, sess.run(Weights), sess.run(biases))v

三 TensorFlow中的Session进一步学习

  • session其实就是负责启动这个神经网络的对象。
  • session中的run方法 如果想用到tf中的方法 变量 就要使用run指向这个对象
  • 列子:两个矩阵相乘
import tensorflow as tf
m1 = tf.constant([[2,3]]) #定义矩阵
m2 = tf.constant([[2],[3]])
product = tf.matmul(m1,m2) #这个就是矩阵相乘,与numpy中的dot一样
# sess = tf.Session()
# r = sess.run(product)
# print(r)
# sess.close()
with tf.Session() as sess:      #开启session并且运行product
    print(sess.run(product))

四 TensorFlow中的变量定义

  • 使用tensorFlow中的Variable作为变量
  • 使用tensorFlow中的constant做为常量
import tensorflow as tf
text1 = tf.Variable(0,'happy') #叫做happy的变量值为1 
one = tf.constant(1)#常量
new = tf.add(text1,one)#这是tf中的相加
update = tf.assign(text1,new)#把new附给text1
init = tf.initialize_all_variables()#这个很重要 初始化所有表变量
with tf.Session() as sess:
    sess.run(init)
    for each in range(3):
        sess.run(update)
        print(sess.run(text1))

五 tensorFlow中的placeholder

  • 这个模块是控制负责接受外界输入的
import tensorflow as tf
input1 = tf.placeholder(tf.float32) #定义一个input1参数
input2 = tf.placeholder(tf.float32)
update = tf.multiply(input1,input2)#这是两个两个数相乘
with tf.Session() as sess:
    print(sess.run(update,feed_dict= {input1:0.3,input2 :0.5}))#通过feed_dict参数来输入数据,这个参数是字典的形式.

六 激励函数

  • 神经网络中的每个节点接受输入值,并将输入值传递给下一层,输入节点会将输入属性值直接传递给下一层(隐层或输出层)。在神经网络中,隐层和输出层节点的输入和输出之间具有函数关系,这个函数称为激励函数。常见的激励函数有:线性激励函数、阈值或阶跃激励函数、S形激励函数、双曲正切激励函数和高斯激励函数等。
  • 我对激励函数的理解:对于输入的一个值,每一层的神经元对这个值的敏感程度不同,会用不同的敏感程度,把这个值放大或者缩小,传入下一层神经元。
    Tensorflow中激励函数传送门
  • 激励函数例子:添加一个层:
import tensorflow as tf
def add_layer(inputs,in_size,out_size,activation_function = None):
    Weight = tf.Variable(tf.random_normal([in_size,out_size]))
    biase = tf.Variable(tf.zeros([1,out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs,Weight) + biase
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs
  • 简单计算一下y = x^2 + 0.5 的损失
        

"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def add_layer(inputs, in_size, out_size, activation_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]#构造出300个x值
noise = np.random.normal(0, 0.05, x_data.shape)#随机生成影响值
y_data = np.square(x_data) * x_data - 0.5 + noise#根据构造的值生成函数  y = x^2 - 0.5 + noise

##plt.scatter(x_data, y_data)
##plt.show()

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])#输入的x
ys = tf.placeholder(tf.float32, [None, 1])#输入的y
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)#这个是输入的xs的神经元 传送给10个神经元 用tf.nn.relu的激励函数
# add output layer
prediction = add_layer(l1, 10, 1, activation_function=None)#输出预测结果

# the error between prediciton and real data
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))#计算损失
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#训练 减少损失
# important step
init = tf.initialize_all_variables()
sess= tf.Session()
sess.run(init)

# plot the real data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.ion()
plt.show()


for i in range(1000):
    # training
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if i % 50 == 0:
        # to visualize the result and improvement
        try:
            ax.lines.remove(lines[0])
        except Exception:
            pass
        prediction_value = sess.run(prediction, feed_dict={xs: x_data})
        # plot the prediction
        lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
        plt.pause(1)

七 数据可视化

  • 需要用到matplotlib包

pip install matplotlib

fig = plt.figure() #创建一个图
ax = fig.add_subplot(1,1,1)#规定图的编号
ax.scatter(x_data, y_data)#写入真实的数据
plt.ion()#画图表之后不要暂停
plt.show()#显示图标
ax.lines.remove(lines[0])#去除第0条线
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)#生成红色宽度为5的线
plt.pause(1) #暂停1秒

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容