TensorFlow中的神经网络

2019-03-05  本文已影响0人  kokana

一 TensorFlow的安装

pip install numpy

pip install tensorflow


二 简单的TensorFlow例子

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进一步学习

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中的变量定义

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参数来输入数据,这个参数是字典的形式.

六 激励函数

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
        

"""
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)

七 数据可视化

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秒

上一篇下一篇

猜你喜欢

热点阅读