GCN图卷积 utils.py脚本

本文介绍GCN图卷积网络中数据处理的方法,包括数据加载、特征矩阵和邻接矩阵预处理等关键步骤,适用于理解GCN如何处理图数据并将其转换为适合模型输入的形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GCN图卷积 utils.py脚本
把带#注释掉的部分取消,打印一些数据,就能理解GCN是怎么处理数据的,也有助于将自己的数据转变成与它类似的形式。

import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys


def parse_index_file(filename):
    """Parse index file."""
    index = []
    for line in open(filename):
        index.append(int(line.strip()))
    return index


def sample_mask(idx, l):
    """Create mask."""
    mask = np.zeros(l)
    mask[idx] = 1
    return np.array(mask, dtype=np.bool)


def load_data(dataset_str):
    """
    Loads input data from gcn/data directory

    ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object;
    ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object;
    ind.dataset_str.allx => the feature vectors of both labeled and unlabeled training instances
        (a superset of ind.dataset_str.x) as scipy.sparse.csr.csr_matrix object;
    ind.dataset_str.y => the one-hot labels of the labeled training instances as numpy.ndarray object;
    ind.dataset_str.ty => the one-hot labels of the test instances as numpy.ndarray object;
    ind.dataset_str.ally => the labels for instances in ind.dataset_str.allx as numpy.ndarray object;
    ind.dataset_str.graph => a dict in the format {index: [index_of_neighbor_nodes]} as collections.defaultdict
        object;
    ind.dataset_str.test.index => the indices of test instances in graph, for the inductive setting as list object.

    All objects above must be saved using python pickle module.

    :param dataset_str: Dataset name
    :return: All data input files loaded (as well the training/test data).
    """
    names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
    objects = []
    for i in range(len(names)):
        with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
            if sys.version_info > (3, 0):
                data = pkl.load(f, encoding='latin1')
                # if(names[i].find('graph')==-1):
                #     print(f)
                #     print(data.shape)
                #     for j in range(data.shape[0]):
                #         print('********',names[i],j,data[j].shape,'**********')
                #         print(data[j])
                # else:
                #     print(f)
                #     print(data)
                objects.append(data)

            else:
                objects.append(pkl.load(f))

    x, y, tx, ty, allx, ally, graph = tuple(objects)

    #测试数据集
    # print(x[0][0],x.shape,type(x))  ##x是一个稀疏矩阵,记住1的位置,140个实例,每个实例的特征向量维度是1433  (140,1433)
    # print(y[0],y.shape)   ##y是标签向量,7分类,140个实例 (140,7)

    ##训练数据集
    # print(tx[0][0],tx.shape,type(tx))  ##tx是一个稀疏矩阵,1000个实例,每个实例的特征向量维度是1433  (1000,1433)
    # print(ty[0],ty.shape)   ##y是标签向量,7分类,1000个实例 (1000,7)

    ##allx,ally和上面的形式一致
    # print(allx[0][0],allx.shape,type(allx))  ##tx是一个稀疏矩阵,1708个实例,每个实例的特征向量维度是1433  (1708,1433)
    # print(ally[0],ally.shape)   ##y是标签向量,7分类,1708个实例 (1708,7)


    ##graph是一个字典,大图总共2708个节点
    # for i in graph:
    #     print(i,graph[i])


    test_idx_reorder = parse_index_file("data/ind.{}.test.index".format(dataset_str))
    test_idx_range = np.sort(test_idx_reorder)

    # print(test_idx_range)

    if dataset_str == 'citeseer':
        # Fix citeseer dataset (there are some isolated nodes in the graph)
        # Find isolated nodes, add them as zero-vecs into the right position
        test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)
        tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
        tx_extended[test_idx_range-min(test_idx_range), :] = tx
        tx = tx_extended
        ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))
        ty_extended[test_idx_range-min(test_idx_range), :] = ty
        ty = ty_extended

    features = sp.vstack((allx, tx)).tolil()
    features[test_idx_reorder, :] = features[test_idx_range, :]
    adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
    # print(adj,adj.shape)

    labels = np.vstack((ally, ty))
    labels[test_idx_reorder, :] = labels[test_idx_range, :]

    idx_test = test_idx_range.tolist()
    idx_train = range(len(y))
    idx_val = range(len(y), len(y)+500)

    train_mask = sample_mask(idx_train, labels.shape[0])
    val_mask = sample_mask(idx_val, labels.shape[0])
    test_mask = sample_mask(idx_test, labels.shape[0])

    y_train = np.zeros(labels.shape)
    y_val = np.zeros(labels.shape)
    y_test = np.zeros(labels.shape)
    y_train[train_mask, :] = labels[train_mask, :]
    y_val[val_mask, :] = labels[val_mask, :]
    y_test[test_mask, :] = labels[test_mask, :]
    

    return adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask


def sparse_to_tuple(sparse_mx):
    """Convert sparse matrix to tuple representation."""
    def to_tuple(mx):
        if not sp.isspmatrix_coo(mx):
            mx = mx.tocoo()
        coords = np.vstack((mx.row, mx.col)).transpose()
        values = mx.data
        shape = mx.shape
        return coords, values, shape

    if isinstance(sparse_mx, list):
        for i in range(len(sparse_mx)):
            sparse_mx[i] = to_tuple(sparse_mx[i])
    else:
        sparse_mx = to_tuple(sparse_mx)

    return sparse_mx


def preprocess_features(features):
    """Row-normalize feature matrix and convert to tuple representation"""
    rowsum = np.array(features.sum(1))
    r_inv = np.power(rowsum, -1).flatten()
    r_inv[np.isinf(r_inv)] = 0.
    r_mat_inv = sp.diags(r_inv)
    features = r_mat_inv.dot(features)
    return sparse_to_tuple(features)


def normalize_adj(adj):
    """Symmetrically normalize adjacency matrix."""
    adj = sp.coo_matrix(adj)
    rowsum = np.array(adj.sum(1))
    d_inv_sqrt = np.power(rowsum, -0.5).flatten()
    d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
    d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
    return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()


def preprocess_adj(adj):
    """Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
    adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))
    return sparse_to_tuple(adj_normalized)


def construct_feed_dict(features, support, labels, labels_mask, placeholders):
    """Construct feed dictionary."""
    feed_dict = dict()
    feed_dict.update({placeholders['labels']: labels})
    feed_dict.update({placeholders['labels_mask']: labels_mask})
    feed_dict.update({placeholders['features']: features})
    feed_dict.update({placeholders['support'][i]: support[i] for i in range(len(support))})
    feed_dict.update({placeholders['num_features_nonzero']: features[1].shape})
    return feed_dict


def chebyshev_polynomials(adj, k):
    """Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation)."""
    print("Calculating Chebyshev polynomials up to order {}...".format(k))

    adj_normalized = normalize_adj(adj)
    laplacian = sp.eye(adj.shape[0]) - adj_normalized
    largest_eigval, _ = eigsh(laplacian, 1, which='LM')
    scaled_laplacian = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])

    t_k = list()
    t_k.append(sp.eye(adj.shape[0]))
    t_k.append(scaled_laplacian)

    def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):
        s_lap = sp.csr_matrix(scaled_lap, copy=True)
        return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two

    for i in range(2, k+1):
        t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))

    return sparse_to_tuple(t_k)


load_data('cora')

 

. ├── cliff_distance_measurement │ ├── CMakeLists.txt │ ├── include │ │ └── cliff_distance_measurement │ ├── package.xml │ └── src │ ├── core │ ├── ir_ranging.cpp │ └── platform ├── robot_cartographer │ ├── config │ │ └── fishbot_2d.lua │ ├── map │ │ ├── fishbot_map.pgm │ │ └── fishbot_map.yaml │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_cartographer │ ├── robot_cartographer │ │ ├── __init__.py │ │ └── robot_cartographer.py │ ├── rviz │ ├── setup.cfg │ └── setup.py ├── robot_control_service │ ├── bash │ │ └── pwm_control_setup.sh │ ├── CMakeLists.txt │ ├── config │ │ └── control_params.yaml │ ├── include │ │ └── robot_control_service │ ├── package.xml │ ├── readme.md │ └── src │ ├── control_client_camera.cpp │ ├── control_client_cliff.cpp │ ├── control_client_ir.cpp │ ├── control_client_ir_four.cpp │ ├── control_client_master.cpp │ ├── control_client_ros.cpp │ ├── control_client_ultrasonic.cpp │ ├── control_service.cpp │ ├── DirectMotorControl.cpp │ ├── PIDControl.cpp │ ├── publisher_control_view.cpp │ └── publisher_human_realized.cpp ├── robot_control_view │ ├── config │ │ └── icare_robot.rviz │ ├── __init__.py │ ├── launch │ │ └── start_init_view.launch.py │ ├── package.xml │ ├── resource │ │ └── robot_control_view │ ├── robot_control_view │ │ ├── app │ │ ├── blood_oxygen_pulse │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── robot_automatic_cruise_server.py │ │ ├── robot_automatic_recharge_server.py │ │ ├── robot_automatic_slam_server.py │ │ ├── robot_blood_oxygen_pulse.py │ │ ├── robot_city_locator_node.py │ │ ├── robot_control_policy_server.py │ │ ├── robot_local_websocket.py │ │ ├── robot_log_clear_node.py │ │ ├── robot_main_back_server.py │ │ ├── robot_network_publisher.py │ │ ├── robot_network_server.py │ │ ├── robot_odom_publisher.py │ │ ├── robot_speech_server.py │ │ ├── robot_system_info_node.py │ │ ├── robot_ultrasonic_policy_node.py │ │ ├── robot_view_manager_node.py │ │ ├── robot_websockets_client.py │ │ ├── robot_websockets_server.py │ │ ├── robot_wifi_server_node.py │ │ ├── start_account_view.py │ │ ├── start_bluetooth_view.py │ │ ├── start_chat_view.py │ │ ├── start_clock_view.py │ │ ├── start_feedback_view.py │ │ ├── start_health_view.py │ │ ├── start_init_view.py │ │ ├── start_lifecycle_view.py │ │ ├── start_main_view.py │ │ ├── start_member_view.py │ │ ├── start_movie_view.py │ │ ├── start_music_view.py │ │ ├── start_radio_view.py │ │ ├── start_schedule_view.py │ │ ├── start_setting_view.py │ │ ├── start_test_view.py │ │ ├── start_view_manager.py │ │ ├── start_weather_view.py │ │ └── start_wifi_view.py │ ├── setup.cfg │ ├── setup.py │ ├── test │ │ ├── my_test.py │ │ ├── test_copyright.py │ │ ├── test_flake8.py │ │ └── test_pep257.py │ └── urdf │ ├── first_robot.urdf.xacro │ ├── fishbot.urdf │ ├── fishbot.urdf.xacro │ ├── fist_robot.urdf │ ├── icare_robot.urdf │ ├── icare_robot.urdf.xacro │ ├── ramand.md │ └── xacro_template.xacro ├── robot_costmap_filters │ ├── CMakeLists.txt │ ├── include │ │ └── robot_costmap_filters │ ├── launch │ │ ├── start_costmap_filter_info_keepout.launch.py │ │ ├── start_costmap_filter_info.launch.py │ │ └── start_costmap_filter_info_speedlimit.launch.py │ ├── package.xml │ ├── params │ │ ├── filter_info.yaml │ │ ├── filter_masks.yaml │ │ ├── keepout_mask.pgm │ │ ├── keepout_mask.yaml │ │ ├── keepout_params.yaml │ │ ├── speedlimit_params.yaml │ │ ├── speed_mask.pgm │ │ └── speed_mask.yaml │ ├── readme.md │ └── src ├── robot_description │ ├── launch │ │ └── gazebo.launch.py │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_description │ ├── robot_description │ │ └── __init__.py │ ├── rviz │ │ └── urdf_config.rviz │ ├── setup.cfg │ ├── setup.py │ ├── urdf │ │ ├── fishbot_gazebo.urdf │ │ ├── fishbot_v0.0.urdf │ │ ├── fishbot_v1.0.0.urdf │ │ ├── test.urdf │ │ └── three_wheeled_car_model.urdf │ └── worlds │ └── empty_world.world ├── robot_interfaces │ ├── CMakeLists.txt │ ├── include │ │ └── robot_interfaces │ ├── msg │ │ ├── AlarmClockMsg.msg │ │ ├── CameraMark.msg │ │ ├── DualRange.msg │ │ ├── HuoerSpeed.msg │ │ ├── IrSensorArray.msg │ │ ├── IrSignal.msg │ │ ├── NavigatorResult.msg │ │ ├── NavigatorStatus.msg │ │ ├── NetworkDataMsg.msg │ │ ├── PoseData.msg │ │ ├── RobotSpeed.msg │ │ ├── SensorStatus.msg │ │ ├── TodayWeather.msg │ │ └── WifiDataMsg.msg │ ├── package.xml │ ├── readme.md │ ├── src │ └── srv │ ├── LightingControl.srv │ ├── MotorControl.srv │ ├── NewMotorControl.srv │ ├── SetGoal.srv │ ├── StringPair.srv │ ├── String.srv │ └── VoicePlayer.srv ├── robot_launch │ ├── config │ │ └── odom_imu_ekf.yaml │ ├── launch │ │ ├── start_all_base_sensor.launch.py │ │ ├── start_cartographer.launch.py │ │ ├── start_control_service.launch.py │ │ ├── start_navigation.launch.py │ │ ├── start_navigation_service.launch.py │ │ ├── start_navigation_speed_mask.launch.py │ │ ├── start_navigation_with_speed_and_keepout.launch.py │ │ ├── start_ros2.launch.py │ │ ├── test_camera_2.launch.py │ │ ├── test_camera.launch.py │ │ ├── test_car_model.launch.py │ │ ├── test_cliff.launch.py │ │ ├── test_ir.launch.py │ │ ├── test_self_checking.launch.py │ │ ├── test_video_multiplesing.launch.py │ │ └── test_visualization.launch.py │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_launch │ ├── robot_launch │ │ └── __init__.py │ ├── setup.cfg │ └── setup.py ├── robot_navigation │ ├── config │ │ ├── nav2_filter.yaml │ │ ├── nav2_params.yaml │ │ └── nav2_speed_filter.yaml │ ├── maps │ │ ├── fishbot_map.pgm │ │ └── fishbot_map.yaml │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_navigation │ ├── robot_navigation │ │ ├── __init__.py │ │ └── robot_navigation.py │ ├── setup.cfg │ └── setup.py ├── robot_navigation2_service │ ├── package.xml │ ├── readme.md │ ├── resource │ │ └── robot_navigation2_service │ ├── robot_navigation2_service │ │ ├── camera_follower_client.py │ │ ├── go_to_pose_service.py │ │ ├── __init__.py │ │ ├── leave_no_parking_zone_client_test_2.py │ │ ├── pose_init.py │ │ ├── real_time_point_client.py │ │ ├── recharge_point_client.py │ │ ├── repub_speed_filter_mask.py │ │ └── save_pose.py │ ├── setup.cfg │ └── setup.py ├── robot_sensor │ ├── bash │ │ └── isr_brushless.sh │ ├── CMakeLists.txt │ ├── config │ │ └── sensor_params.yaml │ ├── include │ │ └── robot_sensor │ ├── package.xml │ ├── readme.md │ └── src │ ├── robot_battery_state_publisher.cpp │ ├── robot_battery_voltage_publisher.cpp │ ├── robot_charging_status_publisher.cpp │ ├── robot_cliff_distance_publisher.cpp │ ├── robot_encode_speed_publisher.cpp │ ├── robot_imu_publisher.cpp │ ├── robot_ir_four_signal_publisher.cpp │ ├── robot_ir_signal_publisher.cpp │ ├── robot_keyboard_control_publisher.cpp │ ├── robot_lighting_control_server.cpp │ ├── robot_map_publisher.cpp │ ├── robot_odom_publisher.cpp │ ├── robot_smoke_alarm_publisher.cpp │ ├── robot_ultrasonic_publisher.cpp │ └── robot_wireless_alarm_publisher.cpp ├── robot_sensor_self_check │ ├── check_report │ │ ├── sensor_diagnostic_report_20250226_144435.json │ │ ├── sensor_diagnostic_report_20250226_144435.txt │ │ ├── sensor_diagnostic_report_20250226_144850.json │ │ ├── sensor_diagnostic_report_20250226_144850.txt │ │ ├── sensor_diagnostic_report_20250226_144927.json │ │ ├── sensor_diagnostic_report_20250226_144927.txt │ │ ├── sensor_diagnostic_report_20250226_144958.json │ │ └── sensor_diagnostic_report_20250226_144958.txt │ ├── config │ │ └── sensors_config.yaml │ ├── package.xml │ ├── resource │ │ └── robot_sensor_self_check │ ├── robot_sensor_self_check │ │ ├── __init__.py │ │ ├── robot_sensor_self_check.py │ │ └── test_topic.py │ ├── setup.cfg │ ├── setup.py │ └── test │ ├── test_copyright.py │ ├── test_flake8.py │ └── test_pep257.py ├── robot_visual_identity │ ├── cfg │ │ ├── nanotrack.yaml │ │ ├── rknnconfig.yaml │ │ └── stgcnpose.yaml │ ├── face_feature │ │ ├── mss_face_encoding.npy │ │ ├── wd_face_encoding.npy │ │ └── yls_face_encoding.npy │ ├── package.xml │ ├── resource │ │ ├── robot_visual_identity │ │ └── ros_rknn_infer │ ├── rknn_model │ │ ├── blood_detect.rknn │ │ ├── blood-seg-last-cbam.rknn │ │ ├── face_detect.rknn │ │ ├── face_emotion.rknn │ │ ├── face_keypoint.rknn │ │ ├── face_verify.rknn │ │ ├── head_detect.rknn │ │ ├── nanotrack_backbone127.rknn │ │ ├── nanotrack_backbone255.rknn │ │ ├── nanotrack_head.rknn │ │ ├── people_detect.rknn │ │ ├── stgcn_pose.rknn │ │ ├── yolo_kpt.rknn │ │ └── yolov8s-pose.rknn │ ├── robot_visual_identity │ │ ├── 人体跟随与避障控制系统文档.md │ │ ├── __init__.py │ │ ├── rknn_infer │ │ ├── robot_behavior_recognition.py │ │ ├── robot_emotion_recognition.py │ │ ├── robot_people_rgb_follow.py │ │ ├── robot_people_scan_follow.py │ │ └── robot_people_track.py │ ├── setup.cfg │ ├── setup.py │ └── test │ ├── test_copyright.py │ ├── test_flake8.py │ └── test_pep257.py ├── video_multiplexing │ ├── bash │ │ ├── test_config.linphonerc │ │ ├── test_video_stream.sh │ │ └── video_stream.pcap │ ├── COLCON_IGNORE │ ├── package.xml │ ├── resource │ │ └── video_multiplexing │ ├── setup.cfg │ ├── setup.py │ ├── test │ │ ├── test_copyright.py │ │ ├── test_flake8.py │ │ └── test_pep257.py │ └── video_multiplexing │ ├── __init__.py │ ├── __pycache__ │ ├── rtp_utils.py │ ├── video_freeswitch.py │ ├── video_linphone_bridge.py │ ├── video_publisher.py │ └── video_test_freeswitch.py └── ydlidar_ros2_driver-humble ├── CMakeLists.txt ├── config │ └── ydlidar.rviz ├── details.md ├── images │ ├── cmake_error.png │ ├── EAI.png │ ├── finished.png │ ├── rviz.png │ ├── view.png │ └── YDLidar.jpg ├── launch │ ├── ydlidar_launch.py │ ├── ydlidar_launch_view.py │ └── ydlidar.py ├── LICENSE.txt ├── package.xml ├── params │ └── TminiPro.yaml ├── README.md ├── src │ ├── ydlidar_ros2_driver_client.cpp │ └── ydlidar_ros2_driver_node.cpp └── startup └── initenv.sh 93 directories, 299 files 我的机器人ros2系统是有显示和主控页面的居家服务型移动机器人,用户点击下载更新就开始执行更新流程,整个系统更新功能应该怎么设计,在开发者应该编写哪些代码和做哪些准备,如何设计流程
最新发布
07-21
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值