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

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

梯度下降算法推导与实现


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))
目录
打赏
0
0
0
0
6
分享
相关文章
基于Python深度学习的眼疾识别系统实现~人工智能+卷积网络算法
眼疾识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了4种常见的眼疾图像数据集(白内障、糖尿病性视网膜病变、青光眼和正常眼睛) 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Django框架搭建了一个Web网页平台可视化操作界面,实现用户上传一张眼疾图片识别其名称。
261 5
基于Python深度学习的眼疾识别系统实现~人工智能+卷积网络算法
PyTorch生态系统中的连续深度学习:使用Torchdyn实现连续时间神经网络
神经常微分方程(Neural ODEs)是深度学习领域的创新模型,将神经网络的离散变换扩展为连续时间动力系统。本文基于Torchdyn库介绍Neural ODE的实现与训练方法,涵盖数据集构建、模型构建、基于PyTorch Lightning的训练及实验结果可视化等内容。Torchdyn支持多种数值求解算法和高级特性,适用于生成模型、时间序列分析等领域。
209 77
PyTorch生态系统中的连续深度学习:使用Torchdyn实现连续时间神经网络
PyTorch PINN实战:用深度学习求解微分方程
物理信息神经网络(PINN)是一种将深度学习与物理定律结合的创新方法,特别适用于微分方程求解。传统神经网络依赖大规模标记数据,而PINN通过将微分方程约束嵌入损失函数,显著提高数据效率。它能在流体动力学、量子力学等领域实现高效建模,弥补了传统数值方法在高维复杂问题上的不足。尽管计算成本较高且对超参数敏感,PINN仍展现出强大的泛化能力和鲁棒性,为科学计算提供了新路径。文章详细介绍了PINN的工作原理、技术优势及局限性,并通过Python代码演示了其在微分方程求解中的应用,验证了其与解析解的高度一致性。
45 5
PyTorch PINN实战:用深度学习求解微分方程
基于MobileNet深度学习网络的MQAM调制类型识别matlab仿真
本项目基于Matlab2022a实现MQAM调制类型识别,使用MobileNet深度学习网络。完整程序运行效果无水印,核心代码含详细中文注释和操作视频。MQAM调制在无线通信中至关重要,MobileNet以其轻量化、高效性适合资源受限环境。通过数据预处理、网络训练与优化,确保高识别准确率并降低计算复杂度,为频谱监测、信号解调等提供支持。
基于Python深度学习的【害虫识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
害虫识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了12种常见的害虫种类数据集【"蚂蚁(ants)", "蜜蜂(bees)", "甲虫(beetle)", "毛虫(catterpillar)", "蚯蚓(earthworms)", "蜚蠊(earwig)", "蚱蜢(grasshopper)", "飞蛾(moth)", "鼻涕虫(slug)", "蜗牛(snail)", "黄蜂(wasp)", "象鼻虫(weevil)"】 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Djan
76 1
基于Python深度学习的【害虫识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
HarmonyOS NEXT 实战系列10-网络通信
本文介绍了网络通信相关知识,包括HTTP协议的工作原理、鸿蒙系统中HTTP模块的使用方法、Promise异步操作处理机制及async/await语法糖的应用,以及JSON数据格式的语法规则与转换方法。重点讲解了HTTP请求响应流程、鸿蒙开发中的网络权限申请与代码实现、Promise三种状态及创建方式,并通过示例说明异步编程技巧和JSON在数据传递中的应用。
48 10
基于MobileNet深度学习网络的活体人脸识别检测算法matlab仿真
本内容主要介绍一种基于MobileNet深度学习网络的活体人脸识别检测技术及MQAM调制类型识别方法。完整程序运行效果无水印,需使用Matlab2022a版本。核心代码包含详细中文注释与操作视频。理论概述中提到,传统人脸识别易受非活体攻击影响,而MobileNet通过轻量化的深度可分离卷积结构,在保证准确性的同时提升检测效率。活体人脸与非活体在纹理和光照上存在显著差异,MobileNet可有效提取人脸高级特征,为无线通信领域提供先进的调制类型识别方案。
Hyper V上网实战:多虚拟机网络环境配置
在Hyper-V环境中配置多虚拟机网络以实现上网功能,需完成以下步骤:1. 确认Hyper-V安装与物理网络连接正常;2. 配置虚拟交换机(外部、内部或专用)以支持不同网络需求;3. 设置虚拟机网络适配器并关联对应虚拟交换机;4. 验证虚拟机网络连接状态;5. 根据场景需求优化多虚拟机网络环境。此外,还需注意网络隔离、性能监控及数据备份等事项,确保网络安全稳定运行。
基于Python深度学习的【蘑菇识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
蘑菇识别系统,本系统使用Python作为主要开发语言,基于TensorFlow搭建卷积神经网络算法,并收集了9种常见的蘑菇种类数据集【"香菇(Agaricus)", "毒鹅膏菌(Amanita)", "牛肝菌(Boletus)", "网状菌(Cortinarius)", "毒镰孢(Entoloma)", "湿孢菌(Hygrocybe)", "乳菇(Lactarius)", "红菇(Russula)", "松茸(Suillus)"】 再使用通过搭建的算法模型对数据集进行训练得到一个识别精度较高的模型,然后保存为为本地h5格式文件。最后使用Django框架搭建了一个Web网页平台可视化操作界面,
121 11
基于Python深度学习的【蘑菇识别】系统~卷积神经网络+TensorFlow+图像识别+人工智能
Python 高级编程与实战:深入理解网络编程与异步IO
在前几篇文章中,我们探讨了 Python 的基础语法、面向对象编程、函数式编程、元编程、性能优化、调试技巧、数据科学、机器学习、Web 开发和 API 设计。本文将深入探讨 Python 在网络编程和异步IO中的应用,并通过实战项目帮助你掌握这些技术。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等