import os import numpy as np import matplotlib.pyplot as plt from PIL import Image from colorcet.plotting import arr from sklearn.cluster import SpectralClustering from sklearn.decomposition import PCA from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.applications.resnet50 import preprocess_input # 定义加载图片函数 def load_image(img_path): img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) return x # 加载ResNet50模型 model = ResNet50(weights='imagenet', include_top=False, pooling='avg') # 加载图片并提取特征向量 img_dir = 'D:/wjd' img_names = os.listdir(img_dir) X = [] for img_name in img_names: img_path = os.path.join(img_dir, img_name) img = load_image(img_path) features = model.predict(img)[0] X.append(features) # 将特征向量转化为矩阵 X = np.array(X) # 将复数类型的数据转换为实数类型 X = np.absolute(X) # 计算相似度矩阵 S = np.dot(X, X.T) # 归一化相似度矩阵 D = np.diag(np.sum(S, axis=1)) L = D - S L_norm = np.dot(np.dot(np.sqrt(np.linalg.inv(D)), L), np.sqrt(np.linalg.inv(D))) # 计算特征向量 eigvals, eigvecs = np.linalg.eig(L_norm) idx = eigvals.argsort()[::-1] eigvals = eigvals[idx] eigvecs = eigvecs[:, idx] Y = eigvecs[:, :2] # 使用谱聚类进行分类 n_clusters = 5 clustering = SpectralClustering(n_clusters=n_clusters, assign_labels="discretize", random_state=0).fit(Y) # 可视化聚类结果 pca = PCA(n_components=2) X_pca = pca.fit_transform(X) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=clustering.labels_, cmap='rainbow') plt.show(),反复会出现numpy.ComplexWarning: Casting complex values to real discards the imaginary part The above exception was the direct cause of the following exception,这个问题
时间: 2024-02-26 19:59:33 浏览: 124
import numpy as np import matplotlib.pyplot as plt import math
这个问题是因为在计算相似度矩阵时,可能存在复数类型的数据,导致计算时出现警告或异常。你可以尝试在计算相似度矩阵前,将特征向量转换为实数类型。你可以使用numpy的绝对值函数numpy.absolute()来将复数类型的数据转换为实数类型。你可以将以下代码:
```
# 将特征向量转化为矩阵
X = np.array(X)
# 计算相似度矩阵
S = np.dot(X, X.T)
# 归一化相似度矩阵
D = np.diag(np.sum(S, axis=1))
L = D - S
L_norm = np.dot(np.dot(np.sqrt(np.linalg.inv(D)), L), np.sqrt(np.linalg.inv(D)))
```
修改为:
```
# 将特征向量转化为矩阵并转换为实数类型
X = np.array(X)
X = np.absolute(X)
# 计算相似度矩阵
S = np.dot(X, X.T)
# 归一化相似度矩阵
D = np.diag(np.sum(S, axis=1))
L = D - S
L_norm = np.dot(np.dot(np.sqrt(np.linalg.inv(D)), L), np.sqrt(np.linalg.inv(D)))
```
这样修改后,应该就可以避免出现这个警告或异常了。
阅读全文