Pennylane Codebook

Wejdz na stronę codebook. Zarejestruj się i zaloguj.

IQC: Introduction to Quantum Computing

Wykonaj pierwsze trzy ćwiczenia z sekcji wprowadzenie od obliczeń kwantowych.

\[ \newcommand{\bra}[1]{\left \langle #1 \right \rvert} \newcommand{\ket}[1]{\left \rvert #1 \right \rangle} \newcommand{\braket}[2]{\left \langle #1 \middle \rvert #2 \right \rangle} \]

PyTorch Regresja liniowa

import torch
import numpy as np
import matplotlib.pyplot as plt

class LinearRegression(torch.nn.Module):

    def __init__(self, inputSize, outputSize):
        super(LinearRegression, self).__init__()
        self.linear = torch.nn.Linear(inputSize, outputSize)

    def forward(self, x):
        out = self.linear(x)
        return out


inputDim = 1
outputDim = 1
learningRate = 0.01
epochs = 100

model = LinearRegression(inputDim, outputDim)

x = np.arange(11)
print(f"dane: {x}")

y = [2*el - 1 for el in x]
print(f"target: {y}")

# dostosowanie do pytorch
y  = np.array(y, dtype=np.float32)
x_train = np.array(x, dtype=np.float32)
x_train, y_train = x_train.reshape(-1, 1), y.reshape(-1, 1)

inputs = torch.from_numpy(x_train)
outputs = torch.from_numpy(y_train)

criterion = torch.nn.MSELoss() 
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
# petla uczaca 
for epoch in range(epochs):
    # forward pass and loss
    y_predicted = model(inputs)
    loss = criterion(y_predicted, outputs)
    
    # backward pass
    loss.backward()
    
    # updates
    optimizer.step()
    
    # zero gradients
    optimizer.zero_grad()
    
    if (epoch+1) % 10 == 0:
        print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')

with torch.no_grad():
    predicted = model(inputs)

plt.clf()
plt.plot(x_train, y_train, 'go', label='True data', alpha=0.5)
plt.plot(x_train, predicted, '--', label='Predictions', alpha=0.5)
plt.legend(loc='best')
plt.show()
dane: [ 0  1  2  3  4  5  6  7  8  9 10]
target: [-1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
epoch: 10, loss = 0.2569
epoch: 20, loss = 0.2296
epoch: 30, loss = 0.2052
epoch: 40, loss = 0.1834
epoch: 50, loss = 0.1640
epoch: 60, loss = 0.1465
epoch: 70, loss = 0.1310
epoch: 80, loss = 0.1171
epoch: 90, loss = 0.1046
epoch: 100, loss = 0.0935

PyTorch Regresja logistyczna

import torch
import numpy as np
import matplotlib.pyplot as plt

class LogisticRegression(torch.nn.Module):

    def __init__(self, inputSize, outputSize):
        super(LogisticRegression, self).__init__()
        self.linear = torch.nn.Linear(inputSize, outputSize)

    def forward(self, x):
        x = self.linear(x)
        y_pred = torch.sigmoid(x)
        return y_pred


inputDim = 1
outputDim = 1
learningRate = 0.001
epochs = 100

model = LogisticRegression(inputDim, outputDim)

x = np.arange(11)
print(f"dane: {x}")

import random
y = [random.choice([0,1]) for _ in range(11)]
print(f"target: {y}")

# dostosowanie do pytorch
y  = np.array(y, dtype=np.float32)
x_train = np.array(x, dtype=np.float32)
x_train, y_train = x_train.reshape(-1, 1), y.reshape(-1, 1)

inputs = torch.from_numpy(x_train)
outputs = torch.from_numpy(y_train)

criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
# petla uczaca 
for epoch in range(epochs):
    # forward pass and loss
    y_predicted = model(inputs)
    loss = criterion(y_predicted, outputs)
    
    # backward pass
    loss.backward()
    
    # updates
    optimizer.step()
    
    # zero gradients
    optimizer.zero_grad()
    
    if (epoch+1) % 10 == 0:
        print(f'epoch: {epoch+1}, loss = {loss.item():.4f}')


with torch.no_grad():
    y_predicted = model(inputs) 
    acc = y_predicted.eq(outputs).sum() / float(y_train.shape[0])  # accuracy
    print(f'accuracy = {acc:.4f}')
dane: [ 0  1  2  3  4  5  6  7  8  9 10]
target: [0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0]
epoch: 10, loss = -0.0000
epoch: 20, loss = -0.0000
epoch: 30, loss = -0.0000
epoch: 40, loss = -0.0000
epoch: 50, loss = -0.0000
epoch: 60, loss = -0.0000
epoch: 70, loss = -0.0000
epoch: 80, loss = -0.0000
epoch: 90, loss = -0.0000
epoch: 100, loss = -0.0000
accuracy = 0.0000