当前位置: 首页 > news >正文

php实现网站消息推送wordpress自动添加标签

php实现网站消息推送,wordpress自动添加标签,网络营销企业案例分析,装潢设计网目录 摘要 ABSTRACT 一、吴恩达机器学习exp2——逻辑回归 1、logistic函数 2、数据预处理 3、损失函数 4、梯度下降 5、设定评价指标 6、决策边界 7、正则化 二、动手深度学习pytorch——数据预处理 1、数据集读取 2、缺失值处理 3、转换为张量格式 总结 摘要…目录 摘要 ABSTRACT 一、吴恩达机器学习exp2——逻辑回归 1、logistic函数 2、数据预处理  3、损失函数 4、梯度下降 5、设定评价指标  6、决策边界 7、正则化 二、动手深度学习pytorch——数据预处理 1、数据集读取 2、缺失值处理 3、转换为张量格式 总结 摘要 本周接着上周的线性回归进一步学习了逻辑回归的完整代码不仅包含了逻辑回归模型的整个训练过程还对逻辑回归中的损失函数和梯度下降函数进行代码表达。在复习了逻辑回归模型的数学原理后对其进行代码实践并且可视化决策边界函数将自定义模型与库函数自带模型进行准确率、损失函数及其边界函数的比较。最后接着pytorch动手深度学习的内容学习了数据预处理部分。 ABSTRACT This week follows up on last weeks linear regression by further studying the complete code for logistic regression, which not only includes the entire training process of a logistic regression model, but also provides a code representation of the loss function and gradient descent function in logistic regression. After reviewing the mathematical principles of the logistic regression model, code practice on it and visualize the decision boundary function, comparing the accuracy, loss function and its boundary function of the custom model with the model that comes with the library function. Finally, the pytorch hands-on deep learning was followed by learning the data preprocessing component. 一、吴恩达机器学习exp2——逻辑回归 1、logistic函数 sigmoid函数不仅可以调用scikit-learn 库中自带的LogisticRegression模型还可以自己定义自定义及验证如下 def sigmoid(z): #定义sigmoid函数return 1 / (1 np.exp(-z))#验证sigmoid函数的正确性 nums np.arange(-10, 10, step1) #np.arange()函数返回一个有终点和起点的固定步长的排列 fig, ax plt.subplots(figsize(12,8)) ax.plot(nums, sigmoid(nums), r) plt.show() import time import matplotlib.pyplot as plt import numpy as npfrom LogisticRegression import sigmoid nums np.arange(-5, 5, step0.1) fig, ax plt.subplots(figsize(12,8)) ax.plot(nums, sigmoid(nums), r) ax.set_title(Sigmoid Function) ax.grid() plt.show() 2、数据预处理  加载数据 import pandas as pd data np.loadtxt(fnameex2data1.txt,delimiter,) data pd.read_csv(ex2data1.txt, headerNone, names[Exam 1, Exam 2, Admitted]) data.head() 查看数据集正负样本 import matplotlib.pyplot as plt import numpy as np# 将列表转换为NumPy数组 data np.array(data)#绘制数据集正负样本的散点图 fig, ax plt.subplots(figsize(12,8)) positive_data_idx np.where(data[:,2]1) positive_data data[positive_data_idx] negative_data_idx np.where(data[:, 2] 0) negative_data data[negative_data_idx] ax.scatter(xpositive_data[:, 0], ypositive_data[:, 1], s10, colorred,labelpositive) ax.scatter(xnegative_data[:, 0], ynegative_data[:, 1], s10, labelnegative) ax.set_title(Dataset) plt.legend(loc2) plt.show() 同理训练集和验证集分别的分布散点图如下 划分训练集额、验证集 from sklearn.model_selection import train_test_split train_x, val_x, train_y, val_y train_test_split(data[:, :-1], data[:, -1], test_size0.2) # train_x, val_x, train_y, val_y data[:, :-1], data[:, :-1], data[:, -1], data[:, -1]#绘制数据集中训练集和验证集的各个分数段的分布散点图 fig, ax plt.subplots(figsize(12,8)) ax.scatter(xtrain_x[:,0], ytrain_x[:,1], s10, labelTrain) ax.scatter(xval_x[:,0], yval_x[:,1], s10, colorred, labelValidation) ax.set_title(Dataset for Train and Validation) ax.legend(loc2) plt.show() 3、损失函数 定义损失函数 def cost(theta, X, y):theta np.matrix(theta)X np.matrix(X)y np.matrix(y)first np.multiply(-y, np.log(sigmoid(X * theta.T)))#这个是(100,1)乘以(100,1)就是对应相乘second np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))return np.sum(first - second) / (len(X)) 初始化参数 data.insert(0, Ones, 1) #增加一列使得矩阵相乘更容易cols data.shape[1] X data.iloc[:,0:cols-1] #训练数据 y data.iloc[:,cols-1:cols]#标签#将X、y转化为数组格式 X np.array(X.values) y np.array(y.values) theta np.zeros(3) #初始化向量theta为0 theta,X,y 检查矩阵属性和当前损失 X.shape, theta.shape, y.shape cost(theta, X, y) 4、梯度下降 定义梯度下降函数 def gradient(theta, X, y): #梯度下降theta np.matrix(theta) #将参数theta、特征值X和标签y转化为矩阵形式X np.matrix(X)y np.matrix(y)parameters int(theta.ravel().shape[1]) #.ravel()将数组维度拉成一维数组, .shape()是长度parameters指theta的下标个数grad np.zeros(parameters) error sigmoid(X * theta.T) - y #误差for i in range(parameters): #迭代的计算梯度下降term np.multiply(error, X[:,i])grad[i] np.sum(term) / len(X)return gradgradient(theta, X, y) 最优化 import scipy.optimize as opt result opt.fmin_tnc(funccost, x0theta, fprimegradient, args(X, y))#opt.fmin_tnc函数用于最优化 result 最优化后的损失 cost(result[0], X, y) 以上的1、2、3、4条都是可以自定义的函数模块把很多个功能封装到LogisticRegression类中后面逻辑回归的训练过程就是直接调用其内部的函数即可。 5、设定评价指标  定义准确率函数 def predict(theta, X): #准确率probability sigmoid(X * theta.T)return [1 if x 0.5 else 0 for x in probability]theta_min np.matrix(result[0]) predictions predict(theta_min, X) correct [1 if ((a 1 and b 1) or (a 0 and b 0)) else 0 for (a, b) in zip(predictions, y)]#zip 可以同时比较两个列表 accuracy (sum(map(int, correct)) % len(correct))#map会对列表correct的每个元素调用int函数将其转换成一个整数然后返回一个迭代器可以用来迭代所有转换后的结果 print (accuracy {0}%.format(accuracy)) #因为数据总共100 个所以准确率只加测对的就行不用除了 查看精确度、损失和F1-score  acc logistic_reg.test(val_x,val_y_ex) print(Accuracy on Test Set: {:.2f}%.format(acc * 100)) from sklearn.metrics import f1_score f1 f1_score(y_trueval_y_ex,y_predlogistic_reg.predict(val_x)) print(My F1 Score: {:.4f}.format(f1)) 调用库函数进行验证 from sklearn.linear_model import LogisticRegression sk_lr LogisticRegression(max_iter50000) sk_lr.fit(train_x,train_y) sk_pred sk_lr.predict(val_x) count np.sum(np.equal(sk_pred,val_y)) sk_acc count/val_y.shape[0] sk_prob sk_lr.predict_proba(val_x)from LogisticRegression import bce_loss sk_loss bce_loss(sk_prob[:,1], val_y_ex) sk_theta np.array([[sk_lr.intercept_[0],sk_lr.coef_[0,0],sk_lr.coef_[0,1]]]) sk_f1 f1_score(y_trueval_y_ex,y_predsk_pred) print(Sklearn Accuracy: {:.2f}%.format(sk_acc * 100)) print(Sklearn Val Loss: {:.4f}.format(sk_loss)) print(SKlearn Parameters: ,sk_theta) print(Sklearn F1 Score: {:.4f}.format(sk_f1)) 6、决策边界 绘制决策边界函数  #计算系数:结果是2*3维数组 coef -(theta/ theta[0, 2]) coef1 -(sk_theta / sk_theta[0, 2])data data.to_numpy() # 将dataframe形式的数据转化为numpy形式: 使用.to_numpy()方法x np.arange(0,100, step10) #x轴是等距刻度 y coef[0,0] coef[0,1]*x #y是自定义边界函数 y1 coef1[0,0] coef[0,1]*x #y1是调用边界函数#绘制边界函数 fig, ax plt.subplots(figsize(12,8)) ax.plot(x,y,labelMy Prediction,colorpurple) ax.plot(x,y1,labelSklearn,colororange)#绘制散点图 ax.scatter(xpositive_data[:, 0], ypositive_data[:, 1], s10, colorred,labelpositive) ax.scatter(xnegative_data[:, 0], ynegative_data[:, 1], s10, colorblue,labelnegative) ax.set_title(Decision Boundary) plt.legend(loc2) plt.show() 绘制训练过程  记录每一轮的损失值  fig, ax plt.subplots(figsize(12,8)) ax.plot(np.arange(1,epochs1), train_loss, r, labelTrain Loss) ax.plot(np.arange(1,epochs1), val_loss, b, labelVal Loss) ax.set_xlabel(Epoch) ax.set_ylabel(Loss) ax.set_title(Train Curve) plt.legend(loc2) plt.show() 7、正则化 正则化实际上就是对损失函数及梯度下降的一种改进方式它在其他数据预处理、训练过程及结果可视化的方面都都跟普通的逻辑回归没什么差别。下面仅指出不同的地方进行修改 正则化损失函数 相比于正常的损失函数多了一个正则项reg  #正则化代价函数 def costReg(theta, X, y, learningRate):theta np.matrix(theta)X np.matrix(X)y np.matrix(y)first np.multiply(-y, np.log(sigmoid(X * theta.T)))second np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))reg (learningRate / (2 * len(X))) * np.sum(np.power(theta[:,1:theta.shape[1]], 2))#注意下标 j是从1开始到n的 不包含0return np.sum(first - second) / len(X) reg 正则化梯度下降 在迭代的计算梯度的时候如果是第一次计算梯度就不需要加正则化项其余轮次需要加上正则化项 #正则化梯度下降 def gradientReg(theta, X, y, learningRate):theta np.matrix(theta)X np.matrix(X)y np.matrix(y)parameters int(theta.ravel().shape[1])grad np.zeros(parameters)error sigmoid(X * theta.T) - yfor i in range(parameters):term np.multiply(error, X[:,i])if (i 0):grad[i] np.sum(term) / len(X) #和上文一样我们这里没有执行梯度下降我们仅仅在计算一个梯度步长else:grad[i] (np.sum(term) / len(X)) ((learningRate / len(X)) * theta[:,i])return grad 决策边界可视化 fig, ax plt.subplots(figsize(12,8))# 使用更鲜明的颜色和更小的点 ax.plot(x, y, labelMy Prediction, colorpurple, linestyle--) # 虚线 ax.plot(x, y1, labelSklearn, colororange, linestyle:) # 点线 # ax.scatter(xmy_bd[:, 0], ymy_bd[:, 1], s5, coloryellow, edgecolorblack, labelMy Decision Boundary) # ax.scatter(xsk_bd[:, 0], ysk_bd[:, 1], s5, colorgray, edgecolorblack, labelSklearn Decision Boundary)# 保持正负样本点的颜色鲜艳但可以适当减小大小 ax.scatter(xpositive_data[:, 0], ypositive_data[:, 1], s20, colorred, labelpositive) ax.scatter(xnegative_data[:, 0], ynegative_data[:, 1], s20, colorblue, labelnegative)ax.set_title(Decision Boundary) ax.legend(loc2) plt.show() 二、动手深度学习pytorch——数据预处理 1、数据集读取 创建一个人工数据集并存储在CSV逗号分隔值文件 os.makedirs(os.path.join(.., data), exist_okTrue) data_file os.path.join(.., data, house_tiny.csv) with open(data_file, w) as f:f.write(NumRooms,Alley,Price\n)f.write(NA,Pave,127500\n)f.write(2,NA,106000\n)f.write(4,NA,178100\n)f.write(NA,NA,140000\n) 从创建的CSV文件中加载原始数据集 import pandas as pddata pd.read_csv(data_file) print(data) 2、缺失值处理 处理缺失值的方法有插值法和删除法下面代码以插值法为例 inputs, outputs data.iloc[:, 0:2], data.iloc[:, 2] inputs inputs.fillna(inputs.mean()) print(inputs) 3、转换为张量格式 import torchX torch.tensor(inputs.to_numpy(dtypefloat)) y torch.tensor(outputs.to_numpy(dtypefloat)) X, y 总结 本周继续完成吴恩达机器学习的实验2部分——逻辑回归 并且复习了对应的理论知识对交叉熵、梯度更新、正则化表示的数学原理进行推导并且实现在代码上pytorch学习了数据集的读取、缺失值的处理以及张量格式的转换。下周继续完成吴恩达实验并接着学习pytorch比较细致的知识点。
http://www.w-s-a.com/news/639731/

相关文章:

  • 河北省建设银行网站首页备案号怎么放到网站
  • 做电脑网站用什么软件有哪些wordpress版权修改
  • 加强部门网站建设工作wordpress文章页横幅
  • 中英网站怎么做wordpress本地音乐
  • 万网提供的网站建设服务的具体项目祥云平台网站建设
  • ftp网站怎么看后台的代码网站 制作软件
  • 网站开发软件教程网站tag 怎么实现
  • 中国建设监理协会化工监理协会网站彩票站自己做网站吗
  • 170个可带链接锚文本外链的网站论坛微信上如何创建小程序
  • 用js来做网站亳州建设局网站
  • 做网站的公司利润多少呢纺织厂网站模板
  • 网页设计构建的基本流程宜宾seo网站建设
  • 西安网站开发公司价格保定徐水网站建设
  • 学做川菜下什么网站软件著作权和专利的区别
  • 百度网站标题东莞外包公司有哪些
  • 织梦增加网站英文名称网页界面设计特点
  • 企业如何进行网站建设棋牌代理平台
  • 韩国做美食网站有哪些seo优化在线诊断
  • 网站建设规划模板做擦边网站
  • 做网站台式还是笔记本网上下载的免费网站模板怎么用
  • 高校网站群管理系统凡科建站是永久的吗
  • 深圳网站建设服务电话网站通栏设计素材
  • 网站里面的视频功能怎么做网站名注册
  • 网站游戏下载厦门php网站建设
  • 沈阳关键词网站排名一台服务器做两个网站吗
  • 哪个行业该做网站但是没有做dom手表官方网站
  • 网站建设费 大创wordpress中函数get
  • 怎样建设个自己的网站首页有没有专门教做扯面的网站
  • 网站后台怎么添加模板教育类网站开发公司
  • 网站的外链是什么php创建一个网站