优达学城深度学习之五——卷积神经网络代码实现及实战演练

简介: 优达学城深度学习之五——卷积神经网络代码实现及实战演练

梯度下降算法推导与实现


df5a6f8a7384c8e0fdc21d18573f2087.jpg

importmatplotlib.pyplotaspltimportnumpyasnpimportpandasaspd#Some helper functions for plotting and drawing linesdefplot_points(X, y):
admitted=X[np.argwhere(y==1)]
rejected=X[np.argwhere(y==0)]
plt.scatter([s[0][0] forsinrejected], [s[0][1] forsinrejected], s=25, color='blue', edgecolor='k')
plt.scatter([s[0][0] forsinadmitted], [s[0][1] forsinadmitted], s=25, color='red', edgecolor='k')
defdisplay(m, b, color='g--'):
plt.xlim(-0.05,1.05)
plt.ylim(-0.05,1.05)
x=np.arange(-10, 10, 0.1)
plt.plot(x, m*x+b, color)
#读取与绘制数据data=pd.read_csv('data.csv', header=None)
X=np.array(data[[0,1]])
y=np.array(data[2])
plot_points(X,y)
plt.show()
# Implement the following functions# Activation (sigmoid) functiondefsigmoid(x):
return1/(1+np.exp(-x))
# Output (prediction) formuladefoutput_formula(features, weights, bias):
sigmoid(np.dot(features, weights) +bias)
# Error (log-loss) formuladeferror_formula(y, output):
return-y*np.log(output) - (1-y) *np.log(1-output)
# Gradient descent stepdefupdate_weights(x, y, weights, bias, learnrate):
output=output_formula(x, weights, bias)
d_error=-(y-output)
weights-=learnrate*d_error*xbias-=learnrate*d_errorreturnweights, biasnp.random.seed(44)
epochs=100learnrate=0.01deftrain(features, targets, epochs, learnrate, graph_lines=False):
errors= []
n_records, n_features=features.shapelast_loss=Noneweights=np.random.normal(scale=1/n_features**.5, size=n_features)
bias=0foreinrange(epochs):
del_w=np.zeros(weights.shape)
forx, yinzip(features, targets):
output=output_formula(x, weights, bias)
error=error_formula(y, output)
weights, bias=update_weights(x, y, weights, bias, learnrate)
# Printing out the log-loss error on the training setout=output_formula(features, weights, bias)
loss=np.mean(error_formula(targets, out))
errors.append(loss)
ife% (epochs/10) ==0:
print("\n========== Epoch", e,"==========")
iflast_lossandlast_loss<loss:
print("Train loss: ", loss, "  WARNING - Loss Increasing")
else:
print("Train loss: ", loss)
last_loss=losspredictions=out>0.5accuracy=np.mean(predictions==targets)
print("Accuracy: ", accuracy)
ifgraph_linesande% (epochs/100) ==0:
display(-weights[0]/weights[1], -bias/weights[1])
# Plotting the solution boundaryplt.title("Solution boundary")
display(-weights[0]/weights[1], -bias/weights[1], 'black')
# Plotting the dataplot_points(features, targets)
plt.show()
# Plotting the errorplt.title("Error Plot")
plt.xlabel('Number of epochs')
plt.ylabel('Error')
plt.plot(errors)
plt.show()
#训练算法train(X, y, epochs, learnrate, True)

反向传播


反向传播流程如下:

  • 进行前向反馈运算。
  • 将模型的输出与期望的输出进行比较。
  • 计算误差。
  • 向后运行前向反馈运算(反向传播),将误差分散到每个权重上。
  • 更新权重,并获得更好的模型。
  • 继续此流程,直到获得很好的模型。

2c5d8b5be881dcae483157006a54dc71.jpg

实战演练:利用神经网络来预测学生录取情况


数据集来源: http://www.ats.ucla.edu/

# Importing pandas and numpyimportpandasaspdimportnumpyasnp# Reading the csv file into a pandas DataFramedata=pd.read_csv('student_data.csv')
# Printing out the first 10 rows of our datadata[:10]
#绘制数据# Importing matplotlibimportmatplotlib.pyplotasplt%matplotlibinline# Function to help us plotdefplot_points(data):
X=np.array(data[["gre","gpa"]])
y=np.array(data["admit"])
admitted=X[np.argwhere(y==1)]
rejected=X[np.argwhere(y==0)]
plt.scatter([s[0][0] forsinrejected], [s[0][1] forsinrejected], s=25, color='red', edgecolor='k')
plt.scatter([s[0][0] forsinadmitted], [s[0][1] forsinadmitted], s=25, color='cyan', edgecolor='k')
plt.xlabel('Test (GRE)')
plt.ylabel('Grades (GPA)')
# Plotting the pointsplot_points(data)
plt.show()
# Separating the ranksdata_rank1=data[data["rank"]==1]
data_rank2=data[data["rank"]==2]
data_rank3=data[data["rank"]==3]
data_rank4=data[data["rank"]==4]
# Plotting the graphsplot_points(data_rank1)
plt.title("Rank 1")
plt.show()
plot_points(data_rank2)
plt.title("Rank 2")
plt.show()
plot_points(data_rank3)
plt.title("Rank 3")
plt.show()
plot_points(data_rank4)
plt.title("Rank 4")
plt.show()
#将评级进行one-shot编码# TODO:  Make dummy variables for rankone_hot_data=pd.concat([data, pd.get_dummies(data['rank'], prefix='rank')], axis=1)
# TODO: Drop the previous rank columnone_hot_data=one_hot_data.drop('rank', axis=1)
# Print the first 10 rows of our dataone_hot_data[:10]
#缩放数据# Making a copy of our dataprocessed_data=one_hot_data[:]
# TODO: Scale the columnsprocessed_data['gre']=processed_data['gre']/800processed_data['gpa']=processed_data['gpa']/4.0# Printing the first 10 rows of our procesed dataprocessed_data[:10]
#将数据分成训练集和测试集sample=np.random.choice(processed_data.index, size=int(len(processed_data)*0.9), replace=False)
train_data, test_data=processed_data.iloc[sample], processed_data.drop(sample)
print("Number of training samples is", len(train_data))
print("Number of testing samples is", len(test_data))
print(train_data[:10])
print(test_data[:10])
#将数据分成特征和目标features=train_data.drop('admit', axis=1)
targets=train_data['admit']
features_test=test_data.drop('admit', axis=1)
targets_test=test_data['admit']
print(features[:10])
print(targets[:10])
#训练二层神经网络Activation (sigmoid) functiondefsigmoid(x):
return1/ (1+np.exp(-x))
defsigmoid_prime(x):
returnsigmoid(x) * (1-sigmoid(x))
deferror_formula(y, output):
return-y*np.log(output) - (1-y) *np.log(1-output)
#误差反向传播# TODO: Write the error term formuladeferror_term_formula(y, output):
return (y-output)*sigmoid_prime(x)
deferror_term_formula(x, y, output):
return (y-output) *output* (1-output)
# Neural Network hyperparametersepochs=1000learnrate=0.5# Training functiondeftrain_nn(features, targets, epochs, learnrate):
# Use to same seed to make debugging easiernp.random.seed(42)
n_records, n_features=features.shapelast_loss=None# Initialize weightsweights=np.random.normal(scale=1/n_features**.5, size=n_features)
foreinrange(epochs):
del_w=np.zeros(weights.shape)
forx, yinzip(features.values, targets):
# Loop through all records, x is the input, y is the target# Activation of the output unit#   Notice we multiply the inputs and the weights here #   rather than storing h as a separate variable output=sigmoid(np.dot(x, weights))
# The error, the target minus the network outputerror=error_formula(y, output)
# The error term#   Notice we calulate f'(h) here instead of defining a separate#   sigmoid_prime function. This just makes it faster because we#   can re-use the result of the sigmoid function stored in#   the output variableerror_term=error_term_formula(x,y, output)
# The gradient descent step, the error times the gradient times the inputsdel_w+=error_term*x# Update the weights here. The learning rate times the # change in weights, divided by the number of records to averageweights+=learnrate*del_w/n_records# Printing out the error on the training setife% (epochs/10) ==0:
out=sigmoid(np.dot(features, weights))
loss=np.mean((out-targets) **2)
print("Epoch:", e)
iflast_lossandlast_loss<loss:
print("Train loss: ", loss, "  WARNING - Loss Increasing")
else:
print("Train loss: ", loss)
last_loss=lossprint("=========")
print("Finished training!")
returnweightsweights=train_nn(features, targets, epochs, learnrate)
#计算测试数据的准确度# Calculate accuracy on test datates_out=sigmoid(np.dot(features_test, weights))
predictions=tes_out>0.5accuracy=np.mean(predictions==targets_test)
print("Prediction accuracy: {:.3f}".format(accuracy))
相关文章
|
传感器 机器学习/深度学习 算法
【UASNs、AUV】无人机自主水下传感网络中遗传算法的路径规划问题研究(Matlab代码实现)
【UASNs、AUV】无人机自主水下传感网络中遗传算法的路径规划问题研究(Matlab代码实现)
384 0
|
机器学习/深度学习 数据采集 人工智能
深度学习实战指南:从神经网络基础到模型优化的完整攻略
🌟 蒋星熠Jaxonic,AI探索者。深耕深度学习,从神经网络到Transformer,用代码践行智能革命。分享实战经验,助你构建CV、NLP模型,共赴二进制星辰大海。
|
机器学习/深度学习 传感器 算法
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
864 2
|
机器学习/深度学习 数据采集 存储
概率神经网络的分类预测--基于PNN的变压器故障诊断(Matlab代码实现)
概率神经网络的分类预测--基于PNN的变压器故障诊断(Matlab代码实现)
1813 92
|
机器学习/深度学习 人工智能 算法
【基于TTNRBO优化DBN回归预测】基于瞬态三角牛顿-拉夫逊优化算法(TTNRBO)优化深度信念网络(DBN)数据回归预测研究(Matlab代码实现)
【基于TTNRBO优化DBN回归预测】基于瞬态三角牛顿-拉夫逊优化算法(TTNRBO)优化深度信念网络(DBN)数据回归预测研究(Matlab代码实现)
573 0
|
传感器 机器学习/深度学习 数据采集
【航空发动机寿命预测】基于SE-ResNet网络的发动机寿命预测,C-MAPSS航空发动机寿命预测研究(Matlab代码实现)
【航空发动机寿命预测】基于SE-ResNet网络的发动机寿命预测,C-MAPSS航空发动机寿命预测研究(Matlab代码实现)
730 0
|
机器学习/深度学习 人工智能 PyTorch
零基础入门CNN:聚AI卷积神经网络核心原理与工业级实战指南
卷积神经网络(CNN)通过局部感知和权值共享两大特性,成为计算机视觉的核心技术。本文详解CNN的卷积操作、架构设计、超参数调优及感受野计算,结合代码示例展示其在图像分类、目标检测等领域的应用价值。
898 7
|
机器学习/深度学习 传感器 数据采集
基于贝叶斯优化CNN-LSTM混合神经网络预测(Matlab代码实现)
基于贝叶斯优化CNN-LSTM混合神经网络预测(Matlab代码实现)
1529 0
|
机器学习/深度学习 传感器 数据采集
【故障识别】基于CNN-SVM卷积神经网络结合支持向量机的数据分类预测研究(Matlab代码实现)
【故障识别】基于CNN-SVM卷积神经网络结合支持向量机的数据分类预测研究(Matlab代码实现)
737 0
|
机器学习/深度学习 数据采集 TensorFlow
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
803 0