Tensorflow的对二次函数的神经网络训练

这个是tensorflow的一个YouTube上的教程。

作为学习资料,拿来敲了一遍。

这是对一个二次函数的进行神经网络的训练

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]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

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

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=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)

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]
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

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

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# add hidden layer
l1 = add_layer(xs, 1, 10, activation_function=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)

for i in range(1000):
    # training
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if i % 50 == 0:
        # to see the step improvement
        print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))

时间: 2024-08-25 00:56:11

Tensorflow的对二次函数的神经网络训练的相关文章

神经网络训练中的Tricks之高效BP(反向传播算法)

神经网络训练中的Tricks之高效BP(反向传播算法) 神经网络训练中的Tricks之高效BP(反向传播算法) [email protected] http://blog.csdn.net/zouxy09 Tricks!这是一个让人听了充满神秘和好奇的词.对于我们这些所谓的尝试应用机器学习技术解决某些问题的人,更是如此.曾记得,我们绞尽脑汁,搓手顿足,大喊“为什么我跑的模型不work?”,“为什么我实现的效果那么差?”,“为什么我复现的结果没有他论文里面说的那么好?”.有人会和你说“你不懂调参!

字符识别OCR研究一(模板匹配&BP神经网络训练)

摘 要 在MATLAB环境下利用USB摄像头採集字符图像.读取一帧保存为图像.然后对读取保存的字符图像,灰度化.二值化,在此基础上做倾斜矫正.对矫正的图像进行滤波平滑处理,然后对字符区域进行提取切割出单个字符.识别方法一是採用模板匹配的方法逐个对字符与预先制作好的字符模板比較,假设结果小于某一阈值则结果就是模板上的字符:二是採用BP神经网络训练.通过训练好的net对待识别字符进行识别.最然后将识别结果通过MATLAB下的串口工具输出51单片机上用液晶显示出来. keyword: 倾斜矫正.字符切

模式识别之ocr项目---(模板匹配&BP神经网络训练)

摘 要 在MATLAB环境下利用USB摄像头采集字符图像,读取一帧保存为图像,然后对读取保存的字符图像,灰度化,二值化,在此基础上做倾斜矫正,对矫正的图像进行滤波平滑处理,然后对字符区域进行提取分割出单个字符,识别方法一是采用模板匹配的方法逐个对字符与预先制作好的字符模板比较,如果结果小于某一阈值则结果就是模板上的字符:二是采用BP神经网络训练,通过训练好的net对待识别字符进行识别.最然后将识别结果通过MATLAB下的串口工具输出51单片机上用液晶显示出来. 关键字: 倾斜矫正,字符分割,模板

Hulu机器学习问题与解答系列 | 二十三:神经网络训练中的批量归一化

来看看批量归一化的有关问题吧!记得进入公号菜单"机器学习",复习之前的系列文章噢. 今天的内容是 [神经网络训练中的批量归一化] 场景描述 深度神经网络的训练中涉及诸多手调参数,如学习率,权重衰减系数,Dropout比例等,这些参数的选择会显著影响模型最终的训练效果.批量归一化(Batch Normalization, BN)方法从数据分布入手,有效减弱了这些复杂参数对网络训练产生的影响,在加速训练收敛的同时也提升了网络的泛化能力. 问题描述 BN基本动机与原理是什么? BN的具体实现

机器学习与Tensorflow(5)——循环神经网络、长短时记忆网络

1.循环神经网络的标准模型 前馈神经网络能够用来建立数据之间的映射关系,但是不能用来分析过去信号的时间依赖关系,而且要求输入样本的长度固定 循环神经网络是一种在前馈神经网络中增加了分亏链接的神经网络,能够产生对过去数据的记忆状态,所以可以用于对序列数据的处理,并建立不同时段数据之间的依赖关系 循环神经网络是一类允许节点连接成有向环的人工神经网络.如下图: 2.循环神经网络与递归神经网络 从广义上说,递归神经网络可以分为结构递归神经网络和时间递归神经网络 从狭义上说,递归神经网络可以通常就是指结构

奉献pytorch 搭建 CNN 卷积神经网络训练图像识别的模型,配合numpy 和matplotlib 一起使用调用 cuda GPU进行加速训练

1.Torch构建简单的模型 # coding:utf-8 import torch class Net(torch.nn.Module): def __init__(self,img_rgb=3,img_size=32,img_class=13): super(Net, self).__init__() self.conv1 = torch.nn.Sequential( torch.nn.Conv2d(in_channels=img_rgb, out_channels=img_size, ke

TensorFlow学习系列(四):minist实例--用简单的神经网络训练和测试

神经网络没有卷积功能,只有简单的三层:输入层,隐藏层和输出层. 数据从输入层输入,在隐藏层进行加权变换,最后在输出层进行输出.输出的时候,我们可以使用softmax回归,输出属于每个类别的概率值. 其中,x1,x2,x3为输入数据,经过运算后,得到三个数据属于某个类别的概率值y1,y2,y3. 用简单的公式表示如下: 在训练过程中,我们将真实的结果和预测的结果相比(交叉熵比较法),会得到一个残差.公式如下: y 是我们预测的概率值, y' 是实际的值.这个残差越小越好,我们可以使用梯度下降法,不

吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集

import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data #设置输入参数 batch_size = 128 test_size = 256 # 初始化权值与定义网络结构,建构一个3个卷积层和3个池化层,一个全连接层和一个输出层的卷积神经网络 # 首先定义初始化权重函数 def init_weights(shape): return tf.Variabl

跟我学算法- tensorflow 卷积神经网络训练验证码

使用captcha.image.Image 生成随机验证码,随机生成的验证码为0到9的数字,验证码有4位数字组成,这是一个自己生成验证码,自己不断训练的模型 使用三层卷积层,三层池化层,二层全连接层来进行组合 第一步:定义生成随机验证码图片 number = ['0','1','2','3','4','5','6','7','8','9'] # alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',