Python 如何为numpy数组&x27;实现函数f(x)={x^2,x>;0和-x^2,x<;0};x';?

Python 如何为numpy数组&x27;实现函数f(x)={x^2,x>;0和-x^2,x<;0};x';?,python,numpy,neural-network,activation-function,Python,Numpy,Neural Network,Activation Function,我试图根据以下函数更改Numpy数组“x”中的每个值: f(x) = { x^2 , x >= 0 and -x^2 , x < 0 } def squares(x): return (x**2) * np.sign(x) 函数似乎已正确执行,但当结果用于此 tmp = output_errors * output_network * (1.0 - output_network) 稍后,它会显示以下错误:RuntimeWarning:multiply

我试图根据以下函数更改Numpy数组“x”中的每个值:

f(x) = { x^2 , x >= 0 and 
        -x^2 , x < 0  }
def squares(x):
    return (x**2) * np.sign(x)
函数似乎已正确执行,但当结果用于此

tmp = output_errors * output_network * (1.0 - output_network)
稍后,它会显示以下错误:
RuntimeWarning:multiply中遇到溢出

但是,在运行以下代码时,不会出现此类错误:

@numpy.vectorize
def sigmoid(x):
    return 1 / (1 + numpy.e ** -x)
整个代码是

import time
import pickle
from scipy.stats import truncnorm
from datetime import datetime

@numpy.vectorize
def activate(x):
    negative_mask = x < 0
    x = x ** 2
    x[negative_mask] *= -1
    return x
    #return (x ** 2) if x > 0 else (-(x ** 2))
    
def truncated_normal(mean=0, sd=1, low=0, upp=10):
    return truncnorm((low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd)

def create_weight_matrices(no_of_in_nodes, no_of_out_nodes, no_of_hidden_nodes):
    rad = 1 / numpy.sqrt(no_of_in_nodes)
    X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)
    wih = X.rvs((no_of_hidden_nodes, no_of_in_nodes)) # Weight from Input to Hidden Layer
    
    rad = 1 / numpy.sqrt(no_of_hidden_nodes)
    X = truncated_normal(mean=0, sd=1, low=-rad, upp=rad)
    who = X.rvs((no_of_out_nodes, no_of_hidden_nodes)) # Weight from Hidden to Output Layer
    return wih, who

def train(wih, who, learning_rate, input_vector, target_vector):
    input_vector = numpy.array(input_vector, ndmin=2).T # Input Vector needs to be Transposed
    target_vector = numpy.array(target_vector, ndmin=2).T # Target Vector needs to be Transposed
    
    output_hidden = activate(numpy.dot(wih, input_vector))
    output_network = activate(numpy.dot(who, output_hidden))
    
    output_errors = target_vector - output_network
    tmp = output_errors * output_network * (1.0 - output_network)     
    who += learning_rate  * numpy.dot(tmp, output_hidden.T)

    hidden_errors = numpy.dot(who.T, output_errors)
    tmp = hidden_errors * output_hidden * (1.0 - output_hidden)
    wih += learning_rate * numpy.dot(tmp, input_vector.T)

    return wih, who

def identify(wih, who, input_vector):
    input_vector = numpy.array(input_vector, ndmin=2).T

    output_vector = numpy.dot(wih, input_vector)
    output_vector = activate(output_vector)
    
    output_vector = numpy.dot(who, output_vector)
    output_vector = activate(output_vector)

    return output_vector

image_size = 28 # Specified for the MNIST Dataset
no_of_different_labels = 10 # The Numbers from 0 to 9
image_pixels = image_size * image_size
data_path = "C:/Users/HP/Desktop/Athul/Academics B.Tech/Semester 6/Introduction to Data Communication/Mini Project - Digit Recognition/"

# MNIST Dataset has been pickled to make access faster!!!!
with open(data_path + "pickled_mnist.pkl", "br") as fh:
    data = pickle.load(fh)

train_imgs = data[0]
test_imgs = data[1]
train_labels = data[2]
test_labels = data[3]
train_labels_one_hot = data[4]
test_labels_one_hot = data[5]

no_of_in_nodes = image_pixels
no_of_out_nodes = 10 
no_of_hidden_nodes = 100
learning_rate = 0.2

#Create Weighted Matrix
wih, who = create_weight_matrices(no_of_in_nodes, no_of_out_nodes, no_of_hidden_nodes) #Create a Matrix to store the weights between Nodes

# Train the Neural Network (Assign Values to Weighted Matrix using the whole MNIST Dataset)
print("Initiating Training...")
#print(numpy.unique(train_imgs))
start_time = datetime.now()
for i in range(int(len(train_imgs[:1000]))):
    wih, who = train(wih, who, learning_rate, train_imgs[i], train_labels_one_hot[i])
end_time = datetime.now()
print("Dataset has been Trained!!!\nTime taken = ", end = "")
print(end_time - start_time, end = "\n\n")


with open(data_path + "neural_net.pkl", "bw") as line:
    data = (wih, 
            who)
    pickle.dump(data, line)
print("Neural Net Pickled!!!!")


#Test the Neural Network using MNIST Dataset
count = 0;
max_right = 0
max_wrong = 0
min_right = 1
min_wrong = 1
for i in range(len(test_imgs)):
    result = identify(wih, who, test_imgs[i])
    if(int(test_labels[i][0]) != int(numpy.argmax(result))):
        if(max_wrong < numpy.max(result)):
            max_wrong = numpy.max(result)
        if(min_wrong > numpy.max(result)):
            min_wrong = numpy.max(result)
    else:
        count += 1;
        if(max_right < numpy.max(result)):
            max_right = numpy.max(result)
        if(min_right > numpy.max(result)):
            min_right = numpy.max(result)

accuracy = (count / len(test_imgs) ) * 100.0
print("Accuracy from testing with " + str(len(test_imgs)) + " pictures = " + str(accuracy) + "%")
max_right *= 100
max_wrong *= 100
min_right *= 100
min_wrong *= 100
print("Highest Accuracy of Right matches = " + str(max_right) + "%")
print("Highest Accuracy of Wrong matches = " + str(max_wrong) + "%")
print("Lowest Accuracy of Right matches = " + str(min_right) + "%")
print("Lowest Accuracy of Wrong matches = " + str(min_wrong) + "%")
导入时间
进口泡菜
从scipy.stats导入truncnorm
从日期时间导入日期时间
@矢量化
def激活(x):
负屏蔽=x<0
x=x**2
x[负屏蔽]*=-1
返回x
#如果x>0,则返回(x**2),否则(-(x**2))
def截断_正常(平均值=0,标准差=1,下限=0,上限=10):
返回truncnorm((低-平均值)/sd,(upp-平均值)/sd,loc=平均值,标尺=sd)
def创建_权重矩阵(没有_的_in_节点,没有_的_out_节点,没有_的_隐藏_节点):
rad=1/numpy.sqrt(在节点中没有任何节点)
X=截断的_正常值(平均值=0,标准差=1,低值=-rad,upp=rad)
wih=X.rvs((没有隐藏节点的数量,没有隐藏节点的数量))#从输入到隐藏层的权重
rad=1/numpy.sqrt(没有隐藏节点)
X=截断的_正常值(平均值=0,标准差=1,低值=-rad,upp=rad)
who=X.rvs((无_of_out_节点,无_of_hidden_节点))#从隐藏层到输出层的权重
返回wih,谁
def培训(wih、who、学习率、输入向量、目标向量):
input_vector=numpy.array(input_vector,ndmin=2)。T#需要对输入向量进行转置
target_vector=numpy.array(target_vector,ndmin=2)。T#需要对target vector进行转置
输出隐藏=激活(numpy.dot(wih,输入向量))
输出\网络=激活(numpy.dot(谁,输出\隐藏))
输出错误=目标向量-输出网络
tmp=输出错误*输出网络*(1.0-输出网络)
who+=学习率*numpy.dot(tmp,输出隐藏.T)
隐藏的错误=numpy.dot(who.T,输出错误)
tmp=隐藏的错误*输出隐藏*(1.0-输出隐藏)
wih+=学习速率*numpy.dot(tmp,输入向量.T)
返回wih,谁
def标识(wih、who、输入向量):
输入向量=numpy.array(输入向量,ndmin=2).T
输出向量=numpy.dot(wih,输入向量)
输出向量=激活(输出向量)
输出向量=numpy.dot(谁,输出向量)
输出向量=激活(输出向量)
返回输出向量
为MNIST数据集指定的图像大小=28
没有不同的标签=10#从0到9的数字
图像像素=图像大小*图像大小
data_path=“C:/Users/HP/Desktop/Athul/Academics B.Tech/stemmer 6/数据通信简介/迷你项目-数字识别/”
#MNIST数据集已被pickle以加快访问速度!!!!
打开(数据路径+“pickled\u mnist.pkl”、“br”)作为fh:
数据=酸洗负荷(fh)
列车imgs=数据[0]
测试=数据[1]
列车标签=数据[2]
测试标签=数据[3]
列车标签一热=数据[4]
测试标签热=数据[5]
_节点中的_数量=图像像素
无\u个\u个\u节点=10
隐藏节点的数量=100
学习率=0.2
#创建加权矩阵
wih,who=创建权重矩阵(不存在in节点、out节点、hidden节点)#创建矩阵以存储节点之间的权重
#训练神经网络(使用整个MNIST数据集为加权矩阵赋值)
打印(“启动培训…”)
#打印(numpy.unique(序列号imgs))
start_time=datetime.now()
对于范围内的i(int(len(train_imgs[:1000])):
wih,who=培训(wih,who,学习率,培训imgs[i],培训标签[i])
end_time=datetime.now()
打印(“数据集已训练!!!\n执行时间=”,结束=)
打印(结束时间-开始时间,结束=“\n\n”)
以open(data_path+“neural_net.pkl”,“bw”)作为行:
数据=(wih,
(世卫组织)
pickle.dump(数据,行)
打印(“神经网络酸洗!!!!”)
#使用MNIST数据集测试神经网络
计数=0;
最大右=0
最大错误=0
最小右=1
最小错误=1
对于范围内的i(len(测试imgs)):
结果=识别(wih、who、测试\u imgs[i])
如果(int(test_labels[i][0])!=int(numpy.argmax(result)):
如果(最大值错误最小值最大值(结果)):
最小值错误=numpy.max(结果)
其他:
计数+=1;
如果(最大值右最大值(结果)):
min_right=numpy.max(结果)
准确度=(计数/长度(测试imgs))*100.0
打印(“使用“+str(len(test_imgs))”+“pictures=“+str(accurity)+“%”测试的准确度”)
最大右*=100
最大错误*=100
最小右*=100
最小错误*=100
打印(“右匹配的最高精度=”+str(最大右)+“%”)
打印(“错误匹配的最高精度=”+str(最大错误)+“%”)
打印(“右匹配的最低精度=”+str(最小右)+“%”)
打印(“错误匹配的最低精度=”+str(最小错误)+“%”)
它训练神经网络来识别数字

您要平方的数字有多大(或多小,如果为负数)?溢出意味着没有足够的位来存储结果。您可以尝试使用具有较大数据类型的numpy数组。以下是转换现有阵列的示例,也可以在创建时调整其大小:

a=a.astype(numpy.float128)

对于函数,像您这样的矢量化应该可以工作,或者:

negative_mask = a < 0
a = a ** 2
a[negative_mask] *= -1
negative\u mask=a<0
a=a**2
a[负屏蔽]*=-1

您可以将其用于您的功能:

f(x) = { x^2 , x >= 0 and 
        -x^2 , x < 0  }
def squares(x):
    return (x**2) * np.sign(x)

但你的问题似乎来自于大数字的乘法。查看您的最大/最小数字。

如果x>=0
仅在
x
是单个数字时有效,如果是数组则无效。Python
if
是一个更简单的开关,而不是任何类型的迭代器。如何在Numpy数组上实现
if