- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用Kobe Bryant Dataset 。我希望用 KnnRegressor 预测 shot_made_flag。
我使用game_date
来提取year
和month
特征:
# covert season to years
kobe_data_encoded['season'] = kobe_data_encoded['season'].apply(lambda x: int(re.compile('(\d+)-').findall(x)[0]))
# add year and month using game_date
kobe_data_encoded['year'] = kobe_data_encoded['game_date'].apply(lambda x: int(re.compile('(\d{4})').findall(x)[0]))
kobe_data_encoded['month'] = kobe_data_encoded['game_date'].apply(lambda x: int(re.compile('-(\d+)-').findall(x)[0]))
kobe_data_encoded = kobe_data_encoded.drop(columns=['game_date'])
并且我希望使用season
、year
、month
功能来赋予它们在距离函数中更大的权重,以便日期更接近的事件当前事件将是更近的邻居,但仍然与潜在的其他数据点保持合理的距离,因此,例如,我不希望同一天的事件仅仅因为日期特征而成为最近的邻居,但它会考虑到其他功能,例如 shot_range
等。
为了赋予它更多的权重,我尝试将 metric 参数与自定义距离函数一起使用,但函数的参数只是 numpy 数组,没有 pandas 的列信息,所以我不确定我能做什么以及如何实现我想要做的事情。
编辑:
对日期特征使用较大的权重,以在 [1, 100]
的 k
上运行 cv
为 10 时找到最佳 k:
from IPython.display import display
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
# scaling
min_max_scaler = preprocessing.MinMaxScaler()
scaled_features_df = kobe_data_encoded.copy()
column_names = ['loc_x', 'loc_y', 'minutes_remaining', 'period',
'seconds_remaining', 'shot_distance', 'shot_type', 'shot_zone_range']
scaled_features = min_max_scaler.fit_transform(scaled_features_df[column_names])
scaled_features_df[column_names] = scaled_features
not_classified_df = scaled_features_df[scaled_features_df['shot_made_flag'].isnull()]
classified_df = scaled_features_df[scaled_features_df['shot_made_flag'].notnull()]
X = classified_df.drop(columns=['shot_made_flag'])
y = classified_df['shot_made_flag']
cv = StratifiedKFold(n_splits=10, shuffle=True)
neighbors = [x for x in range(1, 100)]
cv_scores = []
weight = np.ones((X.shape[1],))
weight[[X.columns.get_loc("season"),
X.columns.get_loc("year"),
X.columns.get_loc("month")
]] = 5
weight = weight/weight.sum() #Normalize weights
def my_distance(x, y):
dist = ((x-y)**2)
return np.dot(dist, weight)
for k in neighbors:
print('k: ', k)
knn = KNeighborsClassifier(n_neighbors=k, metric=my_distance)
cv_scores.append(np.mean(cross_val_score(knn, X, y, cv=cv, scoring='roc_auc')))
#optimal K
optimal_k_index = cv_scores.index(min(cv_scores))
optimal_k = neighbors[optimal_k_index]
print('best k: ', optimal_k)
plt.plot(neighbors, cv_scores)
plt.xlabel('Number of Neighbors K')
plt.ylabel('ROC AUC')
plt.show()
运行速度非常慢,有什么办法让它更快吗?加权特征的想法是找到更接近数据点日期的邻居以避免数据泄漏和cv来找到最佳k。
最佳答案
首先,您必须准备一个 numpy 1D weight
数组,指定每个特征的权重。你可以这样做:
weight = np.ones((M,)) # M is no of features
weight[[1,7,10]] = 2 # Increase weight of 1st,7th and 10th features
weight = weight/weight.sum() #Normalize weights
您可以使用kobe_data_encoded.columns
在数据框中查找season
、year
、month
特征的索引替换上面的第二行。
现在定义一个距离函数,根据准则,该函数必须采用两个一维 numpy 数组。
def my_dist(x,y):
global weight #1D array, same shape as x or y
dist = ((x-y)**2) #1D array, same shape as x or y
return np.dot(dist,weight) # a scalar float
并将KNeighborsRegressor
初始化为:
knn = KNeighborsRegressor(metric=my_dist)
编辑:为了提高效率,您可以预先计算距离矩阵,并在 KNN
中重用它。这应该通过减少对 my_dist 的调用来显着加速,因为这个非向量化的自定义 python 距离函数非常慢。所以现在 -
dist = np.zeros((len(X),len(X))) #Computing NXN distance matrix
for i in range(len(X)): # You can halve this by using the fact that dist[i,j] = dist[j,i]
for j in range(len(X)):
dist[i,j] = my_dist(X[i],X[j])
for k in neighbors:
print('k: ', k)
knn = KNeighborsClassifier(n_neighbors=k, metric='precomputed') #Note: metric='precomputed'
cv_scores.append(np.mean(cross_val_score(knn, dist, y, cv=cv, scoring='roc_auc'))) #Note: passing dist instead of X
我无法测试它,所以如果有问题请告诉我。
关于pandas - Knn 对距离上的特定特征赋予更多权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57521656/
library(ISLR) standardized.X=scale(Caravan [,-86]) test =1:1000 train.X=standardized.X[-test ,] test
这可能是一个愚蠢的问题,但我只是想知道在 scikit.ml 中实现的 ML-KNN 与 scikit-learn 的 KNeighborsClassifier 之间的区别是什么。根据sklearn'
我担心我的预测与测试的准确性,这完全有意义。 X_train , X_test, y_train ,y_test =train_test_split(iris_dataset['data'], iri
我已经开始在 python tensorflow 库上使用 K-Nearest-Neighbors 方法开发一个机器学习项目。我没有使用tensorflow工具的经验,所以我在github上找到了一些
大侠幸会,在下全网同名「算法金」 0 基础转 AI 上岸,多个算法赛 Top 「日更万日,让更多人享受智能乐趣」 KNN算法的工作原理简单直观,易于理解和实现,这使得它在各种应用场景
我试图在 R 中使用 knn(使用了几个包( knnflex , class ))来预测基于 8 个变量的违约概率。数据集大约有 100k 行 8 列,但我的机器似乎很难处理 10k 行的样本。在数据
我有一个 60.000 obs/40 变量数据集,我在其中使用了 Clara,主要是由于内存限制。 library(cluster) library(dplyr) mutate(kddne
我尝试运行这条线: knn(mydades.training[,-7],mydades.test[,-7],mydades.training[,7],k=5) 但我总是收到这个错误: Error in
我正在尝试使用 python 实现 k-近邻算法。我最终得到了以下代码。但是,我正在努力寻找最近邻居项目的索引。以下函数将返回距离矩阵。但是,我需要在features_train(算法的输入矩阵)中获
我正在使用Kobe Bryant Dataset 。我希望用 KnnRegressor 预测 shot_made_flag。 我使用game_date来提取year和month特征: # covert
在 kNN classifier 的文档中,有一个方法kneighbors ,返回 k 个最近邻居。我感兴趣的是如何优雅地返回此类分类器中的 k 个最远邻居? 最佳答案 不,没有这样的能力。 您需要记
我想优化 KNN。关于SVM、RF和XGboost的内容有很多;但对于 KNN 来说很少。 据我所知,邻居的数量是一个需要调整的参数。 但是还有哪些参数需要测试呢?有什么好的文章吗? 谢谢 最佳答案
我正在尝试使用具有两列的数据集进行词袋问题 - 摘要和解决方案。我正在使用 KNN。训练数据集有 91 列,测试数据集有 15 列。 为了生成向量,我使用以下代码。 vectorizer = Coun
我了解 k 最近邻 (KNN) 的工作原理,但我不熟悉“软投票”一词。与 KNN 相关的软投票是什么?它与标准 KNN 投票相比如何工作? 比较两种投票方案的简单示例会很有用,并且指向 Matlab
我正在尝试将 KNN 应用到 tips 数据集 并将对象映射如下: f.Male=df.Gender.map({'Female':0,'Male':1}) df.Smokes = df.Smoker.
在下面的代码(最后一行)中,根据文档使用了 X_test 和 y_test: Returns the mean accuracy on the given test data and label 问题
我有约 65 个特征、450k 个观察值和不平衡的分类响应变量 Y(约 5% 真实,2 个状态)的 df。这已通过 train_test_split 分为 {Xtrain, ytrain} (10%)
为什么在 KNN 中需要规范化?我知道这个过程标准化了所有特征对结果的影响,但是在标准化之前到特定点 V 的“K”最近点将与到该特定点的“K”最近点完全相同归一化后的 V。那么归一化对欧氏距离有何影响
我目前正在为我的人工智能考试做一个机器学习项目。目标是使用 WEKA 正确选择两种分类算法进行比较,请记住,这两种算法必须有足够的不同才能进行比较。此外,算法必须同时处理标称数据和数字数据(我想这是进
进行数据挖掘时,什么时候应该选择其中一种算法而不是另一种?有具体原因吗?另外,其中哪一个是最有效的? 我将给出一个表格作为示例。 最佳答案 一种选择方法是尝试所有这些并选择最好的。 如果我要尝试构建数
我是一名优秀的程序员,十分优秀!