信息密度 (information density),及代码实现

In brief,信息密度就是相似度的加和或均值! 

When using uncertainty sampling (or other similar strategies), we are unable to take the structure of the data into account. 

This can lead us to suboptimal queries. To alleviate this, one method is to use information density measures to help us guide the queries.

 

 

from sklearn.datasets import make_blobs
from modAL.density import information_density
import matplotlib.pyplot as plt
from pathlib import Path
import numpy as np
import pandas as pd

##获取数据
X, y = make_blobs(n_features=2, n_samples=1000, centers=3, random_state=0, cluster_std=0.7)
##获取数据
# data_path = Path(r"D:\OCdata")
# name = "FourBolbs"
# path_data = str(data_path.joinpath(name + ".csv"))
# data = np.array(pd.read_csv(path_data, header=None))
# X = data[:,:-1]
# y = data[:, -1]

euclidean_density = information_density(X,"euclidean")
cosine_density = information_density(X,"cosine")

plt.style.context('seaborn-while')
plt.figure(figsize=(14,7))
plt.subplot(1,2,1)
plt.scatter(x=X[:, 0], y=X[:, 1], c=cosine_density, cmap='viridis', s=50)
plt.title('The cosine information density')
plt.colorbar()
plt.subplot(1,2,2)
plt.scatter(x=X[:,0],y=X[:,1],c=euclidean_density,cmap="viridis",s=50)
plt.title("The euclidean information density")
plt.colorbar()
plt.show()

参考:https://modal-python.readthedocs.io/en/latest/content/query_strategies/information_density.html

计算各种距离和相似度的

from sklearn.metrics.pairwise import pairwise_distances

    similarity_mtx = 1/(1+pairwise_distances(X, X, metric=metric))

    return similarity_mtx.mean(axis=1)

 

 

信息增益决策树是一种常用的机器学习算法,用于分类和回归问题。下面是一个简单的信息增益决策树的代码实现示例: ```python import numpy as np class DecisionTree: def __init__(self): self.tree = {} def calc_entropy(self, y): classes, counts = np.unique(y, return_counts=True) probabilities = counts / len(y) entropy = -np.sum(probabilities * np.log2(probabilities)) return entropy def calc_information_gain(self, X, y, feature_idx, threshold): left_mask = X[:, feature_idx] <= threshold right_mask = X[:, feature_idx] > threshold left_entropy = self.calc_entropy(y[left_mask]) right_entropy = self.calc_entropy(y[right_mask]) left_weight = len(y[left_mask]) / len(y) right_weight = len(y[right_mask]) / len(y) information_gain = self.calc_entropy(y) - (left_weight * left_entropy + right_weight * right_entropy) return information_gain def find_best_split(self, X, y): best_feature_idx = None best_threshold = None best_information_gain = -np.inf for feature_idx in range(X.shape): thresholds = np.unique(X[:, feature_idx]) for threshold in thresholds: information_gain = self.calc_information_gain(X, y, feature_idx, threshold) if information_gain > best_information_gain: best_information_gain = information_gain best_feature_idx = feature_idx best_threshold = threshold return best_feature_idx, best_threshold def build_tree(self, X, y): if len(np.unique(y)) == 1: return np.unique(y) best_feature_idx, best_threshold = self.find_best_split(X, y) if best_feature_idx is None or best_threshold is None: return np.argmax(np.bincount(y)) left_mask = X[:, best_feature_idx] <= best_threshold right_mask = X[:, best_feature_idx] > best_threshold left_subtree = self.build_tree(X[left_mask], y[left_mask]) right_subtree = self.build_tree(X[right_mask], y[right_mask]) self.tree = { 'feature_idx': best_feature_idx, 'threshold': best_threshold, 'left': left_subtree, 'right': right_subtree } def fit(self, X, y): self.build_tree(X, y) def predict(self, X): predictions = [] for sample in X: node = self.tree while isinstance(node, dict): if sample[node['feature_idx']] <= node['threshold']: node = node['left'] else: node = node['right'] predictions.append(node) return predictions ``` 这段代码实现了一个简单的信息增益决策树,包括计算熵、计算信息增益、寻找最佳分割点、构建决策树、拟合数据和预测等功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeniuHe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值