np.where 的用法记录

对分割标签进行处理解码处理

import os
import torch
import numpy as np
import torch.nn.functional as F

x = np.array([[0.2, 0.3], [0.4, 0.5],[0.7, 0.6]])  # 输入的是array 类型
y = np.array([[1, 0], [1, 1],[0, 1]])
y_pred = torch.from_numpy(x).float()
y_label = torch.from_numpy(y).float()
# print(y_label.shape)

pred = F.softmax(y_pred, dim=-1).numpy()
print(pred)
print("使用最值:")
print(pred.argmax(axis=-1))
print("使用阈值:")
pred  = np.where(pred>0.5)
print(pred[1])

注意 np.where是的使用

得到的最值或者满足条件的索引,得到的是元组形式,这里我们只使用列。

pred  = np.where(pred>0.5)
print(pred[1])

以上我们是用的是
np.argwhere和np.where 详情见
https://www.ngui.cc/el/1148979.html?action=onClick

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
class NeuralNetwork: def init(self, input_dim, hidden_dim, output_dim): self.input_dim = input_dim self.hidden_dim = hidden_dim self.output_dim = output_dim self.weights1 = np.random.randn(input_dim, hidden_dim) self.bias1 = np.zeros((1, hidden_dim)) self.weights2 = np.random.randn(hidden_dim, output_dim) self.bias2 = np.zeros((1, output_dim)) def relu(self, x): return np.maximum(0, x) def relu_derivative(self, x): return np.where(x >= 0, 1, 0) def forward(self, x): self.z1 = np.dot(x, self.weights1) + self.bias1 self.a1 = self.relu(self.z1) self.z2 = np.dot(self.a1, self.weights2) + self.bias2 self.y_hat = self.z2 return self.y_hat def backward(self, x, y, learning_rate): error = self.y_hat - y delta2 = error delta1 = np.dot(delta2, self.weights2.T) * self.relu_derivative(self.a1) grad_weights2 = np.dot(self.a1.T, delta2) grad_bias2 = np.sum(delta2, axis=0, keepdims=True) grad_weights1 = np.dot(x.T, delta1) grad_bias1 = np.sum(delta1, axis=0) self.weights2 -= learning_rate * grad_weights2 self.bias2 -= learning_rate * grad_bias2 self.weights1 -= learning_rate * grad_weights1 def mse_loss(self, y, y_hat): return np.mean((y - y_hat)**2) def sgd_optimizer(self, x, y, learning_rate): y_hat = self.forward(x) loss = self.mse_loss(y, y_hat) self.backward(x, y, learning_rate) return loss def train(self, x, y, learning_rate, num_epochs): for i in range(num_epochs): y_hat = self.forward(x) loss = np.mean(np.square(y_hat - y)) loss_history.append(loss) self.backward(X, y, y_hat, learning_rate) if i % 100 == 0: print('Epoch', i, '- Loss:', loss) return loss_history input_dim=13 hidden_dim=25 output=1 nn=NeuralNetwork(input_dim, hidden_dim, output_dim) learning_rate=0.05 num_epochs=2000 loss_history=nn.train(x, y, learning_rate, num_epochs)分析代码
最新发布
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值