使用PointNet++测试分类自己的数据集并可视化

我这里PointNet++的代码用的是pytorch版本的,链接为 https://github.com/yanx27/Pointnet2_pytorch

将自己的数据集格式修改为和modelnet40_normal_resampled数据集格式一样。

       由于源码中测试脚本只是输出了测试数据集的分类精确度,且测试数据集同样的是有标签的,没有模型验证脚本,由于个人实验需要,希望当模型训练完成后能用自己的无标签数据输入后输出类别去检测模型的分类效果,因此根据模型测试脚本,修改了一下代码,可以实现输入一个无标签的数据,从而输出分类结果以及可视化,从而更直观的验证模型训练的准确度。 

 代码如下,其中可视化部分参考这位博主的文章 pointconv pytorch modelnet40 点云分类结果可视化_对象被抛出的博客-CSDN博客_modelnet40可视化

from data_utils.ModelNetDataLoader_my import ModelNetDataLoader
import argparse
import numpy as np
import os
import torch
import logging
from tqdm import tqdm
import sys
import importlib
import matplotlib.pyplot as plt

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = BASE_DIR
sys.path.append(os.path.join(ROOT_DIR, 'models'))

def pc_normalize(pc):  #点云数据归一化
    centroid = np.mean(pc, axis=0)
    pc = pc - centroid
    m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
    pc = pc / m
    return pc
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(torch.cuda.is_available())
def parse_args():
    '''PARAMETERS'''
    parser = argparse.ArgumentParser('Testing')
    parser.add_argument('--use_cpu', action='store_true', default=False, help='use cpu mode')
    parser.add_argument('--gpu', type=str, default='0', help='specify gpu device')
    parser.add_argument('--batch_size', type=int, default=4, help='batch size in training')
    parser.add_argument('--num_category', default=10, type=int, choices=[10, 40],  help='training on ModelNet10/40')
    parser.add_argument('--num_point', type=int, default=10000, help='Point Number')
    parser.add_argument('--log_dir', type=str, default='pointnet2_cls_msg', help='Experiment root')
    parser.add_argument('--use_normals', action='store_true', default=False, help='use normals')
    parser.add_argument('--use_uniform_sample', action='store_true', default=False, help='use uniform sampiling')
    parser.add_argument('--num_votes', type=int, default=3, help='Aggregate classification scores with voting')
    return parser.parse_args()
#加载数据集
dataset='/home/niu/mysubject/Pointnet_Pointnet2_pytorch-master/evalset/aaa_1.txt'
pcdataset = np.loadtxt(dataset, delimiter=' ').astype(np.float32)#数据读取,我的数据是三个维度,数据之间是空格,如果是逗号修改一下即可
point_set = pcdataset[0:10000, :] #我的输入数据设置为原始数据中10000个点
point_set[:, 0:3] = pc_normalize(point_set[:, 0:3]) #归一化数据
point_set = point_set[:, 0:3] 
point_set = point_set.transpose(1,0)#将数据由N*C转换为C*N
#print(point_set.shape)
point_set = point_set.reshape(1, 3, 10000)
n_points = point_set
point_set = torch.as_tensor(point_set)#需要将数据格式变为张量,不然会报错
point_set = point_set.cuda()
#print(point_set.shape)
#print(point_set.shape)
#分类测试函数
def test(model,point_set, num_class=10, vote_num=1):
    #mean_correct = []
    classifier = model.eval()
    class_acc = np.zeros((num_class, 3))
    vote_pool = torch.zeros(1, 10).cuda()
    for _ in range(vote_num):
        pred, _ = classifier(point_set)
        print(pred)
        vote_pool += pred
    pred = vote_pool / vote_num
    # 对预测结果每行取最大值得到分类
    pred_choice = pred.data.max(1)[1]
    print(pred_choice)
    #可视化
    file_dir = '/home/niu/mysubject/Pointnet_Pointnet2_pytorch-master/visualizer'
    save_name_prefix = 'pred'
    draw(n_points[:, 0, :], n_points[:, 1, :], n_points[:, 2, :], save_name_prefix, file_dir, color=pred_choice)
    return pred_choice
#定义可视化函数
def draw(x, y, z, name, file_dir, color=None):
    """
    绘制单个样本的三维点图
    """
    if color is None:
        for i in range(len(x)):
            ax = plt.subplot(projection='3d')  # 创建一个三维的绘图工程
            save_name = name + '-{}.png'.format(i)
            save_name = os.path.join(file_dir,save_name)
            ax.scatter(x[i], y[i], z[i],s=0.1, c='r')
            ax.set_zlabel('Z')  # 坐标轴
            ax.set_ylabel('Y')
            ax.set_xlabel('X')
            plt.draw()
            plt.savefig(save_name)
            # plt.show()
    else:
        colors = ['red', 'blue', 'green', 'yellow', 'orange', 'tan', 'orangered', 'lightgreen', 'coral', 'aqua']
        for i in range(len(x)):
            ax = plt.subplot(projection='3d')  # 创建一个三维的绘图工程
            save_name = name + '-{}-{}.png'.format(i, color[i])
            save_name = os.path.join(file_dir,save_name)
            ax.scatter(x[i], y[i], z[i],s=0.1, c=colors[color[i]])
            ax.set_zlabel('Z')  # 坐标轴
            ax.set_ylabel('Y')
            ax.set_xlabel('X')
            plt.draw()
            plt.savefig(save_name)
            # plt.show()

def main(args):
    def log_string(str):
        logger.info(str)
        print(str)
    '''HYPER PARAMETER'''
    os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
    '''CREATE DIR'''
    experiment_dir = '/home/niu/mysubject/Pointnet_Pointnet2_pytorch-master/log/classification/' + args.log_dir
    '''LOG'''
    args = parse_args()
    logger = logging.getLogger("Model")
    '''
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = logging.FileHandler('%s/eval.txt' % experiment_dir)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    log_string('PARAMETER ...')
    log_string(args)
    '''
    num_class = args.num_category
    #选择模型
    model_name = os.listdir(experiment_dir + '/logs')[0].split('.')[0]
    model = importlib.import_module(model_name)
    
    classifier = model.get_model(num_class, normal_channel=args.use_normals)
    if not args.use_cpu:
        classifier = classifier.cuda()
    #选择训练好的.pth文件
    checkpoint = torch.load(str(experiment_dir) + '/checkpoints/best_model.pth')
    classifier.load_state_dict(checkpoint['model_state_dict'])
    #预测分类
    with torch.no_grad():
         pred_choice = test(classifier.eval(), point_set, vote_num=args.num_votes, num_class=num_class)
         #log_string('pred_choice: %f' % (pred_choice))

if __name__ == '__main__':
    args = parse_args()
    main(args)

用自己的数据集训练完成后,测试代码中修改训练好的.pth文件。根据自己的数据格式修改自己对应的参数以及数据集路径运行即可

分类输出结果:

输出为分类的数据类别3

 可视化结果保存在visualizer文件下,可视化结果:

  • 13
    点赞
  • 88
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
### 回答1: 好的。首先,你需要导入所需的库,如 NumPy 和 Matplotlib。你还需要使用 Scikit-learn 中的 svm 库来训练支持向量机模型,以及使用 datasets 库来加载图像数据集。 ``` import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets ``` 然后,你需要加载数据集。例如,你可以使用 Scikit-learn 自带的 digits 数据集,它包含手写数字图像。 ``` # 加载数据集 digits = datasets.load_digits() # 定义特征和标签 X = digits.data y = digits.target ``` 接下来,你可以使用 svm 库的 SVC 函数来训练支持向量机模型。你可以调整超参数,如 kernel 和 C,来调整模型的表现。 ``` # 训练支持向量机模型 model = svm.SVC(kernel='linear', C=1, gamma='auto') model.fit(X, y) ``` 最后,你可以使用 Matplotlib 库中的 pyplot 函数来可视化分类结果。 ``` # 可视化分类结果 plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired) # 绘制支持向量 ax = plt.gca() xlim = ax.get_xlim() ylim = ax.get_ylim() # 创建网格来评估模型 xx = np.linspace(xlim[0], xlim[1], 30) yy = np.linspace(ylim[0], ylim[1], 30) YY, XX = np.meshgrid(yy, xx) xy = np.vstack([XX.ravel(), YY.ravel()]).T Z = model.decision_function(xy).reshape ### 回答2: 使用Python中的机器学习库scikit-learn可以实现支持向量机(SVM)对图像数据集进行分类,并使用可视化工具matplotlib进行可视化。 首先,我们需要导入所需的库和模块: ```python import numpy as np from sklearn import svm, datasets import matplotlib.pyplot as plt ``` 然后,我们可以加载一个内置的图像数据集,比如鸢尾花数据集: ```python # 加载鸢尾花数据集 iris = datasets.load_iris() X = iris.data[:, :2] y = iris.target ``` 接下来,我们可以使用支持向量机进行分类: ```python # 创建SVM模型对象 clf = svm.SVC(kernel='linear', C=1.0) # 训练模型 clf.fit(X, y) ``` 然后,我们可以通过训练好的模型进行预测,并将数据可视化: ```python # 生成一个网格来绘制决策边界 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 h = (x_max / x_min) / 100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # 预测网格点的标签 Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # 绘制决策边界和数据点 plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.title('SVM Classification') plt.show() ``` 运行以上代码,我们将得到一个图像,其中散点表示数据点,色块表示预测的决策边界。 综上所述,通过使用Python中的scikit-learn库中的支持向量机模型和matplotlib库中的可视化工具,我们可以实现对图像数据集进行分类并进行可视化。 ### 回答3: 使用Python实现使用支持向量机(SVM)对图像数据集进行分类并进行可视化的方法如下。 步骤1:导入必要的库和模块 首先,需要导入所需的Python库和模块,如numpy、matplotlib和sklearn。确保已经安装了这些库。 步骤2:准备数据集 接下来,选择一个适当的图像数据集并加载它们。可以使用sklearn中的内置数据集,例如手写数字数据集(digits)或MNIST数据集。 步骤3:数据处理和特征提取 对数据集进行预处理和特征提取,以便将其用于SVM模型。例如,可以将图像转换为二维数组形式,并使用像素强度作为特征值。 步骤4:数据集划分 将数据集划分为训练集和测试集,以便评估训练后的SVM模型的性能。可以使用sklearn中的train_test_split函数完成此步骤。 步骤5:训练SVM模型 使用训练集数据训练SVM模型。可以使用sklearn中的SVC类创建一个SVM分类器,并使用fit方法拟合数据。 步骤6:模型评估 使用测试集数据评估训练后的SVM模型的性能。可以使用sklearn中的accuracy_score函数计算准确度或其他性能指标。 步骤7:可视化分类结果 最后,使用Matplotlib库绘制图像,并将训练后的SVM模型的分类结果可视化。可以使用imshow函数将图像和其预测的标签绘制在同一张图上,以便直观地观察分类效果。 这是一个简单的示例代码,用于使用SVM对图像数据集进行分类可视化: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import accuracy_score # 导入图像数据集 digits = load_digits() # 数据预处理和特征提取 X = digits.images.reshape((len(digits.images), -1)) y = digits.target # 数据集划分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 训练SVM模型 svm = SVC() svm.fit(X_train, y_train) # 模型评估 y_pred = svm.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("准确度:", accuracy) # 可视化分类结果 plt.figure(figsize=(8, 6)) for i, (image, target) in enumerate(zip(digits.images, digits.target)): plt.subplot(2, 5, i + 1) plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') plt.title(f'Target: {target}\nPrediction: {svm.predict([X[i]])[0]}') plt.tight_layout() plt.show() ``` 这段代码中,首先导入所需的库和模块。然后加载手写数字数据集,并对数据集进行预处理和特征提取。接下来,将数据集划分为训练集和测试集,并使用训练集数据训练SVM模型。最后,使用Matplotlib库绘制图像,并将每个图像的实际标签和预测标签显示在图像上方,以便可视化分类结果。 需要注意的是,这只是一个简单的示例,实际应用中可能需要针对具体问题进行更多的数据处理和模型调优等步骤。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值