吴恩达作业5:正则化和dropout

构建了三层神经网络来验证正则化和dropout对防止过拟合的作用。
首先看数据集,reg_utils.py包含产生数据集函数,前向传播,计算损失值等,代码如下: 

import numpy as np
import matplotlib.pyplot as plt
import h5py
import sklearn
import sklearn.datasets
import sklearn.linear_model
import scipy.iodef sigmoid(x):"""Compute the sigmoid of xArguments:x -- A scalar or numpy array of any size.Return:s -- sigmoid(x)"""s = 1/(1+np.exp(-x))return sdef relu(x):"""Compute the relu of xArguments:x -- A scalar or numpy array of any size.Return:s -- relu(x)"""s = np.maximum(0,x)return sdef load_planar_dataset(seed):np.random.seed(seed)m = 400 # number of examplesN = int(m/2) # number of points per classD = 2 # dimensionalityX = np.zeros((m,D)) # data matrix where each row is a single exampleY = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)a = 4 # maximum ray of the flowerfor j in range(2):ix = range(N*j,N*(j+1))t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # thetar = a*np.sin(4*t) + np.random.randn(N)*0.2 # radiusX[ix] = np.c_[r*np.sin(t), r*np.cos(t)]Y[ix] = jX = X.TY = Y.Treturn X, Ydef initialize_parameters(layer_dims):"""Arguments:layer_dims -- python array (list) containing the dimensions of each layer in our networkReturns:parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":W1 -- weight matrix of shape (layer_dims[l], layer_dims[l-1])b1 -- bias vector of shape (layer_dims[l], 1)Wl -- weight matrix of shape (layer_dims[l-1], layer_dims[l])bl -- bias vector of shape (1, layer_dims[l])Tips:- For example: the layer_dims for the "Planar Data classification model" would have been [2,2,1]. This means W1's shape was (2,2), b1 was (1,2), W2 was (2,1) and b2 was (1,1). Now you have to generalize it!- In the for loop, use parameters['W' + str(l)] to access Wl, where l is the iterative integer."""np.random.seed(3)parameters = {}L = len(layer_dims) # number of layers in the networkfor l in range(1, L):parameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) / np.sqrt(layer_dims[l-1])parameters['b' + str(l)] = np.zeros((layer_dims[l], 1))assert(parameters['W' + str(l)].shape == layer_dims[l], layer_dims[l-1])assert(parameters['W' + str(l)].shape == layer_dims[l], 1)return parametersdef forward_propagation(X, parameters):"""Implements the forward propagation (and computes the loss) presented in Figure 2.Arguments:X -- input dataset, of shape (input size, number of examples)parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":W1 -- weight matrix of shape ()b1 -- bias vector of shape ()W2 -- weight matrix of shape ()b2 -- bias vector of shape ()W3 -- weight matrix of shape ()b3 -- bias vector of shape ()Returns:loss -- the loss function (vanilla logistic loss)"""# retrieve parametersW1 = parameters["W1"]b1 = parameters["b1"]W2 = parameters["W2"]b2 = parameters["b2"]W3 = parameters["W3"]b3 = parameters["b3"]# LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOIDZ1 = np.dot(W1, X) + b1A1 = relu(Z1)Z2 = np.dot(W2, A1) + b2A2 = relu(Z2)Z3 = np.dot(W3, A2) + b3A3 = sigmoid(Z3)cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3)return A3, cachedef backward_propagation(X, Y, cache):"""Implement the backward propagation presented in figure 2.Arguments:X -- input dataset, of shape (input size, number of examples)Y -- true "label" vector (containing 0 if cat, 1 if non-cat)cache -- cache output from forward_propagation()Returns:gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables"""m = X.shape[1](Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cachedZ3 = A3 - YdW3 = 1./m * np.dot(dZ3, A2.T)db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True)dA2 = np.dot(W3.T, dZ3)dZ2 = np.multiply(dA2, np.int64(A2 > 0))dW2 = 1./m * np.dot(dZ2, A1.T)db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True)dA1 = np.dot(W2.T, dZ2)dZ1 = np.multiply(dA1, np.int64(A1 > 0))dW1 = 1./m * np.dot(dZ1, X.T)db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True)gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2,"dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1}return gradientsdef update_parameters(parameters, grads, learning_rate):"""Update parameters using gradient descentArguments:parameters -- python dictionary containing your parameters:parameters['W' + str(i)] = Wiparameters['b' + str(i)] = bigrads -- python dictionary containing your gradients for each parameters:grads['dW' + str(i)] = dWigrads['db' + str(i)] = dbilearning_rate -- the learning rate, scalar.Returns:parameters -- python dictionary containing your updated parameters """n = len(parameters) // 2 # number of layers in the neural networks# Update rule for each parameterfor k in range(n):parameters["W" + str(k+1)] = parameters["W" + str(k+1)] - learning_rate * grads["dW" + str(k+1)]parameters["b" + str(k+1)] = parameters["b" + str(k+1)] - learning_rate * grads["db" + str(k+1)]return parametersdef predict(X, y, parameters):"""This function is used to predict the results of a  n-layer neural network.Arguments:X -- data set of examples you would like to labelparameters -- parameters of the trained modelReturns:p -- predictions for the given dataset X"""m = X.shape[1]p = np.zeros((1,m), dtype = np.int)# Forward propagationa3, caches = forward_propagation(X, parameters)# convert probas to 0/1 predictionsfor i in range(0, a3.shape[1]):if a3[0,i] > 0.5:p[0,i] = 1else:p[0,i] = 0# print results#print ("predictions: " + str(p[0,:]))#print ("true labels: " + str(y[0,:]))print("Accuracy: "  + str(np.mean((p[0,:] == y[0,:]))))return pdef compute_cost(a3, Y):"""Implement the cost functionArguments:a3 -- post-activation, output of forward propagationY -- "true" labels vector, same shape as a3Returns:cost - value of the cost function"""m = Y.shape[1]logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)cost = 1./m * np.nansum(logprobs)return costdef load_dataset():train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set featurestrain_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labelstest_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set featurestest_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labelsclasses = np.array(test_dataset["list_classes"][:]) # the list of classestrain_set_y = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))test_set_y = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))train_set_x_orig = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).Ttest_set_x_orig = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).Ttrain_set_x = train_set_x_orig/255test_set_x = test_set_x_orig/255return train_set_x, train_set_y, test_set_x, test_set_y, classesdef predict_dec(parameters, X):"""Used for plotting decision boundary.Arguments:parameters -- python dictionary containing your parameters X -- input data of size (m, K)Returnspredictions -- vector of predictions of our model (red: 0 / blue: 1)"""# Predict using forward propagation and a classification threshold of 0.5a3, cache = forward_propagation(X, parameters)predictions = (a3>0.5)return predictionsdef load_planar_dataset(randomness, seed):np.random.seed(seed)m = 50N = int(m/2) # number of points per classD = 2 # dimensionalityX = np.zeros((m,D)) # data matrix where each row is a single exampleY = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)a = 2 # maximum ray of the flowerfor j in range(2):ix = range(N*j,N*(j+1))if j == 0:t = np.linspace(j, 4*3.1415*(j+1),N) #+ np.random.randn(N)*randomness # thetar = 0.3*np.square(t) + np.random.randn(N)*randomness # radiusif j == 1:t = np.linspace(j, 2*3.1415*(j+1),N) #+ np.random.randn(N)*randomness # thetar = 0.2*np.square(t) + np.random.randn(N)*randomness # radiusX[ix] = np.c_[r*np.cos(t), r*np.sin(t)]Y[ix] = jX = X.TY = Y.Treturn X, Ydef plot_decision_boundary(model, X, y):# Set min and max values and give it some paddingx_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1h = 0.01# Generate a grid of points with distance h between themxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))# Predict the function value for the whole gridZ = model(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)# Plot the contour and training examplesplt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)plt.ylabel('x2')plt.xlabel('x1')plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)plt.show()def load_2D_dataset():data = scipy.io.loadmat('datasets/data.mat')train_X = data['X'].Ttrain_Y = data['y'].Ttest_X = data['Xval'].Ttest_Y = data['yval'].T#plt.scatter(train_X[0, :], train_X[1, :], c=np.squeeze(train_Y), s=40, cmap=plt.cm.Spectral);return train_X, train_Y, test_X, test_Y

调用数据集,代码如下:

import numpy as np
import reg_utils
import matplotlib.pyplot as plt
import testCases
import sklearn
import sklearn.datasets
train_X, train_Y, test_X, test_Y=reg_utils.load_2D_dataset()
print('训练样本={}'.format(train_X.shape))
print('训练样本标签={}'.format(train_Y.shape))
print('测试样本={}'.format(test_X.shape))
plt.show()

打印结果:

第一种方法不用正则化和dropout即lambda=0,keep_prob=1,代码如下

import numpy as np
import reg_utils
import matplotlib.pyplot as plt
import testCases
import sklearn
import sklearn.datasets
train_X, train_Y, test_X, test_Y=reg_utils.load_2D_dataset()
print('训练样本={}'.format(train_X.shape))
print('训练样本标签={}'.format(train_Y.shape))
print('测试样本={}'.format(test_X.shape))
# plt.show()
"""
初始化权重 方差为2/n
"""
def initialize_parameters_he(layers_dims):L=len(layers_dims)parameters={}for i in range(1,L):parameters['W'+str(i)]=np.random.randn(layers_dims[i],layers_dims[i-1])\*np.sqrt(2.0/layers_dims[i-1])parameters['b' + str(i)]=np.zeros((layers_dims[i],1))return parameters
'''
计算损失值:带有L2正则项的损失值
'''
def compute_cost_with_regularization(A3,Y,parameters,lambd):m=Y.shape[1]W1 = parameters['W1']W2 = parameters['W2']W3 = parameters['W3']cost_entropy=reg_utils.compute_cost(A3, Y)#cost_regularize = np.sum(np.sum(np.square(Wl)) for Wl in [W1, W2, W3]) * lambd / (2 * m)cost_regularize=np.sum(np.sum(np.square(Wl)) for Wl in [W1,W2,W3])* lambd / (2 * m)cost=cost_entropy+cost_regularizereturn cost
"""
前向传播带有dropout
"""
def forward_propagation_with_dropout(X,paremeters,keep_prob):W1 = paremeters['W1']b1 = paremeters['b1']W2 = paremeters['W2']b2 = paremeters['b2']W3 = paremeters['W3']b3 = paremeters['b3']Z1=np.dot(W1,X)+b1A1=reg_utils.relu(Z1)D1=np.random.rand(A1.shape[0],A1.shape[1])#np.random.rand 输出值在0 1之间D1=(D1<keep_prob)    # 返回的是 true false#去掉A1上的一些神经元 只剩下 要的和0A1=np.multiply(A1,D1)#放大回去 确保A1的期望值不变A1=A1/keep_probZ2 = np.dot(W2, A1) + b2A2 = reg_utils.relu(Z2)D2 = np.random.rand(A2.shape[0], A2.shape[1])D2 = (D2 < keep_prob)  # 返回的是 true falseA2 = np.multiply(A2, D2)A2 = A2 / keep_probZ3 = np.dot(W3, A2) + b3A3=reg_utils.sigmoid(Z3)cache=(Z1,D1,A1,W1,b1,Z2,D2,A2,W2,b2,Z3,A3,W3,b3,)return A3,cache
'''
后向传播:带有dropout
'''
def back_propagation_with_dropout(X,Y,cache,keep_prob):m=X.shape[1](Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3,)=cachedZ3 = 1. / m * (A3 - Y)dW3 = np.dot(dZ3, A2.T)db3 = np.sum(dZ3, axis=1, keepdims=True)dA2 = np.dot(W3.T, dZ3)dA2=np.multiply(dA2,D2)dA2=dA2/keep_probdZ2 = np.multiply(dA2, np.int64(A2 > 0))dW2 = np.dot(dZ2, A1.T)db2 = np.sum(dZ2, axis=1, keepdims=True)dA1 = np.dot(W2.T, dZ2)dA1 = np.multiply(dA1, D1)dA1 = dA1 / keep_probdZ1 = np.multiply(dA1, np.int64(A1 > 0))dW1 = np.dot(dZ1, X.T)db1 = np.sum(dZ1, axis=1, keepdims=True)gradients={'dZ3':dZ3,'dW3':dW3,'db3':db3,'dA2':dA2,'dZ2':dZ2,'dW2':dW2,'db2':db2,'dA1':dA1,'dZ1':dZ1,'dW1':dW1,'db1':db1}return gradients
"""
后向传播带有L2正则项
"""
def back_propagation_with_regularization(X,Y,lambd,cache):m=X.shape[1](Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache#X,W1,A1,W2,A2,W3,A3=cachedZ3=1./m *(A3-Y)dW3=np.dot(dZ3,A2.T)+W3*(lambd/m)db3=np.sum(dZ3, axis=1, keepdims = True)dA2=np.dot(W3.T,dZ3)dZ2=np.multiply(dA2,np.int64(A2 > 0))dW2=np.dot(dZ2,A1.T)+W2*(lambd/m)#由此可看处 lambda越大 W的惩罚越大db2 = np.sum(dZ2, axis=1, keepdims=True)dA1=np.dot(W2.T,dZ2)dZ1 = np.multiply(dA1, np.int64(A1 > 0))dW1 = np.dot(dZ1, X.T) + W1 * (lambd / m)db1 = np.sum(dZ1, axis=1, keepdims=True)gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3, "dA2": dA2,"dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1,"dZ1": dZ1, "dW1": dW1, "db1": db1}return gradients
"""
构建模型
"""
def model(X,Y,num_iterations,learning_rate,lambd=0,keep_prob=1):layers_dims=[X.shape[0], 20, 3, 1]parameters=initialize_parameters_he(layers_dims)costs=[]for i in range(num_iterations):if keep_prob==1:A3, cache=reg_utils.forward_propagation(X, parameters)elif keep_prob<1:A3, cache=forward_propagation_with_dropout(X, parameters, keep_prob)if lambd==0:cost = reg_utils.compute_cost(A3, Y)else:cost=compute_cost_with_regularization(A3,Y,parameters,lambd)if lambd==0 and keep_prob==1:gradients=reg_utils.backward_propagation(X, Y, cache)elif lambd!=0:gradients=back_propagation_with_regularization(X, Y, lambd, cache)elif keep_prob<1:gradients=back_propagation_with_dropout(X,Y,cache,keep_prob)parameters=reg_utils.update_parameters(parameters, gradients, learning_rate)if i%1000==0:print('after {} iterations cost is {}'.format(i,cost))costs.append(cost)plt.plot(costs)plt.xlabel('num_iterations')plt.ylabel('costs')plt.title('learning rate is {}'.format(str(learning_rate)))plt.show()return parametersdef test():
#######test compute_cost_with_regularization# a3, Y_assess, parameters=testCases.compute_cost_with_regularization_test_case()# cost=compute_cost_with_regularization(a3, Y_assess, parameters,0.1)# print(cost)
########################
#######back_propagation_with_regularization# X_assess, Y_assess, cache=testCases.backward_propagation_with_regularization_test_case()# gradients=back_propagation_with_regularization(X_assess, Y_assess,0.7,cache)# print('dw1={} dw2={} dw3={}'.format(gradients['dW1'],gradients['dW2'],gradients['dW3']))
###################test forward_propagation_with_dropout# X_assess, parameters=testCases.forward_propagation_with_dropout_test_case()# A3, cache=forward_propagation_with_dropout(X_assess, parameters,keep_prob=0.7)# print('A3={}'.format(A3))
###################test backward_propagation_with_dropoutX_assess, Y_assess, cache=testCases.backward_propagation_with_dropout_test_case()gradients=back_propagation_with_dropout(X_assess, Y_assess, cache,keep_prob=0.8)print('dA1={}'.format(gradients['dA1']))print('dA2={}'.format(gradients['dA2']))
"""
测试模型
"""
def test_model():parameters = model(train_X, train_Y, num_iterations=30000, learning_rate=0.3, lambd=0,keep_prob=1)print('on the train sample')train_prediction=reg_utils.predict(train_X, train_Y,parameters)print('on the test sample')test_prediction = reg_utils.predict(test_X, test_Y, parameters)
if __name__=='__main__':#test()test_model()#pass

打印结果:可看出过拟合了

lambda=0.7,keep_prob=1打印结果:可看出减少了过拟合

lambda=0.keep_prob=0.86,打印结果:可看出dropout也能减少过拟合。

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/493623.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

十年之后,数字孪生将这样改变我们的工作与生活

来源&#xff1a;资本实验室数字孪生是近几年兴起的非常前沿的新技术&#xff0c;简单说就是利用物理模型&#xff0c;使用传感器获取数据的仿真过程&#xff0c;在虚拟空间中完成映射&#xff0c;以反映相对应的实体的全生命周期过程。在未来&#xff0c;物理世界中的各种事物…

什么是图像

图像&#xff0c;尤其是数字图像的定义&#xff0c;在冈萨雷斯的书中是一个二维函数f(x,y),x,y是空间平面坐标&#xff0c;幅值f是图像在该点处的灰度或者强度。下面通过OpenCV中最常用的图像表示方法Mat来看一下在计算机中是怎么定义图像的。 Mat的定义 OpenCV在2.0之后改用…

吴恩达作业6:梯度检验

梯度检验的目的就是看反向传播过程中的导数有没有较大的误差&#xff0c;首先看Jtheta*x的梯度检验&#xff1a;代码如下 import numpy as np """ Jx*theta的前向传播 """ def forward_propagation(x,theta):Jx*thetareturn J ""&quo…

10年后的计算机会是怎样的?

作者&#xff1a;孙鹏&#xff08;剑桥大学计算机系博士&#xff09;来源&#xff1a;新原理研究所上个世纪三十年代&#xff0c;邱奇和图灵共同提出了通用计算机的概念[1]。在接下来的十多年里&#xff0c;因为战争需要下的国家推动&#xff0c;计算机得以很快从理论发展成为实…

什么是图像变换

还是看OpenCV官方手册&#xff0c;我觉得这样可以同时学习如何使用函数和如何理解一些基本概念。 首先&#xff0c;这里的几何变换geometrical transformations是针对2D图像而言的&#xff0c;不改变图像内容而是将像素网格变形deform the pixel grid&#xff0c;映射到目标图…

MSRA20周年研究趋势文章|图像识别的未来:机遇与挑战并存

文/微软亚洲研究院 代季峰 林思德 郭百宁识别图像对人类来说是件极容易的事情&#xff0c;但是对机器而言&#xff0c;这也经历了漫长岁月。在计算机视觉领域&#xff0c;图像识别这几年的发展突飞猛进。例如&#xff0c;在 PASCAL VOC 物体检测基准测试中&#xff0c;检测器的…

吴恩达作业7:梯度下降优化算法

先说说BatchGD用整个训练样本进行训练得出损失值&#xff0c;SGD是只用一个训练样本训练就得出损失值&#xff0c;GD导致训练慢&#xff0c;SGD导致收敛到最小值不平滑&#xff0c;故引入Mini-batch GD&#xff0c;选取部分样本进行训练得出损失值&#xff0c; 普通梯度下降算…

什么是单应矩阵和本质矩阵

知乎上面的大牛还是很多&#xff0c;直接搜Homography或者单应矩阵就能得到很多大神的回答&#xff0c;可能回答中的一句话或者一个链接就够自己学习很久。 其实在之前研究双目视觉的时候就接触了对极几何&#xff0c;通过视觉就可以得到物体的远近信息&#xff0c;这也是特斯…

tensorflow实现反卷积

先看ogrid用法 from numpy import ogrid,repeat,newaxis from skimage import io import numpy as np size3 x,yogrid[:size,:size]#第一部分产生多行一列 第二部分产生一行多列 print(x) print(y) 打印结果&#xff1a; newaxis用法&#xff1a; """ newaxis…

寿命能推算吗?加州大学科学家提出“预测方法”

来源&#xff1a;中国科学报从古至今&#xff0c;从国内到国外&#xff0c;从炼丹术到现代科学&#xff0c;长生不老似乎一直是人类乐此不疲的追求。但若要延缓衰老&#xff0c;首先要弄清是什么造成了衰老。近日&#xff0c;加州大学洛杉矶分校&#xff08;UCLA&#xff09;生…

Deep Image Homography Estimation

在知乎问题&#xff1a;深度学习应用在哪些领域让你觉得「我去&#xff0c;这也能行&#xff01;」&#xff1f;中遇到一篇提交在arXiv 2016&#xff08;arXiv不是正式发表&#xff0c;只是可以证明原创性&#xff0c;提供时间戳的网站&#xff09;的文章《Deep Image Homograp…

tensorflow:双线性插值反卷积

首先生成333的黑色图片 """ 生成333黑色图像 """ def produce_image():size 3x, y ogrid[:size, :size] # 第一部分产生多行一列 第二部分产生一行多列z x yz z[:, :, newaxis] # 增加第三维# print(z)img repeat(z, 3, 2)/12 # 在第三…

腾讯医疗AI新突破:提出器官神经网络,全自动辅助头颈放疗规划 | 论文

来源&#xff1a;量子位腾讯医疗AI实验室又有新研究。这次跟美国加州大学合作&#xff0c;在国际权威期刊《Medical Physics》发表最新研究成果&#xff1a;《器官神经网络&#xff1a;深度学习用于快速和全自动整体头颈危及器官靶区勾画》AnatomyNet: Deep Learning for Fast …

视频制作中的绿幕与拜耳阵列

先来欣赏一些大片背后的特效。 现在国内的电影市场越来越大&#xff0c;做短视频的自媒体也越来越多&#xff0c;在他们的后期视频制作的片花中可以看到很多都在使用绿幕或者蓝幕&#xff0c;这是为什么呢&#xff1f; 首先肯定是为了抠图的方便。将主体部分抠出再将通过特效…

吴恩达作业8:三层神经网络实现手势数字的识别(基于tensorflow)

数据集的载入&#xff0c;随机产生mini-batch放在tf_utils.py,代码如下 import h5py import numpy as np import tensorflow as tf import mathdef load_dataset():train_dataset h5py.File(datasets/train_signs.h5, "r")train_set_x_orig np.array(train_datase…

基于visual Studio2013解决面试题之0307最后谁剩下

&#xfeff;&#xfeff;&#xfeff;题目解决代码及点评/* n 个数字&#xff08;0,1,…,n-1&#xff09;形成一个圆圈&#xff0c;从数字 0 开始&#xff0c;每次从这个圆圈中删除第 m 个数字&#xff08;第一个为当前数字本身&#xff0c;第二个为当前数字的下一个数字&…

谷歌、苹果等大佬亲自戳穿自动驾驶完美童话,技术、场景、安全牢笼实难突围!...

来源&#xff1a; 物联网智库摘要&#xff1a;自动驾驶普及不仅局限于自身技术和应用场景&#xff0c;而且与产业链各环节密切相关。一项科技从诞生到被人们所接受是一个循序渐进的过程&#xff0c;自动驾驶真正普及还任重而道远。2018年11月1日百度世界大会上&#xff0c;百度…

使用文件监控对象FileSystemWatcher实现数据同步

使用文件监控对象FileSystemWatcher实现数据同步 原文 使用文件监控对象FileSystemWatcher实现数据同步 最近在项目中有这么个需求&#xff0c;就是得去实时获取某个在无规律改变的文本文件中的内 容。首先想到的是用程序定期去访问这个文件&#xff0c;因为对实时性要求很高&a…

吴恩达作业11:残差网络实现手势数字的识别(基于 keras)+tensorbord显示loss值和acc值

一&#xff0c;残差网络实现手写数字识别 数据集地址&#xff1a;https://download.csdn.net/download/fanzonghao/10551018 首先来resnets_utils.py,里面有手势数字的数据集载入函数和随机产生mini-batch的函数&#xff0c;代码如下&#xff1a; import os import numpy as…

通过SVD求解单应矩阵

我们现在知道原则上4对匹配点对就可以唯一确定单应矩阵&#xff0c;但是在实际应用中我们无法保证两个视图严格满足使用条件&#xff08;只有旋转变换&#xff1b;远景&#xff1b;平面场景&#xff09;&#xff0c;所以要使用拟合的方法求一个最优解。现在就来以SIFT算法源码为…