deepNN

本文介绍了一种使用TensorFlow构建多层神经网络的方法,通过增加神经网络层数而非卷积层,实现对MNIST手写数字数据集的分类。文章详细展示了如何定义神经网络层、设置超参数、训练模型以及评估模型准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不做卷积,只是增加多层神经网络层。

#-*- encoding:utf-8 -*-
#!/usr/local/env python

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

def add_layer(inputs, in_size, out_size, activation_function=None):
    W = tf.Variable(tf.random_normal([in_size, out_size]))
    b = tf.Variable(tf.zeros([1, out_size]) + 0.01)

    Z = tf.matmul(inputs, W) + b
    if activation_function is None:
        outputs = Z
    else:
        outputs = activation_function(Z)

    return outputs


if __name__ == "__main__":

    MNIST = input_data.read_data_sets("mnist", one_hot=True)

    learning_rate = 0.01
    batch_size = 128
    n_epochs = 70

    X = tf.placeholder(tf.float32, [batch_size, 784])
    Y = tf.placeholder(tf.float32, [batch_size, 10])

    layer_dims = [784, 500, 500, 10]
    layer_count = len(layer_dims)-1 # 不算输入层
    layer_iter = X

    for l in range(1, layer_count): # layer [1,layer_count-1] is hidden layer
        layer_iter = add_layer(layer_iter, layer_dims[l-1], layer_dims[l], activation_function=tf.nn.relu)
    prediction = add_layer(layer_iter, layer_dims[layer_count-1], layer_dims[layer_count], activation_function=None)

    entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=prediction)
    loss = tf.reduce_mean(entropy)

    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)

    init = tf.initialize_all_variables()

    with tf.Session() as sess:
        sess.run(init)

        n_batches = int(MNIST.test.num_examples/batch_size)
        for i in range(n_epochs):
            for j in range(n_batches):
                X_batch, Y_batch = MNIST.train.next_batch(batch_size)
                _, loss_ = sess.run([optimizer, loss], feed_dict={X: X_batch, Y: Y_batch})
                if i % 10 == 5 and j == 0:
                    print( "Loss of epochs[{0}]: {1}".format(i, loss_))

        # test the model
        n_batches = int(MNIST.test.num_examples/batch_size)
        total_correct_preds = 0
        for i in range(n_batches):
            X_batch, Y_batch = MNIST.test.next_batch(batch_size)
            preds = sess.run(prediction, feed_dict={X: X_batch, Y: Y_batch})
            correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))
            accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))

            total_correct_preds += sess.run(accuracy)

        print ("Accuracy {0}".format(total_correct_preds/MNIST.test.num_examples))
View Code

 

转载于:https://www.cnblogs.com/superxuezhazha/p/9531932.html

下面的代码是干什么用的,请生成深度说明注释,让我理解每一行代码含义: 【import torch.nn as nn import torch import numpy as np input_size = 1 hidden_size1 =50 hidden_size2 =20 output_size = 1 N2 = nn.Sequential( nn.Linear(input_size, hidden_size1), nn.Tanh(), nn.Linear(hidden_size1, hidden_size2), nn.Tanh(), nn.Linear(hidden_size2, output_size) ) device=torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”) w=60000 l=2.7 I=0.000038929334 E=200*10**9 N2 = N2.to(device) def f(x): return -w/(E*I) def loss(x): x.requires_grad = True y = N2(x) dy_1 = torch.autograd.grad(y.sum(), x, create_graph=True)[0] dy_2 = torch.autograd.grad(dy_1.sum(), x, create_graph=True)[0] dy_3 = torch.autograd.grad(dy_2.sum(), x, create_graph=True)[0] dy_4 = torch.autograd.grad(dy_3.sum(), x, create_graph=True)[0] return torch.mean( (dy_4-f(x))**2 + (y[0, 0] - 0)**2 +(y[-1, 0] - 0)**2+(dy_2[0, 0] - 0)**2+(dy_2[-1, 0] - 0)**2 ) optimizer = torch.optim.Adam(N2.parameters(),lr=0.01) x = torch.linspace(0, l, 100)[:, None] def closure(): optimizer.zero_grad() l = loss(x) l.backward() return l epochs = 2000 for i in range(epochs): optimizer.step(closure) if(i%100==0): print(‘cost function:’,loss(x).detach().numpy()) xx = torch.linspace(0, l, 100)[:, None] with torch.no_grad(): yy = N2(xx) true_y= (w/(24EI))(-xx**4+2lxx3-l3xx) import matplotlib.pyplot as plt plt.title(‘Deflection of the Simply Supported Beam with Udl w(x)’) plt.plot(xx, true_y,c=‘blue’) plt.scatter(xx, yy,c=‘red’) plt.xlabel(‘Along The length(x)’) plt.ylabel(‘Deflection y(x)’) plt.legend([‘Analytical’,‘Deep NN’]) plt.grid() plt.show()
最新发布
03-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值