workshop-week10-2021S2
COMP20008 2021S2 workshop week 10 Answers¶
Copyright By PowCoder代写 加微信 powcoder
Code version for Question 1¶
import numpy as np
from sklearn.cluster import KMeans
# Explicitly setting initial points to match those given in Q1 – normally you would not do this for KMeans.
# It’s generally better to let sklearn handle the initialisation and set a fixed random_state if you need reproducability.
points = np.array([[1],[2],[3],[4],[5],[6],[7],[8],[9],[10]])
initials=np.array([[1],[2]])
clusters = KMeans(n_clusters=2, init=initials).fit(points)
print(clusters.cluster_centers_)
print(clusters.labels_)
[0 0 0 0 1 1 1 1 1 1]
C:\Users\chris\Anaconda3\lib\site-packages\sklearn\cluster\_kmeans.py:984: RuntimeWarning: Explicit initial center position passed: performing only one init in KMeans instead of n_init=10.
self._check_params(X)
Code version for Question 2¶
###Question 2
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.image as mpimg
%matplotlib inline
from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.spatial.distance import pdist, squareform
inputs = np.array([[i] for i in range(1,11)])
d = pdist(inputs, ‘euclidean’)
print(squareform(d))
print(inputs)
[[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[1. 0. 1. 2. 3. 4. 5. 6. 7. 8.]
[2. 1. 0. 1. 2. 3. 4. 5. 6. 7.]
[3. 2. 1. 0. 1. 2. 3. 4. 5. 6.]
[4. 3. 2. 1. 0. 1. 2. 3. 4. 5.]
[5. 4. 3. 2. 1. 0. 1. 2. 3. 4.]
[6. 5. 4. 3. 2. 1. 0. 1. 2. 3.]
[7. 6. 5. 4. 3. 2. 1. 0. 1. 2.]
[8. 7. 6. 5. 4. 3. 2. 1. 0. 1.]
[9. 8. 7. 6. 5. 4. 3. 2. 1. 0.]]
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
# print(squareform(d))
#At each iteration, the algorithm must update the distance matrix to reflect the distance of the newly formed cluster u with the remaining clusters in the forest.
hc1 = linkage(d, ‘single’) # min
dendrogram(hc1, labels=inputs)
plt.show()
C:\Users\chris\Anaconda3\lib\site-packages\matplotlib\text.py:1165: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
if s != self._text:
hc2 = linkage(d, ‘average’)
dendrogram(hc2, labels=inputs)
plt.show()
hc3 = linkage(d, ‘complete’) # max
dendrogram(hc3, labels=inputs)
plt.show()
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com