pytorch和keras测试gpu是否可以调用

pytorch

import numpy as np
import torch
x = np.linspace(0,20,100).astype(np.float32).reshape((-1,1))
y = x*4 + np.random.rand((*x.shape)).astype(np.float32).reshape((-1,1))


import torch.nn as nn
class LinearRegressionModel(nn.Module):

    def __init__(self, input_dim, output_dim):

        super(LinearRegressionModel, self).__init__() 
        self.linear = nn.Linear(input_dim, output_dim)

    def forward(self, x):

        out = self.linear(x)
        return out

input_dim = 1
output_dim = 1

net = LinearRegressionModel(input_dim,output_dim)
net = net.cuda()

criterion = nn.MSELoss()# Mean Squared Loss
l_rate = 0.001
optimizer = torch.optim.SGD(net.parameters(), lr = l_rate) #Stochastic Gradient Descent

epochs = 10000


for epoch in range(epochs):

    epoch +=1
    #increase the number of epochs by 1 every time
    inputs = torch.from_numpy(x)
    labels = torch.from_numpy(y)
    inputs = inputs.cuda()
    labels = labels.cuda()
    outputs = net(inputs)
    
    optimizer.zero_grad()
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()
    
    if epoch % 200 == 0:
        print('epoch {}, loss {}, w {}, b {},'.format(epoch,loss.item(), net.linear.weight.item(), net.linear.bias.item()))


keras

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 2020-08-10 carryhjr
#
# Distributed under terms of the MIT license.

import numpy as np
np.random.seed(1337)  
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
 
X = np.linspace(-1, 1, 200)
np.random.shuffle(X)   
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, )) 
# plot
plt.scatter(X, Y)
plt.show()
 
X_train, Y_train = X[:160], Y[:160]    
X_test, Y_test = X[160:], Y[160:]     
 

model = Sequential()
model.add(Dense(input_dim=1, units=1))
 

model.compile(loss='mse', optimizer='sgd')
 

print('Training -----------')
for step in range(501):
    cost = model.train_on_batch(X_train, Y_train)
    if step % 50 == 0:
        print("After %d trainings, the cost: %f" % (step, cost))

print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值