简单的自动标签库
Torch-Yottaxx的Python项目详细描述
简易手电筒
implement by numpy
亲笔签名
张量
实现:基本的张量计算,同时记录张量与张量梯度的相关性。在
功能
机具:激活功能。那里现在只有谭。在
参数
实现:使用requires_grad=True快速创建随机张量。在
模块
机具:记录所有参数
optim
实现:模块优化。在
测试
自动加载功能测试 在
示例
嘶嘶嗡嗡声
importnumpyasnpfromtypingimportListfromautogradimportTensor,Parameter,Modulefromautograd.optimimportSGDfromautograd.functionimporttanh"""print the numbers 1 to 100,except if the number is divisible by 3 print "fizz" if the number is divisible by 5 print "fizz" if the number is divisible by 15 print "fizz_buzz""""defbinary_encode(x:int)->List[int]:return[x>>i&1foriinrange(10)]deffizz_buzz_encode(x:int)->List[int]:ifx%15==0:return[0,0,0,1]elifx%5==0:return[0,0,1,0]elifx%3==0:return[0,1,0,0]else:return[1,0,0,0]x_train=Tensor([binary_encode(x)forxinrange(101,1024)])y_train=Tensor([fizz_buzz_encode(x)forxinrange(101,1024)])classFizzBuzzModule(Module):def__init__(self,num_hidden:int=50)->None:self.w1=Parameter(10,num_hidden)self.b1=Parameter(num_hidden)self.w2=Parameter(num_hidden,4)self.b2=Parameter(4)defpredict(self,in_puts:Tensor):# inputs (batch_size,10)x1=inputs@self.w1+self.b1# (batch_size,num_hidden)x2=tanh(x1)x3=x2@self.w2+self.b2# (batch_size,4)returnx3optimizer=SGD(lr=0.001)batch_size=32module=FizzBuzzModule()starts=np.arange(0,x_train.shape[0],batch_size)forepochinrange(10000):epoch_loss=0.0np.random.shuffle(starts)forstartinstarts:end=start+batch_sizemodule.zero_grad()inputs=x_train[start:end]predicted=module.predict(inputs)actual=y_train[start:end]errors=predicted-actualloss=(errors*errors).sum()loss.backward()epoch_loss+=loss.dataoptimizer.step(module)print(epoch,epoch_loss)num_correct=0forxinrange(1,101):inputs=Tensor([binary_encode(x)])predicted=module.predict(inputs)[0]predicted_idx=np.argmax(predicted.data)actual_idx=np.argmax(fizz_buzz_encode(x))labels=[str(x),"fizz","buzz","fizz_buzz"]ifpredicted_idx==actual_idx:num_correct+=1print(x,labels[predicted_idx],labels[actual_idx])print(num_correct,"/100")
- 项目
标签: