学习《tensorflow for machine intelligence》
在mac下使用matplotlib 可能会遇到问题
在环境上安装matplotlib
画图参考
https://blog.csdn.net/qq_34337272/article/details/79555544
conda install -n tensorenv matplotlib
参考
https://jingyan.baidu.com/article/eb9f7b6d4a1365869364e839.html
安装 matplotlib 之后,会在家目录生成一个 .matplotlib 文件夹。在这个文件夹中新建一个文件:matplotlibrc,内容是:backend: TkAgg。保存重新进入测试,问题解决
helloworld
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt a = tf.random_normal([2,20]) sess = tf.Session() out = sess.run(a) x, y = out plt.scatter(x, y) plt.show()
得到
kmeas实现:
conda create -n kmdemo python=3 source activate kmdemo conda install -n kmdemo matplotlib numpy
输入文件
test.txt
1.65 4.28 -3.45 3.42 4.84 -1.15 -5.37 -3.36 0.97 2.92 -3.57 1.53 0.45 -3.30 -3.49 -1.72 2.67 1.59 -3.16 3.19
kmeans代码:
import numpy as np import matplotlib.pyplot as plt def loadDataSet(fileName): data = np.loadtxt(fileName,delimiter='\t') return data def distEclud(x,y): return np.sqrt(np.sum((x-y)**2)) def randCent(dataSet,k): m,n = dataSet.shape centroids = np.zeros((k,n)) for i in range(k): index = int(np.random.uniform(0,m)) # centroids[i,:] = dataSet[index,:] return centroids def KMeans(dataSet,k): m = np.shape(dataSet)[0] clusterAssment = np.mat(np.zeros((m,2))) clusterChange = True centroids = randCent(dataSet,k) while clusterChange: clusterChange = False for i in range(m): minDist = 100000.0 minIndex = -1 for j in range(k): distance = distEclud(centroids[j,:],dataSet[i,:]) if distance < minDist: minDist = distance minIndex = j if clusterAssment[i,0] != minIndex: clusterChange = True clusterAssment[i,:] = minIndex,minDist**2 for j in range(k): pointsInCluster = dataSet[np.nonzero(clusterAssment[:,0].A == j)[0]] centroids[j,:] = np.mean(pointsInCluster,axis=0) print("Congratulations,cluster complete!") return centroids,clusterAssment def showCluster(dataSet,k,centroids,clusterAssment): m,n = dataSet.shape if n != 2: print("data not two wei ") return 1 mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', 'len(mark): print("k value too large") return 1 for i in range(m): markIndex = int(clusterAssment[i,0]) plt.plot(dataSet[i,0],dataSet[i,1],mark[markIndex]) mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '