cs231n assignment1 two layer net作业

cs231n Assignment 1# two layer net详细答案及总结 Forward pass: 这里没有任何技术上的难点,就是写了文件中loss函数中scores和loss部分。 loss函数作用就是如果传入了y就返回loss和对所有w和b的梯度,这里在traning的时候调取。 如果没有传入y,就只返回scores,在predict的时候调用。 backward pass: 这里写了loss函数中计算grads的部分,完成了loss函数的书写内容。 ... 阅读详情
from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt

class TwoLayerNet(object):
  """
  A two-layer fully-connected neural network. The net has an input dimension of
  N, a hidden layer dimension of H, and performs classification over C classes.
  We train the network with a softmax loss function and L2 regularization on the
  weight matrices. The network uses a ReLU nonlinearity after the first fully
  connected layer.

  In other words, the network has the following architecture:

  input - fully connected layer - ReLU - fully connected layer - softmax

  The outputs of the second fully-connected layer are the scores for each class.
  """

  def __init__(self, input_size, hidden_size, output_size, std=1e-4):
    """
    Initialize the model. Weights are initialized to small random values and
    biases are initialized to zero. Weights and biases are stored in the
    variable self.params, which is a dictionary with the following keys:

    W1: First layer weights; has shape (D, H)
    b1: First layer biases; has shape (H,)
    W2: Second layer weights; has shape (H, C)
    b2: Second layer biases; has shape (C,)

    Inputs:
    - input_size: The dimension D of the input data.
    - hidden_size: The number of neurons H in the hidden layer.
    - output_size: The number of classes C.
    """
    self.params = {}
    self.params['W1'] = std * np.random.randn(input_size, hidden_size)
    self.params['b1'] = np.zeros(hidden_size)
    self.params['W2'] = std * np.random.randn(hidden_size, output_size)
    self.params['b2'] = np.zeros(output_size)

  def loss(self, X, y=None, reg=0.0):
    """
    Compute the loss and gradients for a two layer fully connected neural
    network.

    Inputs:
    - X: Input data of shape (N, D). Each X[i] is a training sample.
    - y: Vector of training labels. y[i] is the label for X[i], and each y[i] is
      an integer in the range 0 <= y[i] < C. This parameter is optional; if it
      is not passed then we only return scores, and if it is passed then we
      instead return the loss and gradients.
    - reg: Regularization strength.

    Returns:
    If y is None, return a matrix scores of shape (N, C) where scores[i, c] is
    the score for class c on input X[i].

    If y is not None, instead return a tuple of:
    - loss: Loss (data loss and regularization loss) for this batch of training
      samples.
    - grads: Dictionary mapping parameter names to gradients of those parameters
      with respect to the loss function; has the same keys as self.params.
    """
    # Unpack variables from the params dictionary
    W1, b1 = self.params['W1'], self.params['b1']
    W2, b2 = self.params['W2'], self.params['b2']
    N, D = X.shape
    # Compute the forward pass
    scores = None
    #############################################################################
    # TODO: Perform the forward pass, computing the class scores for the input. #
    # Store the result in the scores variable, which should be an array of      #
    # shape (N, C).                                                             #
    #############################################################################
    # print(X.shape) (5,4)
    # print(W1.shape) (4,10) (D,H)
    # print(b1.shape) (10,)

    f1 = np.maximum(0,X.dot(W1)+b1)
    scores = f1.dot(W2)+b2
    
    #############################################################################
    #                              END OF YOUR CODE                             #
    #############################################################################
    
    # If the targets are not given then jump out, we're done
    if y is None:
      return scores

    # Compute the loss
    loss = None
    #############################################################################
    # TODO: Finish the forward pass, and compute the loss. This should include  #
    # both the data loss and L2 regularization for W1 and W2. Store the result  #
    # in the variable loss, which should be a scalar. Use the Softmax           #
    # classifier loss.                                                          #
    #############################################################################
    correct_scores = scores[np.arange(N),y]
    correct_scores = np.reshape(correct_scores,(N,-1))
    scores -= correct_scores
    correct_scores_exp = np.exp(scores[np.arange(N),y])
    scores_exp_sum = np.sum(np.exp(scores),axis=1)
    loss = -np.log(correct_scores_exp/scores_exp_sum)
    loss = np.sum(loss)
    loss = loss/N + 0.5*reg*(np.sum(W1*W1)+np.sum(W2*W2))
    #############################################################################
    #                              END OF YOUR CODE                             #
    #############################################################################

    # Backward pass: compute gradients
    grads = {}
    #############################################################################
    # TODO: Compute the backward pass, computing the derivatives of the weights #
    # and biases. Store the results in the grads dictionary. For example,       #
    # grads['W1'] should store the gradient on W1, and be a matrix of same size #
    #############################################################################
    dscores = np.exp(scores)/scores_exp_sum.reshape(N,-1)
    dscores[range(N), y] -= 1
    dscores /= N

    grads['W2'] = (f1.T).dot(dscores) + reg * W2
    grads['b2'] = np.sum(dscores, axis=0)

    df1 = dscores.dot(W2.T)
    df1[f1 <= 0] = 0
    grads['W1'] = X.T.dot(df1) + reg * W1
    grads['b1'] = np.sum(df1, axis=0)
    #############################################################################
    #                              END OF YOUR CODE                             #
    #############################################################################

    return loss, grads

  def train(self, X, y, X_val, y_val,
            learning_rate=1e-3, learning_rate_decay=0.95,
            reg=5e-6, num_iters=100,
            batch_size=200, verbose=False):
    """
    Train this neural network using stochastic gradient descent.

    Inputs:
    - X: A numpy array of shape (N, D) giving training data.
    - y: A numpy array f shape (N,) giving training labels; y[i] = c means that
      X[i] has label c, where 0 <= c < C.
    - X_val: A numpy array of shape (N_val, D) giving validation data.
    - y_val: A numpy array of shape (N_val,) giving validation labels.
    - learning_rate: Scalar giving learning rate for optimization.
    - learning_rate_decay: Scalar giving factor used to decay the learning rate
      after each epoch.
    - reg: Scalar giving regularization strength.
    - num_iters: Number of steps to take when optimizing.
    - batch_size: Number of training examples to use per step.
    - verbose: boolean; if true print progress during optimization.
    """
    num_train = X.shape[0]
    iterations_per_epoch = max(num_train / batch_size, 1)

    # Use SGD to optimize the parameters in self.model
    loss_history = []
    train_acc_history = []
    val_acc_history = []

    for it in range(num_iters):
      X_batch = None
      y_batch = None

      #########################################################################
      # TODO: Create a random minibatch of training data and labels, storing  #
      # them in X_batch and y_batch respectively.                             #
      #########################################################################
      index = np.random.choice(num_train,batch_size,replace=True)
      X_batch=X[index]
      y_batch=y[index]
      #########################################################################
      #                             END OF YOUR CODE                          #
      #########################################################################

      # Compute loss and gradients using the current minibatch
      loss, grads = self.loss(X_batch, y=y_batch, reg=reg)
      loss_history.append(loss)

      #########################################################################
      # TODO: Use the gradients in the grads dictionary to update the         #
      # parameters of the network (stored in the dictionary self.params)      #
      # using stochastic gradient descent. You'll need to use the gradients   #
      # stored in the grads dictionary defined above.                         #
      #########################################################################
      self.params['W2'] -= learning_rate * grads['W2']
      self.params['b2'] -= learning_rate * grads['b2']
      self.params['W1'] -= learning_rate * grads['W1']
      self.params['b1'] -= learning_rate * grads['b1']

      #########################################################################
      #                             END OF YOUR CODE                          #
      #########################################################################

      if verbose and it % 100 == 0:
        print('iteration %d / %d: loss %f' % (it, num_iters, loss))

      # Every epoch, check train and val accuracy and decay learning rate.
      if it % iterations_per_epoch == 0:
        # Check accuracy
        train_acc = (self.predict(X_batch) == y_batch).mean()
        val_acc = (self.predict(X_val) == y_val).mean()
        train_acc_history.append(train_acc)
        val_acc_history.append(val_acc)

        # Decay learning rate
        learning_rate *= learning_rate_decay

    return {
      'loss_history': loss_history,
      'train_acc_history': train_acc_history,
      'val_acc_history': val_acc_history,
    }

  def predict(self, X):
    """
    Use the trained weights of this two-layer network to predict labels for
    data points. For each data point we predict scores for each of the C
    classes, and assign each data point to the class with the highest score.

    Inputs:
    - X: A numpy array of shape (N, D) giving N D-dimensional data points to
      classify.

    Returns:
    - y_pred: A numpy array of shape (N,) giving predicted labels for each of
      the elements of X. For all i, y_pred[i] = c means that X[i] is predicted
      to have class c, where 0 <= c < C.
    """
    y_pred = None

    ###########################################################################
    # TODO: Implement this function; it should be VERY simple!                #
    ###########################################################################
    l1 = X.dot(self.params['W1']) + self.params['b1']
    fl1 = np.maximum(0,l1)
    l2 = fl1.dot(self.params['W2']) + self.params['b2']
    y_pred = np.argmax(l2,axis=1)
    ###########################################################################
    #                              END OF YOUR CODE                           #
    ###########################################################################

    return y_pred


best_net = None # store the best model into this 

#################################################################################
# TODO: Tune hyperparameters using the validation set. Store your best trained  #
# model in best_net.                                                            #
#                                                                               #
# To help debug your network, it may help to use visualizations similar to the  #
# ones we used above; these visualizations will have significant qualitative    #
# differences from the ones we saw above for the poorly tuned network.          #
#                                                                               #
# Tweaking hyperparameters by hand can be fun, but you might find it useful to  #
# write code to sweep through possible combinations of hyperparameters          #
# automatically like we did on the previous exercises.                          #
#################################################################################
best_hls = 0
best_lr = 0
best_reg = 0
best_accuracy= 0

hls_base =100
hls_step =5
lr_base =0.001
lr_step =0.0002
reg_base =0.25
reg_step =0.25

for hls_num in range(5):
    for lr_num in range(5):
        for reg_num in range(5):
            
            hls = hls_base + hls_num*hls_step
            lr = lr_base + lr_num*lr_step
            reg = reg_base + reg_num*reg_step
            
            net = TwoLayerNet(input_size, hls, num_classes)
            results = net.train(X_train, y_train, X_val, y_val,
                                num_iters=2000, batch_size=200,
                                learning_rate=lr, learning_rate_decay=0.95,
                                reg=reg, verbose=False)
            accuracy = np.mean(net.predict(X_val) == y_val)
            print("hls:%d, lr:%f, reg:%f, accuracy:%f"%(hls, lr, reg, accuracy))
            if accuracy > best_accuracy:
                best_accuracy = accuracy
                best_net = net
                best_hls = hls
                best_lr = lr
                best_reg = reg
print("best model is:")
print("hls:%d, lr:%f, reg:%f, accuracy:%f"%(best_hls, best_lr, best_reg, best_accuracy))







#################################################################################
#                               END OF YOUR CODE                                #
#################################################################################

 这是我得到的best_model,0.531

best model is:
hls:115, lr:0.001800, reg:0.500000, accuracy:0.531000

经过测试得到的Test accuracy:  0.525

test_acc = (best_net.predict(X_test) == y_test).mean()
print('Test accuracy: ', test_acc)

 

CS231N Assignment4 Two Layer Net CS231N Assignment4 Two Layer Net CS231N Assignment4 Two Layer Net Begin 本文主要介绍CS231N系列课程的第四项作业,写一个两层神经网络训练模型。 课程主页:网易云课堂CS231N系列课程 语言:Python3.6 1神经网络 神经网络理解起来比较简单,在线形分类器的基础上... 阅读详情

相关推荐

深度学习系列之cs231n assignment1 two_layer_net(五)

写在开头:这次是完成assignmengt1的第四个作业浅层神经网络,通过这样的浅层神经网络来感受神经网络向前计算得分与向后计算梯度更新的过程。 内容安排 今天的任务主要是搭建两层全连接层,并在中间加入Relu的操作处理,最后使用softmax的损失函数进行梯度的更新,并进行预测。在本次的任务中与上一节softmax的区别在于搭建网络和全连接层的传递,任务的loss是softmax是一样的,同...

明曦君的小家 1292

关于神经网络的权重信息和特征图的可视化

对神经网络隐藏层的可视化,以及参数权重的可视化

Henry的博客 5599

cs231n assignment1_Q4_two_layer_net

A two-layer fully-connected neural network. The net has an input dimension of N, a hidden layer dimension of H, and performs classification over C classes. We train the network with a softmax loss fu...

Sean_csy的博客 765

【深度学习 | 机器学习】干货满满 | 近万字总结了 12 个令人惊艳的神经网络可视化工具!

【深度学习 | 机器学习】干货满满 | 近万字总结了 12 个令人惊艳的神经网络可视化工具!

wzk4869的博客 8152

内存设计指南:01 Xilinx DDR4 design guide解析

最近有很多网友咨询FPGA DDR4为什么速率总是上不去的问题,发现他们的设计确实很随意,都没有遵守一些手册的基本要求,所以今天和大家一起重新读一读DDR4 design guide,看看哪些要求是一定不能忽略的。首次设计一款新的芯片或者内存方案时,可能会无从下手。对于内存设计,官方指导首推JEDEC规范,每一代内存推出时,在JEDEC官网均能找到对应的规范文档、各种内存形式的说明文档如DDR4-JESD79、DDR4 SDRAM UDIMM Design Specification以及内存条DEMO等。

halee_00的博客 3302

【迁移学习】域对抗迁移网络 DANN

Domain-Adversarial Training of Neural Networks

这个博客太懒了什么都没说 8417

神经网络 权重可视化

深度学习已经应用在各种不同的领域,并且都取得了不错的效果,但是在很多情况下,深度学习网络被我们看做一个黑匣子,我们不知道通过训练,我们的网络到底学习到了什么。今天给大家分享一个简单的权重可视化的方法,在我们训练完网络之后,可以通过权重可视化,直观的理解网络到底学习到了什么。本次实验基于MNIST数据集,通过建立一个两层的神经网络,采用softmax对数据集进行分类。训练完成之后,就可以看到网络的权...

weixin_39709476的博客 7498

基于Web的智能家居(源码+开题)

实践上,智能家居系统的普及和应用将极大改善人们的居住体验,提高生活质量,同时也有助于促进智能家居产业链的发展和完善,为社会经济发展注入新的活力。此外,本研究还将对基于Web的智能家居系统的用户体验进行深入研究,通过用户调研和数据分析,不断优化系统功能和界面设计,提升用户的使用体验和满意度。针对以上问题,本研究将综合运用物联网、云计算、大数据等新一代信息技术,通过系统架构设计、功能模块开发、安全性保障、用户体验优化等多个方面的研究工作,力求为基于Web的智能家居系统的研发和应用提供全面而有效的解决方案。

sryue06的博客 1903

CS231N作业1Two-Layer Neural Network

CS231N作业1Two-Layer Neural Network

weixin_40473318的博客 380

炼金术士的试炼:2026年企业信用信息公示系统极验五维反爬下的Python数据博弈与破局之道

企业信用信息公示系统(以下简称“公示系统”)作为国家市场监督管理总局权威发布平台,承载着全国亿万市场主体的登记、许可、处罚等核心信用数据。对于金融风控、市场分析、商业尽职调查等领域,这些数据具有不可替代的黄金价值。然而,公示系统在2025年至2026年间进行了数次史诗级的安全加固,构建了包含动态令牌、极致混淆的JavaScript混淆、无感行为指纹、智能语义验证码以及WebAssembly防护在内的“五维反爬长城”。

2201_76125261的博客 350

【100%通过率】华为OD机试真题 C++ 实现【水库蓄水问题】【2022.11 Q4 新题】

给定一个长度为 n 的整数数组height。数组的元素表示山的高度,选择两个元素作为水库的边界,求蓄水量的最大值并输出蓄水量最大时的边界下标(蓄水量相同时输出下标较近的)。

MISAYAONE的博客 1万+

cs231n作业:Assignment1- two_layer_net

from __future__ import print_function from builtins import range from builtins import object import numpy as np import matplotlib.pyplot as plt from past.builtins import xrange class TwoLayerNet(obj...

MR CODER 516

Raspberry Pi 4B 蓝牙串口(SPP)配置与使用

Linux、Android、Windows 等操作系统带有在引导期间启动的蓝牙守护进程/蓝牙服务。 对于与监视器连接并使用 GUI(如 GTK 等)运行的设备,只需多次单击即可轻松启用并连接到附近的设备。 但是在无头设备的情况下,我们必须依赖于需要在命令行上运行的不同命令。 这篇博客我们将讨论如何在无头树莓派上通过蓝牙设备连接附近。

视觉与物联智能 2745

cs231n作业:assignment1 - two_layer_net

个人博客:fangzh.top,欢迎来访 搭建一个两层的神经网络。 Forward pass 先计算前向传播过程,编辑cs231n/classifiers/neural_net.py的TwoLayerNet.loss函数 这个就和之前的svm和softmax一样了: def loss(self, X, y=None, reg=0.0): &quot;&quot;&quot; Compute the lo...

Fangzh的技术博客 2959

Qt QTableView排序

在开发过程中,我们需要通过点击表头来对QTableView或QTreeView等一系列高级视图进行排序操作,以下是进行排序的步骤。首先创建了一个QStandardItemModel对象或者继承QAbstractTableModel类作为数据模型,并设置了一些数据。然后创建一个QTableView对象,并将数据模型设置为其模型。接下来,创建一个QSortFilterProxyModel对象,并将QStandardItemModel对象设置为其源模型。然后设置QTableView开启排序功能。

希望能帮助大家,希望大家多多支持,你们的支持是我前进的动力。 2644

SOMEIP协议--第三节[SOMEIP/SD](SD格式)

Entry和Option是SD报文中最重要的内容,是服务发现功能的承载。7.Minor Version是指当前服务的小版本号,可以配置,用于给用户区分当前服务的版本用的。注意:stop offer,stop subscribe,Subscribe Nack 这三条的TTL一定设为0,唯一和offer,subscribe,Subscribe的区别。Option用来辅助Entry实现其功能,是Entry携带的附加信息,作用上一般是用来告诉对端自己业务的ip和port信息,方便对端通过ip和port发送报文。

qq_41816308的博客 1339

CS231n assignment1 -- Two-layer neural network

   作业地址:https://github.com/donghaiyu233/cs231n,欢迎fork~。    接近assignment1的尾声了,这次我们要完成的是一个两层的神经网络,要求如下:   RELU使用np.maximum()即可;   Softmax与作业上个part相同,可以直接照搬。   不同的地方在求导,两个全连接层,共有W1 b1 W2 b2四个参数。对于它们具体的计算...

donghai_yu的博客 3491

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

CS231n assignment1 Q4 Two-Layer Neural Network

网络设置: 两层的神经网络,第一层激活函数为Relu,第二层用softmax输出分类概率。使用随机梯度下降来训练。 neural_net.py from __future__ import print_function import numpy as np import matplotlib.pyplot as plt class TwoLayerNet(object): """...

weixin_30394633的博客 275

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

two layer net及cs231n作业解读

two layer net 为了让自己的cs231n学习更加高效且容易复习,特此在这里记录学习过程,以供参考和自我监督。 目录two layer net作用机制公式Assignment 1的two layer net作业two_layer_net.ipynb(1)neural_net.py 作用机制 从这节开始就要接触神经网络了,本次涉及到的是一个二层(不包括输入层)的神经网络,我们需要设计向前传播和向后传播的算法。 公式 公式的推导很麻烦,不过还是需要静下心来自己推导一遍,这样对代码的理解也更深刻。 本次

qq_49230659的博客 6890

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

【学习笔记】cs231n-assignment1-two_layer_net

前言    大家好,我是Kay,小白一个。以下是我完成斯坦福 cs231n-assignment1-two_layer_net 这份作业的做题过程、思路、踩到的哪些坑、还有一些得到的启发和心得。希望下面的文字能对所有像我这样的小白有所帮助。       两层的网络处理方法与之前的SVM/Softmax 的处理方法类似,关键在于函数和梯度的计算。 TODO1:计算 scores         【...

KammyIsTheBest的博客 2060

cs231n assignment1 two-layer-net

two-layer-net 首先完成神经网络对scores和损失函数的计算,其中激活函数使用RELU函数,即max(0,x)函数。 neural_net.py的loss()函数 # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** h1 = np.maximum(0,X.dot(W1) + b1) scores = h1.d...

SpicyCoder的博客 2213

cs231n assignment1--two_layer_net

神经网络部分。要先把理论知识搞的比较清楚才好写作业。梯度推导参考: http://www.jianshu.com/p/004c99623104multiclass 梯度推导: 调整参数部分,一开始想要把参数综合起来找一个最优参数,结果发现一次训练跑了一个小时,于是我就对每个参数进行单独训练,找到一个最好的参数,保留下来,换另一个参数。最后的测试正确率有54.8%import numpy as

zt_1995的专栏 5987

【CS231n】Spring 2020 Assignments - Assignment1 - Two Layer Net

文章目录前言1. Implementing a Neural Network1.1. TwoLayerNet.loss1.1.1. Scores1.1.2. Loss1.1.3. dW1.2. TwoLayerNet.train1.2.1 Create a random minibatch of training data and labels1.2.2. Update the parameters1.3. TwoLayerNet.predict2. Tune Your Hyperparameters总结

Mister_Yu的博客 801

CS231n Spring 2019 Assignment 1—two_layer_net/features

two_layer_net/featurestwo_layer_netfeaturesTrain SVM on featuresNeural Network on image features链接 到目前为止,作业1(assignment1)里面就剩两个ipynb作业了:two_layer_net.ipynb和features.ipynb。有了前面的基础,这两个作业并不难完成,虽然课程官网上有三...

laizi_laizi的博客 742

Stanford-CS231n-assignment1-two_layer_net附中文注释

先记录一个很好用的画神经网络图的网站:http://alexlenail.me/NN-SVG/index.html 然后因为对神经网络的几个层的名字到底应该标注在哪有点疑惑,现在看了几段代码才弄清楚,所以标注在图上记录一下,如下图(激活函数以ReLU为例),如果错误欢迎指正 神经网络各层名 上图中的神经网络可叫做双层(应该是双全连接层)神经网络或者单隐藏层(one hidden layer...

o707191418的博客 1730
上一篇: cs231n assignment1 softmax作业
下一篇: LeetCode001 Two Sum
船桥
博客等级 码龄9年 5粉丝 194原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值