KNN k近邻法tensorflow实现

import tensorflow as tf
import numpy as np
from sklearn import datasets
from tensorflow.python.framework import ops

ops.reset_default_graph()
sess = tf.Session()

iris = datasets.load_iris()
x_vals = iris.data
y_vals = iris.target</pre><br>

x_vals_norm = (x_vals - x_vals.min(0)) / x_vals.ptp(0) #min-max scale
train_indices = np.random.choice(len(x_vals),round(len(x_vals) * 0.8),replace=False)
test_indices = np.array(list(set(range(len(x_vals))) - set(train_indices)))
x_train = x_vals_norm[train_indices]
x_test = x_vals_norm[test_indices]
y_train = y_vals[train_indices].reshape(-1,1)
y_test = y_vals[test_indices].reshape(-1,1)</pre><br>

k = 5

X_train = tf.placeholder(tf.float32,[None,x_vals.shape[1]])
X_test = tf.placeholder(tf.float32,[None,x_vals.shape[1]])
Y_train = tf.placeholder(tf.float32,[None,1])
Y_test = tf.placeholder(tf.float32,[None,1])

distance = tf.reduce_sum(tf.abs(tf.subtract(X_train,tf.expand_dims(X_test,1))),2)#L1
#distance = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(X_train,tf.expand_dims(X_test,1))),2)) #L2

top_k_vals, top_k_indices = tf.nn.top_k(tf.negative(distance),k=k)
top_k_yvals = tf.squeeze(tf.gather(Y_train,top_k_indices))
predict=tf.reduce_mean(tf.cast(tf.equal(tf.matmul(Y_test,tf.ones([1,k],tf.float32)),top_k_yvals),dtype=tf.float32),1)
predict = tf.reduce_mean(tf.cast(predict>=0.5,dtype=tf.float32))</pre><br>
predictions = sess.run(predict, feed_dict={X_train: x_train, X_test: x_test,
                                         Y_train: y_train, Y_test: y_test})
print('accuracy:' + str(predictions))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值