mindspore的MLP模型(多层感知机)

news2024/9/24 5:23:42

导入模块

import hashlib
import os
import tarfile
import zipfile
import requests
import numpy as np
import pandas as pd
import mindspore
import mindspore.dataset as ds
from mindspore import nn
import mindspore.ops as ops
import mindspore.numpy as mnp
from mindspore import Tensor
from IPython import display
from matplotlib import pyplot as plt

数据预处理

数据下载:https://www.kaggle.com/datasets/ahsan81/hotel-reservations-classification-dataset

train_data = pd.read_csv("Hotel Reservations_train.csv")
test_data = pd.read_csv("Hotel Reservations_test.csv")

print(train_data.shape)
print(test_data.shape)
(30000, 20)
(6275, 20)
# 可去掉第0列与第1列的信息
print(train_data.iloc[0:4, [0, 1, 2, -3, -2, -1]])
   Unnamed: 0 Booking_ID  no_of_adults  avg_price_per_room  \
0           0   INN00001             2               65.00   
1           1   INN00002             2              106.68   
2           2   INN00003             1               60.00   
3           3   INN00004             2              100.00   

   no_of_special_requests booking_status  
0                       0   Not_Canceled  
1                       1   Not_Canceled  
2                       0       Canceled  
3                       0       Canceled  
# 将train_data和test_data合并,后面做数据预处理方便
all_features = pd.concat((train_data.iloc[:, 2:-1], test_data.iloc[:, 2:-1]))
 
all_features
no_of_adultsno_of_childrenno_of_weekend_nightsno_of_week_nightstype_of_meal_planrequired_car_parking_spaceroom_type_reservedlead_timearrival_yeararrival_montharrival_datemarket_segment_typerepeated_guestno_of_previous_cancellationsno_of_previous_bookings_not_canceledavg_price_per_roomno_of_special_requests
02012Meal Plan 10Room_Type 12242017102Offline00065.000
12023Not Selected0Room_Type 152018116Online000106.681
21021Meal Plan 10Room_Type 112018228Online00060.000
32002Meal Plan 10Room_Type 12112018520Online000100.000
42011Not Selected0Room_Type 1482018411Online00094.500
......................................................
62703026Meal Plan 10Room_Type 485201883Online000167.801
62712013Meal Plan 10Room_Type 122820181017Online00090.952
62722026Meal Plan 10Room_Type 1148201871Online00098.392
62732003Not Selected0Room_Type 1632018421Online00094.500
62742012Meal Plan 10Room_Type 120720181230Offline000161.670

36275 rows × 17 columns

# 将所有缺失的值替换为相应特征的平均值。 通过将特征重新缩放到零均值和单位方差来标准化数据

# 先将为数字类型的列取出来,dtypes[all_features.dtypes != 'object'].index 返回类型是数字的列的索引
numeric_features = all_features.dtypes[all_features.dtypes != 'object'].index
# 之后对其应用apply方法 apply中对每列进行了标准化(Z-score标准化方法)
all_features[numeric_features] = all_features[numeric_features].apply(
    lambda x: (x - x.mean()) / (x.std()))
# 在标准化数据之后,所有均值消失,因此我们可以将缺失值设置为0
all_features[numeric_features] = all_features[numeric_features].fillna(0)
# 处理离散值。我们用独热编码替换它们
# 独热编码:例如,“MSZoning”包含值“RL”和“Rm”。 我们将创建两个新的指示器特征“MSZoning_RL”和“MSZoning_RM”,其值为0或1。

print(all_features.shape)

# “Dummy_na=True”将“na”(缺失值)视为有效的特征值,并为其创建指示符特征
all_features = pd.get_dummies(all_features, dummy_na=True)

print(all_features.shape)
(36275, 17)
(36275, 33)
all_labels = pd.concat((train_data.iloc[:,-1], test_data.iloc[:, -1]))

change = {'Not_Canceled':1,'Canceled':0}
all_labels = all_labels.map(change)
all_labels
0       1
1       1
2       0
3       0
4       0
       ..
6270    1
6271    0
6272    1
6273    0
6274    1
Name: booking_status, Length: 36275, dtype: int64
n_train = train_data.shape[0]         # 提取训练样本数
train_features = all_features[:n_train].values.astype(np.float32)      # 注意要统一数据的类型:np.float32
test_features = all_features[n_train:].values.astype(np.float32)
train_labels = all_labels.iloc[:n_train].values.astype(np.int64)
test_labels = all_labels.iloc[n_train:].values.astype(np.int64)
class SyntheticData():  
    def __init__(self,features,labels):
        self.features, self.labels = features , labels

    def __getitem__(self, index):   # __getitem__(self, index) 一般用来迭代序列(常见序列如:列表、元组、字符串)
        return self.features[index], self.labels[index]
    
    def __len__(self):
        return len(self.labels)
# 数据集
train_dataset= ds.GeneratorDataset(source=SyntheticData(train_features, train_labels), column_names=['features', 'label'],
                                    python_multiprocessing=False)

test_dataset= ds.GeneratorDataset(source=SyntheticData(test_features, test_labels ), column_names=['features', 'label'],
                                   python_multiprocessing=False)

构建模型

class Accumulator:  
    """累加器"""
    def __init__(self, n):
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]
def accuracy(y_hat, y):  
    """计算预测正确的数量"""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:   # 判断y_hat是不是矩阵
        y_hat = y_hat.argmax(axis=1)                  # 得到每样本预测概率最大所属分类的下标
    cmp = y_hat.asnumpy() == y.asnumpy()              # y_hat.asnumpy() == y.asnumpy()返回的是一个布尔数组
    return float(cmp.sum())



def evaluate_accuracy(net, data_iter):  
    """计算在指定数据集上模型的精度"""
    metric = Accumulator(2)         # 累加器,metric[0]记录正确预测数,metric[1]记录预测总数
    for X, y in data_iter:
        metric.add(accuracy(net(X), y), y.size)
    return metric[0] / metric[1]    # 正确预测数 / 预测总数
def train_epoch( train_iter, learning_rate, weight_decay, batch_size):  
    """训练模型一个迭代周期"""
    net = nn.SequentialCell([nn.Dense(all_features.shape[1], 32),
                             nn.ReLU(),
                             nn.Dense(32, 16),
                             nn.ReLU(),
                             nn.Dense(16, 2)]) 
    
    loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
    
    #optim = nn.SGD(net.trainable_params(), learning_rate = learning_rate, weight_decay = weight_decay)
    optim = nn.Adam(net.trainable_params(), learning_rate = learning_rate, weight_decay = weight_decay) 
    
    net_with_loss = nn.WithLossCell(net, loss)                
    net_train = nn.TrainOneStepCell(net_with_loss, optim)     
    metric = Accumulator(3)
    for X, y in train_iter:
        l = net_train(X, y)
        y_hat = net(X)
        metric.add(float(l.sum().asnumpy()), accuracy(y_hat, y), y.size)
    return metric[0] / metric[2], metric[1] / metric[2] ,net      # 误差 / 预测总数 ,正确预测数 / 预测总数
def trainer( train_iter, test_iter, num_epochs, learning_rate, weight_decay, batch_size, train_acc_plot, test_acc_plot):  
    """训练模型"""
    train_iter = train_iter.batch(batch_size = batch_size, num_parallel_workers=1)
    test_iter = test_iter.batch(batch_size = batch_size, num_parallel_workers=1)
    
    for epoch in range(num_epochs):
        train_metrics = train_epoch(train_iter, learning_rate, weight_decay, batch_size)
        train_loss, train_acc, net = train_metrics
        test_acc = evaluate_accuracy(net, test_iter)
        
        train_acc_plot.append(float(train_acc))
        test_acc_plot.append(float(test_acc))
    
    print('最终训练集精度:', train_acc, '最终测试集精度:',test_acc )
        
    # 检测
    assert train_loss < 0.6, train_loss
    assert train_acc <= 1 and train_acc > 0.7, train_acc
    assert test_acc <= 1 and test_acc > 0.7, test_acc

训练

num_epochs,  weight_decay, batch_size  =20, 0, 64

# 动态学习率
learning_rate = 0.1
end_learning_rate = 0.05
decay_steps = 6
power = 0.5
learning_rate  = nn.PolynomialDecayLR(learning_rate, end_learning_rate, decay_steps, power)

train_acc_plot=[]
test_acc_plot=[]
trainer( train_dataset, test_dataset, num_epochs, learning_rate, weight_decay, batch_size, train_acc_plot, test_acc_plot)
最终训练集精度: 0.8078666666666666 最终测试集精度: 0.8124302788844622
# 构建loss-step曲线可了解loss随epoch的变化情况

plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False

x=np.linspace(0, num_epochs-1,num_epochs)

plt.figure(figsize=(4,3)) 
plt.xlabel(u"epoch")
plt.ylabel(u"精度")
plt.plot(x, train_acc_plot, label='train acc')
plt.plot(x, test_acc_plot, label='test acc')
plt.legend(loc="best")
plt.tight_layout(rect = [0,0,1,1]) 

在这里插入图片描述

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

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

相关文章

Python 内置函数eval()

Python 内置函数eval() eval(expression, globalsNone, localsNone) 函数用来执行一个字符串表达式&#xff0c;并返回表达式的值。 expression: 字符串表达式。global: 可选&#xff0c;globals必须是一个字典。locals: 可选&#xff0c;locals可以是任何映射对象。 示例 &…

微信小程序开发【壹】

随手拍拍&#x1f481;‍♂️&#x1f4f7; 日期: 2023.02.24 地点: 杭州 介绍: 2023.02.24上午十点&#xff0c;路过学院的教学楼时&#x1f3e2;&#xff0c;突然看见了一团粉红色。走进一看是一排梅花&#x1f338;&#xff0c;赶在它们凋零前&#xff0c;将它们定格在我的相…

QML 第一个应用程序Window

1.创建QML工程 新建文件或者项目-->选择Qt Quick Application 然后生成了一个默认的Window 2.main.cpp中如何加载的qml文件 QQmlApplicationEngine提供了从单个QML文件加载应用程序的便捷方式。 此类结合了QQmlEngine和QQmlComponent&#xff0c;以提供一种方便的方式加载…

用 Python 画如此漂亮的插图 ,So easy

人生苦短&#xff0c;快学Python&#xff01; 今天我们进行一次实战案例分享&#xff0c;以全球预期寿命与人均 GPD数据为例&#xff0c;写一篇 Python 中漂亮散点图的快速指南。除了正常的数据清洗/处理、还会进行简单的统计分析&#xff0c;实现数据处理-统计分析-可视化一条…

【Servlet篇】如何解决Request请求中文乱码的问题?

前言 前面一篇文章我们探讨了 Servlet 中的 Request 对象&#xff0c;Request 请求对象中封装了请求数据&#xff0c;使用相应的 API 就可以获取请求参数。 【Servlet篇】一文带你读懂 Request 对象 也许有小伙伴已经发现了前面的方式获取请求参数时&#xff0c;会出现中文乱…

【Spark分布式内存计算框架——Spark Streaming】4.入门案例(下)Streaming 工作原理

2.3 Streaming 工作原理 SparkStreaming处理流式数据时&#xff0c;按照时间间隔划分数据为微批次&#xff08;Micro-Batch&#xff09;&#xff0c;每批次数据当做RDD&#xff0c;再进行处理分析。 以上述词频统计WordCount程序为例&#xff0c;讲解Streaming工作原理。 创…

[数据结构]:06-队列(链表)(C语言实现)

目录 前言 已完成内容 队列实现 01-开发环境 02-文件布局 03-代码 01-主函数 02-头文件 03-QueueCommon.cpp 04-QueueFunction.cpp 结语 前言 此专栏包含408考研数据结构全部内容&#xff0c;除其中使用到C引用外&#xff0c;全为C语言代码。使用C引用主要是为了简化…

Spring Cache的使用--快速上手篇

系列文章目录 分页查询–Java项目实战篇 全局异常处理–Java实战项目篇 完善登录功能–过滤器的使用 更多该系列文章请查看我的主页哦 文章目录系列文章目录前言一、Spring Cache介绍二、Spring Cache的使用1. 导入依赖2. 配置信息3. 在启动类上添加注解4. 添加注解4.1 CacheP…

duboo+zookeeper分布式架构入门

分布式 dubbo Zookeeper 分布式系统就是若干独立计算机的集合&#xff08;并且这些计算机之间相互有关联&#xff0c;就像是一台计算机中的C盘F盘等&#xff09;&#xff0c;这些计算对于用户来说就是一个独立的系统。 zookeeper安装 下载地址&#xff1a;Index of /dist/z…

MyBatis——增删改查操作的实现

开启mybatis sql日志打印 可以在日志中看到sql中执行的语句 在配置文件中加上下面这几条语句 mybatis.configuration.log-implorg.apache.ibatis.logging.stdout.StdOutImpl logging.level.com.example.demodebug查询操作 根据用户id查询用户 UserMapper&#xff1a; User…

RTD2169芯片停产|完美替代RTD2169芯片|CS5260低BOM成本替代RTD2169方案设计

RTD2169芯片停产|完美替代RTD2169芯片|CS5260低BOM成本替代RTD2169方案设计 瑞昱的RTD2169芯片目前已经停产了&#xff0c; 那么之前用RTD2169来设计TYPEC转VGA方案的产品&#xff0c;该如何生产这类产品&#xff1f;且RTD2169芯片价格较贵&#xff0c;芯片封装尺寸是QFN40&…

JS函数的4种调用方式

函数可以声明定义&#xff0c;也可以是一个表达式&#xff0c;函数使用关键字function定义函数被定义时&#xff0c;函数内部的代码不会执行函数被调用时&#xff0c;函数内部的代码才会执行函数有四种调用方式&#xff0c;每种方式的不同在于this的初始化。&#xff08;this是…

HTML#1快速入门

一. 简介HTML是一门语言, 所有的网页都是用HTML编写的HTML(Hyper Text Markup Language): 超文本(超越了文本限制,除了文字信息还可以定义图片,音频,视频等)标记语言(有标签构成的语言)W3C标准: 网页主要由三部分组成(1) 结构: HTML(2) 表现: CSS(3) 行为: JavaScript二. 快速入…

optional说明

1.说明 public final class Optional<T> extends Object 可能包含或不包含非空值的容器对象。 如果一个值存在&#xff0c; isPresent()将返回true和get()将返回值。 提供依赖于存在或不存在包含值的其他方法&#xff0c;例如orElse() &#xff08;如果值不存在则返回…

印度这事真的干的挺棒的! |

来源&#xff1a;statista最近逛外网看到一张图&#xff0c;是关于印度家庭自来水供应的对比图。Crore是印度的单位千万(卢比)&#xff0c;所以他们从2019年供应3.23千万家庭&#xff0c;增长到了2022年的9.57万家庭&#xff0c;印度这事真的干的挺棒的&#xff01;一直以来印度…

【USB】windows热插拔通知接口分析

文章目录接口介绍概述过滤器介绍举例接收通知创建窗口参考文档接口介绍 概述 window提供了RegisterDeviceNotificationW方法&#xff0c;可以用来监听设备的热插拔事件。 HDEVNOTIFY RegisterDeviceNotificationW([in] HANDLE hRecipient,[in] LPVOID NotificationFilter,[in]…

Android 多种支付方式的优雅实现

场景App 的支付流程&#xff0c;添加多种支付方式&#xff0c;不同的支付方式&#xff0c;对应的操作不一样&#xff0c;有的会跳转到一个新的webview&#xff0c;有的会调用系统浏览器&#xff0c;有的会进去一个新的表单页面&#xff0c;等等。并且可以添加的支付方式也是不确…

计算机网络-网络核心(day02)

网络核心 最主要的功能&#xff1a; 数据交换的功能 转发&#xff0c;路由 主要分为线路交换&#xff0c;分组交换 线路交换 可以认为所有的电话通信都是线路交换 线路交换&#xff0c;比如打电话&#xff0c;需要先建立连接&#xff08;主机要经过哪些链路哪些交换机&#…

软件测试之因果图法

因果图法 1. 概述 因果图法是一种**利用图解法分析输入条件、输出结果的各种组合情况,**从而设计测试用例的方法. 因果图法适用于有多个输入和多个输出&#xff0c;而且输入和输入之间有相互的组合关系&#xff0c;输入和输出之间有相互的制约和依赖关系. 使用场景和判定表…

第一个 Spring MVC 注解式开发案例(初学必看)

✅作者简介&#xff1a;2022年博客新星 第八。热爱国学的Java后端开发者&#xff0c;修心和技术同步精进。 &#x1f34e;个人主页&#xff1a;Java Fans的博客 &#x1f34a;个人信条&#xff1a;不迁怒&#xff0c;不贰过。小知识&#xff0c;大智慧。 &#x1f49e;当前专栏…