sampled = 1000 x_test = x_test[:sampled] t_test = t_test[:sampled] prediect_result = [] for i in x_test: i = np.expand_dims(i, 0) y = network.predict(i) _result = network.predict(i) _result = softmax(_result) result = np.argmax(_result) prediect_result.append(int(result))

时间: 2023-10-06 08:09:18 浏览: 38
这段代码的作用是对测试集数据进行预测,并将预测结果保存到 prediect_result 列表中。首先,从测试集数据中随机抽取了 1000 个样本,并将其赋值给 x_test 和 t_test 变量。然后,通过 for 循环依次对每个样本进行预测。接着,使用 np.expand_dims 函数将当前样本 i 扩展为形状为 (1, 1, 28, 28) 的四维数组,以便传入网络进行预测。然后,调用 network.predict 函数对当前样本进行预测,得到一个形状为 (1, 10) 的二维数组 _result,表示当前样本被预测为每个类别的概率。接着,将 _result 应用 softmax 函数,得到一个形状为 (1, 10) 的二维数组,表示当前样本被预测为每个类别的概率。然后,使用 np.argmax 函数获取概率最大的类别,将其作为当前样本的预测结果,并将预测结果添加到 prediect_result 列表中。最终,prediect_result 列表中保存了 1000 个样本的预测结果。
相关问题

x_train, t_train, x_test, t_test = load_data('F:\\2023\\archive\\train') network = DeepConvNet() network.load_params("deep_convnet_params.pkl") print("calculating test accuracy ... ") sampled = 1000 x_test = x_test[:sampled] t_test = t_test[:sampled] prediect_result = [] for i in x_test: i = np.expand_dims(i, 0) y = network.predict(i) _result = network.predict(i) _result = softmax(_result) result = np.argmax(_result) prediect_result.append(int(result))

根据你的代码,你正在加载一个名为"deep_convnet_params.pkl"的神经网络模型的参数,并使用该模型进行图像分类的测试。测试集中的图像数量为1000张,并且你对每张图像进行了预测,并将预测结果存储在了一个名为"predict_result"的列表中。你使用了softmax函数将预测结果转换为概率分布,并选择具有最高概率的类别作为预测结果。最后,你将预测结果转换为整数格式并将其添加到"predict_result"列表中。你的代码似乎是用Python编写的,但是我不确定你导入了哪些库。

network = DeepConvNet() network.load_params("deep_convnet_params.pkl") # sampled = 10000 # 为了实现高速化 # x_test = x_test[:sampled] # t_test = t_test[:sampled] print("caluculate accuracy (float64) ... ") print(network.accuracy(x_test, t_test)) # 转换为float16型 x_test = x_test.astype(np.float16) for param in network.params.values(): param[...] = param.astype(np.float16) print("caluculate accuracy (float16) ... ") print(network.accuracy(x_test, t_test))

这段代码是一个使用DeepConvNet模型来测试图像分类准确率的例子。首先,使用`load_params()`方法加载预先训练好的模型参数,然后打印出使用`accuracy()`方法计算出的模型在测试数据集上的分类准确率。接下来,将测试数据转换为float16类型,并将模型参数也转换为float16类型,然后再次计算模型在测试数据集上的分类准确率。这个例子旨在展示使用float16类型可以提高模型的计算速度,但可能会降低模型的精度。

相关推荐

修改和补充下列代码得到十折交叉验证的平均每一折auc值和平均每一折aoc曲线,平均每一折分类报告以及平均每一折混淆矩阵 min_max_scaler = MinMaxScaler() X_train1, X_test1 = x[train_id], x[test_id] y_train1, y_test1 = y[train_id], y[test_id] # apply the same scaler to both sets of data X_train1 = min_max_scaler.fit_transform(X_train1) X_test1 = min_max_scaler.transform(X_test1) X_train1 = np.array(X_train1) X_test1 = np.array(X_test1) config = get_config() tree = gcForest(config) tree.fit(X_train1, y_train1) y_pred11 = tree.predict(X_test1) y_pred1.append(y_pred11 X_train.append(X_train1) X_test.append(X_test1) y_test.append(y_test1) y_train.append(y_train1) X_train_fuzzy1, X_test_fuzzy1 = X_fuzzy[train_id], X_fuzzy[test_id] y_train_fuzzy1, y_test_fuzzy1 = y_sampled[train_id], y_sampled[test_id] X_train_fuzzy1 = min_max_scaler.fit_transform(X_train_fuzzy1) X_test_fuzzy1 = min_max_scaler.transform(X_test_fuzzy1) X_train_fuzzy1 = np.array(X_train_fuzzy1) X_test_fuzzy1 = np.array(X_test_fuzzy1) config = get_config() tree = gcForest(config) tree.fit(X_train_fuzzy1, y_train_fuzzy1) y_predd = tree.predict(X_test_fuzzy1) y_pred.append(y_predd) X_test_fuzzy.append(X_test_fuzzy1) y_test_fuzzy.append(y_test_fuzzy1)y_pred = to_categorical(np.concatenate(y_pred), num_classes=3) y_pred1 = to_categorical(np.concatenate(y_pred1), num_classes=3) y_test = to_categorical(np.concatenate(y_test), num_classes=3) y_test_fuzzy = to_categorical(np.concatenate(y_test_fuzzy), num_classes=3) print(y_pred.shape) print(y_pred1.shape) print(y_test.shape) print(y_test_fuzzy.shape) # 深度森林 report1 = classification_report(y_test, y_prprint("DF",report1) report = classification_report(y_test_fuzzy, y_pred) print("DF-F",report) mse = mean_squared_error(y_test, y_pred1) rmse = math.sqrt(mse) print('深度森林RMSE:', rmse) print('深度森林Accuracy:', accuracy_score(y_test, y_pred1)) mse = mean_squared_error(y_test_fuzzy, y_pred) rmse = math.sqrt(mse) print('F深度森林RMSE:', rmse) print('F深度森林Accuracy:', accuracy_score(y_test_fuzzy, y_pred)) mse = mean_squared_error(y_test, y_pred) rmse = math.sqrt(mse)

修改和补充下列代码得到十折交叉验证的平均auc值和平均aoc曲线,平均分类报告以及平均混淆矩阵 min_max_scaler = MinMaxScaler() X_train1, X_test1 = x[train_id], x[test_id] y_train1, y_test1 = y[train_id], y[test_id] # apply the same scaler to both sets of data X_train1 = min_max_scaler.fit_transform(X_train1) X_test1 = min_max_scaler.transform(X_test1) X_train1 = np.array(X_train1) X_test1 = np.array(X_test1) config = get_config() tree = gcForest(config) tree.fit(X_train1, y_train1) y_pred11 = tree.predict(X_test1) y_pred1.append(y_pred11 X_train.append(X_train1) X_test.append(X_test1) y_test.append(y_test1) y_train.append(y_train1) X_train_fuzzy1, X_test_fuzzy1 = X_fuzzy[train_id], X_fuzzy[test_id] y_train_fuzzy1, y_test_fuzzy1 = y_sampled[train_id], y_sampled[test_id] X_train_fuzzy1 = min_max_scaler.fit_transform(X_train_fuzzy1) X_test_fuzzy1 = min_max_scaler.transform(X_test_fuzzy1) X_train_fuzzy1 = np.array(X_train_fuzzy1) X_test_fuzzy1 = np.array(X_test_fuzzy1) config = get_config() tree = gcForest(config) tree.fit(X_train_fuzzy1, y_train_fuzzy1) y_predd = tree.predict(X_test_fuzzy1) y_pred.append(y_predd) X_test_fuzzy.append(X_test_fuzzy1) y_test_fuzzy.append(y_test_fuzzy1)y_pred = to_categorical(np.concatenate(y_pred), num_classes=3) y_pred1 = to_categorical(np.concatenate(y_pred1), num_classes=3) y_test = to_categorical(np.concatenate(y_test), num_classes=3) y_test_fuzzy = to_categorical(np.concatenate(y_test_fuzzy), num_classes=3) print(y_pred.shape) print(y_pred1.shape) print(y_test.shape) print(y_test_fuzzy.shape) # 深度森林 report1 = classification_report(y_test, y_prprint("DF",report1) report = classification_report(y_test_fuzzy, y_pred) print("DF-F",report) mse = mean_squared_error(y_test, y_pred1) rmse = math.sqrt(mse) print('深度森林RMSE:', rmse) print('深度森林Accuracy:', accuracy_score(y_test, y_pred1)) mse = mean_squared_error(y_test_fuzzy, y_pred) rmse = math.sqrt(mse) print('F深度森林RMSE:', rmse) print('F深度森林Accuracy:', accuracy_score(y_test_fuzzy, y_pred)) mse = mean_squared_error(y_test, y_pred) rmse = math.sqrt(mse) print('F?深度森林RMSE:', rmse) print('F?深度森林Accuracy:', accuracy_score(y_test, y_pred))

改成三分类代码n_trees = 100 max_depth = 10 forest = [] for i in range(n_trees): idx = np.random.choice(X_train.shape[0], size=X_train.shape[0], replace=True) X_sampled = X_train[idx, :] y_sampled = y_train[idx] X_fuzzy = [] for j in range(X_sampled.shape[1]): if np.median(X_sampled[:, j])> np.mean(X_sampled[:, j]): fuzzy_vals = fuzz.trapmf(X_sampled[:, j], [np.min(X_sampled[:, j]), np.mean(X_sampled[:, j]), np.median(X_sampled[:, j]), np.max(X_sampled[:, j])]) else: fuzzy_vals = fuzz.trapmf(X_sampled[:, j], [np.min(X_sampled[:, j]), np.median(X_sampled[:, j]), np.mean(X_sampled[:, j]), np.max(X_sampled[:, j])]) X_fuzzy.append(fuzzy_vals) X_fuzzy = np.array(X_fuzzy).T tree = RandomForestClassifier(n_estimators=1, max_depth=max_depth) tree.fit(X_fuzzy, y_sampled) forest.append(tree) inputs = keras.Input(shape=(X_train.shape[1],)) x = keras.layers.Dense(64, activation="relu")(inputs) x = keras.layers.Dense(32, activation="relu")(x) outputs = keras.layers.Dense(1, activation="sigmoid")(x) model = keras.Model(inputs=inputs, outputs=outputs) model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]) y_pred = np.zeros(y_train.shape) for tree in forest: a = [] for j in range(X_train.shape[1]): if np.median(X_train[:, j]) > np.mean(X_train[:, j]): fuzzy_vals = fuzz.trapmf(X_train[:, j], [np.min(X_train[:, j]), np.mean(X_train[:, j]), np.median(X_train[:, j]), np.max(X_train[:, j])]) else: fuzzy_vals = fuzz.trapmf(X_train[:, j], [np.min(X_train[:, j]), np.median(X_train[:, j]), np.mean(X_train[:, j]), np.max(X_train[:, j])]) a.append(fuzzy_vals) fuzzy_vals = np.array(a).T y_pred += tree.predict_proba(fuzzy_vals)[:, 1] y_pred /= n_trees model.fit(X_train, y_pred, epochs=10, batch_size=32) y_pred = model.predict(X_test) mse = mean_squared_error(y_test, y_pred) rmse = math.sqrt(mse) print('RMSE:', rmse) print('Accuracy:', accuracy_score(y_test, y_pred))

为下面这段代码的预测结果加上可视化功能,要能够看到每个预测数据的结果的准确度:from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import jieba from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt good_comments = [] bad_comments = [] with open('D:\PyCharmProjects\爬虫测试\好评.txt', 'r', encoding='gbk') as f: for line in f.readlines(): good_comments.append(line.strip('\n')) with open('D:\PyCharmProjects\爬虫测试\差评.txt', 'r', encoding='gbk') as f: for line in f.readlines(): bad_comments.append(line.strip('\n')) with open('StopWords.txt', 'r', encoding='utf-8') as f: stopwords = f.read().splitlines() good_words = [] for line in good_comments: words = jieba.cut(line, cut_all=False) words = [w for w in words if w not in stopwords] good_words.append(' '.join(words)) bad_words = [] for line in bad_comments: words = jieba.cut(line, cut_all=False) words = [w for w in words if w not in stopwords] bad_words.append(' '.join(words)) # 将文本转换为向量 vectorizer = CountVectorizer() X = vectorizer.fit_transform(good_words + bad_words) y = [1] * len(good_words) + [0] * len(bad_words) # 将数据分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 训练模型 clf = MultinomialNB() clf.fit(X_train, y_train) # 测试模型并计算准确率 pred = clf.predict(X_test) accuracy = sum(pred == y_test) / len(y_test) print('准确率:{:.2%}'.format(accuracy)) # 预测新数据的类别 with open('测试评论.txt', 'r', encoding='utf-8') as f: count = 0 for line in f.readlines(): count += 1 test_text = line.strip('\n') test_words = ' '.join(jieba.cut(test_text, cut_all=False)) test_vec = vectorizer.transform([test_words]) pred = clf.predict(test_vec) if pred[0] == 1: print(count, '好评') else: print(count, '差评')

column_name = ["label"] column_name.extend(["pixel%d" % i for i in range(32 * 32 * 3)]) dataset = pd.read_csv('cifar_train.csv') #dataset = pd.read_csv('heart.csv') #dataset = pd.read_csv('iris.csuv') #sns.pairplot(dataset.iloc[:, 1:6]) #plt.show() #print(dataset.head()) #shuffled_data = dataset.sample(frac=1) #dataset=shuffled_data #index=[0,1,2,3,4,5,6,7,8,9,10,11,12,13] #dataset.columns=index dataset2=pd.read_csv('test.csv') #X = dataset.iloc[:, :30].values #y = dataset.iloc[:,30].values mm = MinMaxScaler() from sklearn.model_selection import train_test_split #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0) X_train =dataset.iloc[:,1:].values X_test = dataset2.iloc[:,1:].values y_train = dataset.iloc[:,0].values y_test = dataset2.iloc[:,0].values print(y_train) # 进行独热编码 def one_hot_encode_object_array(arr): # 去重获取全部的类别 uniques, ids = np.unique(arr, return_inverse=True) # 返回热编码的结果 return tf.keras.utils.to_categorical(ids, len(uniques)) #train_y_ohe=y_train #test_y_ohe=y_test # 训练集热编码 train_y_ohe = one_hot_encode_object_array(y_train) # 测试集热编码 test_y_ohe = one_hot_encode_object_array(y_test) # 利用sequential方式构建模型 from keras import backend as K def swish(x, beta=1.0): return x * K.sigmoid(beta * x) from keras import regularizers model = tf.keras.models.Sequential([ # 隐藏层1,激活函数是relu,输入大小有input_shape指定 tf.keras.layers.InputLayer(input_shape=(3072,)), # lambda(hanshu, output_shape=None, mask=None, arguments=None), #tf.keras.layers.Lambda(hanshu, output_shape=None, mask=None, arguments=None), tf.keras.layers.Dense(500, activation="relu"), # 隐藏层2,激活函数是relu tf.keras.layers.Dense(500, activation="relu"), # 输出层 tf.keras.layers.Dense(10, activation="softmax") ])

def evaluate(self, datloader_Test): Image_Feature_ALL = [] Image_Name = [] Sketch_Feature_ALL = [] Sketch_Name = [] start_time = time.time() self.eval() for i_batch, sampled_batch in enumerate(datloader_Test): sketch_feature, positive_feature = self.test_forward(sampled_batch) Sketch_Feature_ALL.extend(sketch_feature) #草图特征 模型的 Sketch_Name.extend(sampled_batch['sketch_path']) #草图名 for i_num, positive_name in enumerate(sampled_batch['positive_path']): #遍历正例图像 if positive_name not in Image_Name: Image_Name.append(positive_name) Image_Feature_ALL.append(positive_feature[i_num]) rank = torch.zeros(len(Sketch_Name)) Image_Feature_ALL = torch.stack(Image_Feature_ALL) Image_Feature_ALL = Image_Feature_ALL.view(Image_Feature_ALL.size(0), -1) for num, sketch_feature in enumerate(Sketch_Feature_ALL): s_name = Sketch_Name[num] sketch_query_name = os.path.basename(s_name) # 提取草图路径中的文件名作为查询名称 position_query = -1 for i, image_name in enumerate(Image_Name): if sketch_query_name in os.path.basename(image_name): # 提取图像路径中的文件名进行匹配 position_query = i break if position_query != -1: sketch_feature = sketch_feature.view(1, -1) distance = F.pairwise_distance(sketch_feature, Image_Feature_ALL) target_distance = F.pairwise_distance(sketch_feature, Image_Feature_ALL[position_query].view(1, -1)) rank[num] = distance.le(target_distance).sum() top1 = rank.le(1).sum().item() / rank.shape[0] top10 = rank.le(10).sum().item() / rank.shape[0] print('Time to Evaluate: {}'.format(time.time() - start_time)) return top1, top10

最新推荐

recommend-type

课设毕设基于SSM的毕业生就业信息管理系统-LW+PPT+源码可运行

课设毕设基于SSM的毕业生就业信息管理系统--LW+PPT+源码可运行
recommend-type

STM32设置闹钟中断-博文程序源码

发了《STM32设置闹钟中断》一文后,大家都要问我要源码,其实我也找不到,当初也只是做设计时的一部分,根本没留单独的源代码,今天按博文特意重新整理了一下,有需要的自己下载吧。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

SPDK_NVMF_DISCOVERY_NQN是什么 有什么作用

SPDK_NVMF_DISCOVERY_NQN 是 SPDK (Storage Performance Development Kit) 中用于查询 NVMf (Non-Volatile Memory express over Fabrics) 存储设备名称的协议。NVMf 是一种基于网络的存储协议,可用于连接远程非易失性内存存储器。 SPDK_NVMF_DISCOVERY_NQN 的作用是让存储应用程序能够通过 SPDK 查询 NVMf 存储设备的名称,以便能够访问这些存储设备。通过查询 NVMf 存储设备名称,存储应用程序可以获取必要的信息,例如存储设备的IP地址、端口号、名称等,以便能
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

Windows 运行Python脚本

要在 Windows 上运行 Python 脚本,你需要先安装 Python。可以从官网下载 Python 安装包并按照提示进行安装。安装完成后,就可以在命令行中输入 `python` 命令,进入 Python 解释器环境。 接着,你可以编写 Python 脚本,保存为 `.py` 后缀的文件。在命令行中进入脚本所在的目录,输入 `python script.py` 命令来运行脚本。其中 `script.py` 是你的脚本文件名。 如果你想在 Windows 上运行一个 Python 程序,但不想打开命令行窗口,可以将脚本文件拖动到 Python 可执行文件 `python.exe` 上,