import tensorflow as tf
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
num_points = 2000
conjunto_points = []
for i in range(num_points):
if np.random.random() < 0.5:
conjunto_points.append([np.random.normal(0.0, 0.9), np.random.normal(0.0, 0.9)])
else:
conjunto_points.append([np.random.normal(3.0, 0.5), np.random.normal(1.0, 0.5)])
df = pd.DataFrame({"x1": [v[0] for v in conjunto_points], "y1": [v[1] for v in conjunto_points]})
sns.lmplot("x1", "y1", data=df, fit_reg=False)
plt.show()
sess = tf.Session()
np.set_printoptions(threshold=5)
vectors = tf.constant(conjunto_points)
k = 4
centroides = tf.Variable(tf.slice(tf.random_shuffle(vectors), [0, 0], [k, -1]))
print ("centroides = ", tf.slice(tf.random_shuffle(vectors), [0, 0], [k, 2]).eval(session=sess))
expended_vector = tf.expand_dims(vectors, 0)
expended_centroides = tf.expand_dims(centroides, 1)
reduce_sum = tf.reduce_sum(tf.square(tf.subtract(expended_vector, expended_centroides)), 2)
assignments = tf.argmin(reduce_sum, 0)
means = tf.concat([tf.reduce_mean(tf.gather(vectors, tf.reshape(tf.where(tf.equal(assignments, c)), [1, -1])), reduction_indices=[1]) for c in range(k)], 0)
update_centroides = tf.assign(centroides, means)
init = tf.global_variables_initializer()
sess.run(init)
for i in range(100):
pcentroides = sess.run(update_centroides)
print (sess.run(centroides))
assignment_values = sess.run( assignments )
data = { "x":[], "y":[], "cluster":[] }
for i in range( len(assignment_values) ):
data[ 'x' ].append( conjunto_points[i][0] )
data[ 'y' ].append( conjunto_points[i][1] )
data[ 'cluster' ].append( assignment_values[i] )
df = pd.DataFrame( data )
sns.lmplot( "x", "y", data=df, fit_reg = False, size=6, hue='cluster', legend = False )
plt.show()
tensorflow 实现kmeans
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 3.2 TensorFlow实现Softmax Regression识别手写数字 MNIST(Mixed Nati...
- TensorFlow从0到N专题入口 当看到本篇时,根据TensorFlow官方标准《Deep MNIST for...
- 早年学者发现几乎所有的图片碎片都可以由64种正交的边组合得到。自编码(AutoEncoder),顾名思义即可以使用...
- 本章将介绍AlexNet,VGGNet,Google Inception Net,和ResNetAlexNet其主...
- 回顾 skip-gram CBOW 与skip-gram相反,context(word) 预测 word the...