# -*- coding: utf-8 -*-
"""
Created on Thu Jan 24 14:12:08 2019
@author: 11583
"""
import numpy as np
import torch
import sklearn.neighbors
from sklearn.svm import SVC
import scipy.linalg
#from ELM import HiddenLayer
from sklearn import metrics
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def kernel(ker, X, X2, gamma):
if not ker or ker == 'primal':
return X
elif ker == 'linear':
if not X2:
K = torch.dot(X.T, X)
else:
K = torch.dot(X.T, X2)
elif ker == 'rbf':
n1sq = torch.sum(X ** 2, dim=0)
n1 = X.shape[1]
if not X2:
D = ((torch.ones((n1, 1)).to(DEVICE) * n1sq).t()).to(DEVICE) + (torch.ones((n1, 1)).to(DEVICE) * n1sq) - 2 * torch.mm(X.t(), X)
else:
n2sq = torch.sum(X2 ** 2, dim=0)
n2 = X2.shape[1]
D = (torch.ones((n2, 1)) * n1sq).t() + torch.ones((n1, 1)) * n2sq - 2 * torch.dot(X.t(), X)
K = torch.exp(-gamma * D)
elif ker == 'sam':
if not X2:
D = torch.dot(X.T, X)
else:
D = torch.dot(X.T, X2)
K = torch.exp(-gamma * torch.arccos(D) ** 2)
return K
class TCA:
def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1):
'''
Init func
:param kernel_type: kernel, values: 'primal' | 'linear' | 'rbf' | 'sam'
:param dim: dimension after transfer
:param lamb: lambda value in equation
:param gamma: kernel bandwidth for rbf kernel
'''
self.kernel_type = kernel_type
self.dim = dim
self.lamb = lamb
self.gamma = gamma
#@cuda.jit(argtypes=(float32[:], float32[:]),restype=(float32[:],float32[:]), device=True, inline=True)
def fit(self, Xs, Xt):
'''
Transform Xs and Xt
:param Xs: ns * n_feature, source feature
:param Xt: nt * n_feature, target feature
:return: Xs_new and Xt_new after TCA
'''
X = torch.cat((Xs.t(),Xt.t()),1)
X /= torch.norm(X, dim=0)
m, n = X.shape
ns, nt = len(Xs), len(Xt)
aa = (1 / ns * torch.ones(ns, 1))
bb = (-1 / nt * torch.ones(nt, 1))
e = torch.cat((aa,bb),0)
#e = torch.squeeze(e)
M = e * e.t()
#######M的类型必须为浮点型#######
#M = torch.from_numpy(M)
#M = M / np.linalg.norm(M, 'fro')
M = (M / torch.norm(M,p='fro')).to(DEVICE)
#M = torch.from_numpy(M)
H = torch.eye(n).to(DEVICE) - (1 / n * torch.ones((n, n))).to(DEVICE)
K = kernel(self.kernel_type, X, None, gamma=self.gamma)
n_eye = m if self.kernel_type == 'primal' else n
#print(K.shape)
#print(M.shape)
t = torch.mm(K, M)
p = torch.mm(K, H)
a, b = torch.mm(t,K.t()) + self.lamb * torch.eye(n_eye).to(DEVICE), torch.mm(p, K.t())
a = a.cpu().numpy()
b = b.cpu().numpy()
w, V = scipy.linalg.eig(a, b)
# print(w.shape)
# print(V.shape)
# ind = np.argsort(w)
# A = V[:, ind[:self.dim]]
# Z = np.dot(A.T, K)
# Z /= np.linalg.norm(Z, axis=0)
# Xs_new, Xt_new = Z[:, :ns].T, Z[:, ns:].T
# cc = torch.mm(torch.inverse(b),a)
# #print(cc.shape)
# gg = torch.eig(cc,eigenvectors=True)
# w = gg[0]
# V = gg[1]
# print(V.shape)
#print(w.dtype)
w = w.astype(np.float32)
V = V.astype(np.float32)
w = torch.from_numpy(w)
#print(w.shape)
V = torch.from_numpy(V)
#print(w.shape)
ind = torch.argsort(w)
A = V[:, ind[:self.dim]]
#print(A.dtype)
#print(K.dtype)
Z = torch.mm(A.t().cpu(), K.cpu())
Z /= torch.norm(Z, dim=0)
#dist = torch.trace(Z)
Xs_new, Xt_new = torch.t(Z[:, :ns]), torch.t(Z[:, ns:])
# Xs_new = Xs_new.numpy()
# Xt_new = Xt_new.numpy()
#dist = dist.numpy()
#print(type(Xs_new))
#print(Xt_new.shape)
return Xs_new, Xt_new#,dist
#@cuda.jit(argtypes=(float32[:], float32[:],float32[:], float32[:]),restype=(float32[:],float32[:]), device=True, inline=True)
def fit_predict(self, Xs_new, Ys, Xt_new, Yt):
'''
Transform Xs and Xt, then make predictions on target using 1NN
:param Xs: ns * n_feature, source feature
:param Ys: ns * 1, source label
:param Xt: nt * n_feature, target feature
:param Yt: nt * 1, target label
:return: Accuracy and predicted_labels on the target domain
'''
#Xs_new, Xt_new = self.fit(Xs, Xt)
####model select #####
#clf = sklearn.neighbors.KNeighborsClassifier(n_neighbors=10)
# clf = GridSearchCV(SVC(kernel='rbf', gamma=0.1), cv=5,
# param_grid={"C": [1e0, 1e1, 1e2, 1e3],
# "gamma": np.logspace(-2, 2, 5)},scoring="accuracy")
#clf = SVC(kernel='linear',C=19,gamma=0.1)#linear
#clf = SVC(kernel='linear',C=10,gamma=0.1)#sigmoid
clf = SVC(C=10.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma=1.0, kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
# clf = GridSearchCV(SVC(kernel='rbf', gamma=0.1), cv=5,
# param_grid={"C": [1e0, 1e1, 1e2, 1e3],
# "gamma": np.logspace(-2, 2, 5)},scoring="accuracy")
#######线性逻辑回归方法######
#clf = linear_model.LogisticRegression(C=1.0)
clf.fit(Xs_new, Ys.ravel())
y_pred = clf.predict(Xt_new)
#acc = accuracy_score(Yt,y_pred)
acc = sklearn.metrics.accuracy_score(Yt, y_pred)
# a = HiddenLayer(Xs_new,50)
# a.classifisor_train(Ys)
# result = a.classifisor_test(Xt_new)
# acc = metrics.accuracy_score(Yt,result)
#return acc
return acc, y_pred
#return Xs_new,Ys, Xt_new,Yt

邓凌佳
- 粉丝: 96
最新资源
- bcMall教学级电商全栈系统演进实战项目_ToB复杂业务与高并发架构设计_DDD领域驱动与微服务拆分_模型驱动与数据驱动开发_SpringBoot后端与AntdPro前端整合_V.zip
- 《基于Spring Cloud的实战开发文档合集》
- 一加7pro完好机备份基带qcn 一加7pro基带qcn
- 卡尔曼滤波学习项目_UKF优化_DKF与AKF分析_上三角阵对角阵优化_误差定量统计_尖刺检测_接口设计_学习资料整合_技术文档编写_算法实现与测试_性能评估与改进_实际应用案例研.zip
- 跨平台可移植C程序与独立Matlab卡尔曼滤波及绘图工具集_嵌入式系统兼容性头文件分离平台迁移原始数据处理卡尔曼滤波算法实现实时数据可视化多平台部署模块化设计数据驱.zip
- 嵌入式卡尔曼滤波算法库_用于嵌入式系统的高效递归状态估计算法实现_提供卡尔曼滤波器的C语言源码和Keil工程示例_支持线性系统状态估计和传感器数据融合_包含完整的状态预测和更新过程.zip
- wzce_77GRadarML_15044_1755669062809.zip
- 基于4D雷达点云聚类与ROS-Kinetic环境配置的自动驾驶感知系统开发项目_4D雷达数据处理_点云聚类算法_ROS-Kinetic安装_Ubuntu系统配置_雷达目标检测_环境.zip
- 基于4D毫米波雷达与多传感器融合的智能驾驶SLAM系统_前端ICP配准后端SAM优化集成GPS与IMU数据_用于高精度实时定位与建图_支持多分支开发包括回环检测与局部建图_技术关键.zip
- 使用CMake构建系统集成Eigen库实现卡尔曼滤波算法的C项目_卡尔曼滤波预测与状态估计_传感器数据融合与噪声处理_机器人导航与控制系统仿真_多源信息优化与实时轨迹跟踪_CM.zip
- 手搓版卡尔曼滤波器实现与优化研究项目_包含经典线性卡尔曼滤波器误差状态卡尔曼滤波器滑动窗口协方差优化IMU与GNSS数据轨迹推导实验_用于深入理解卡尔曼滤波数学原理探索局部.zip
- 基于AI8051U微控制器的高精度微动检测报警系统_集成CEM5826-M1124GHz毫米波雷达模块与096英寸OLED显示屏的智能感知设备_实时监测环境中物体运动并触发声光.zip
- 基于AWR1642毫米波雷达点云数据采集与神经网络手势识别系统_集成PyTorch深度学习框架与ONNX模型部署_实现高精度实时手势动作分类与交互控制_支持树莓派4B嵌入式平台与串.zip
- 基于AWR1642毫米波雷达的多人实时跟踪系统_毫米波雷达信号处理_点云数据采集与多目标跟踪_用于室内外人员监测与行为分析_支持ROS框架与MATLAB可视化_集成UART串口通信.zip
- 手写实现卡尔曼滤波算法_从零开始构建卡尔曼滤波器_详细理论解释与数学推导_直观可视化演示_轻量化数学公式解析_适用于状态估计与预测_传感器数据融合_目标跟踪_机器人导航_自动驾驶_.zip
- 基于AWR1642毫米波雷达与摄像头融合的实时目标检测与测距测速测角系统_毫米波雷达点云数据采集与图像平面投影_与YOLOv5Lite目标检测框匹配融合_实现目标距离速度角度测量_.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈



评论0