Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to using black for code formatting #81

Merged
merged 1 commit into from
May 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .github/actions/run-tests/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,17 @@ inputs:
required: true
runs:
using: "composite"
steps:
- run: |
steps:
- name: Run Unit Tests
env:
PYTHONWARNINGS: default
run: |
# run slow tests only on scheduled event or if input flag is set
if [ "${{ inputs.event-name }}" == "schedule" ] || [ "${{ inputs.run-slow }}" == "true" ]; then
export QISKIT_TESTS="run_slow"
fi
if [ "${{ inputs.python-version }}" == "3.7" ]; then
export PYTHON="coverage3 run --source qiskit_machine_learning --parallel-mode"
fi
export PYTHONWARNINGS=default
stestr --test-path test run 2> >(tee /dev/stderr out.txt > /dev/null)
shell: bash
3 changes: 2 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,13 @@ jobs:
name: ml${{ matrix.python-version }}
path: ./m${{ matrix.python-version }}/*
- name: Machine Learning Unit Tests without torch under Python ${{ matrix.python-version }}
env:
PYTHONWARNINGS: default
run: |
pip uninstall -y torch
if [ "${{ github.event_name }}" == "schedule" ] || [ "${{ contains(github.event.pull_request.labels.*.name, 'run_slow') }}" == "true" ]; then
export QISKIT_TESTS="run_slow"
fi
export PYTHONWARNINGS=default
stestr --test-path test run
shell: bash
Tutorials:
Expand Down
5 changes: 3 additions & 2 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ disable=no-self-use, # disabled as it is too verbose
unnecessary-pass, # allow for methods with just "pass", for clarity
no-else-return, # relax "elif" after a clause with a return
docstring-first-line-empty, # relax docstring style
import-outside-toplevel
import-outside-toplevel,
bad-continuation, bad-whitespace # differences of opinion with black



Expand Down Expand Up @@ -215,7 +216,7 @@ max-nested-blocks=5
[FORMAT]

# Maximum number of characters on a single line.
max-line-length=100
max-line-length=105

# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
Expand Down
4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ please ensure that:
make style
```
from the root of the Machine Learning repository clone for lint and style conformance checks.

If your code fails the local style checks (specifically the black
code formatting check) you can use `make black` to automatically
fix update the code formatting.

For unit testing please see [Testing](#testing) section below.

Expand Down
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ mypy:
mypy qiskit_machine_learning test tools

style:
pycodestyle qiskit_machine_learning test tools
black --check qiskit_machine_learning test tools

black:
black qiskit_machine_learning test tools

test:
python -m unittest discover -v test
Expand Down
5 changes: 1 addition & 4 deletions qiskit_machine_learning/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,4 @@
from .version import __version__
from .exceptions import QiskitMachineLearningError

__all__ = [
'__version__',
'QiskitMachineLearningError'
]
__all__ = ["__version__", "QiskitMachineLearningError"]
37 changes: 20 additions & 17 deletions qiskit_machine_learning/algorithms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,23 +60,26 @@

from .classifiers import QSVC, VQC, NeuralNetworkClassifier
from .regressors import QSVR, VQR, NeuralNetworkRegressor
from .distribution_learners import (DiscriminativeNetwork,
GenerativeNetwork,
NumPyDiscriminator,
PyTorchDiscriminator,
QuantumGenerator, QGAN)
from .distribution_learners import (
DiscriminativeNetwork,
GenerativeNetwork,
NumPyDiscriminator,
PyTorchDiscriminator,
QuantumGenerator,
QGAN,
)

__all__ = [
'QSVC',
'NeuralNetworkClassifier',
'VQC',
'QSVR',
'NeuralNetworkRegressor',
'VQR',
'DiscriminativeNetwork',
'GenerativeNetwork',
'NumPyDiscriminator',
'PyTorchDiscriminator',
'QuantumGenerator',
'QGAN',
"QSVC",
"NeuralNetworkClassifier",
"VQC",
"QSVR",
"NeuralNetworkRegressor",
"VQR",
"DiscriminativeNetwork",
"GenerativeNetwork",
"NumPyDiscriminator",
"PyTorchDiscriminator",
"QuantumGenerator",
"QGAN",
]
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,4 @@
from .qsvc import QSVC
from .vqc import VQC

__all__ = [
'NeuralNetworkClassifier',
'QSVC',
'VQC'
]
__all__ = ["NeuralNetworkClassifier", "QSVC", "VQC"]
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,13 @@

from ...exceptions import QiskitMachineLearningError
from ...neural_networks import NeuralNetwork
from ...utils.loss_functions import (Loss, L1Loss, L2Loss, CrossEntropyLoss,
CrossEntropySigmoidLoss)
from ...utils.loss_functions import (
Loss,
L1Loss,
L2Loss,
CrossEntropyLoss,
CrossEntropySigmoidLoss,
)


class NeuralNetworkClassifier(ClassifierMixin):
Expand All @@ -29,11 +34,14 @@ class NeuralNetworkClassifier(ClassifierMixin):
for more details.
"""

def __init__(self, neural_network: NeuralNetwork,
loss: Union[str, Loss] = 'l2',
one_hot: bool = False,
optimizer: Optimizer = None,
warm_start: bool = False):
def __init__(
self,
neural_network: NeuralNetwork,
loss: Union[str, Loss] = "l2",
one_hot: bool = False,
optimizer: Optimizer = None,
warm_start: bool = False,
):
"""
Args:
neural_network: An instance of an quantum neural network. If the neural network has a
Expand Down Expand Up @@ -63,20 +71,20 @@ def __init__(self, neural_network: NeuralNetwork,
"""
self._neural_network = neural_network
if len(neural_network.output_shape) > 1:
raise QiskitMachineLearningError('Invalid neural network output shape!')
raise QiskitMachineLearningError("Invalid neural network output shape!")
if isinstance(loss, Loss):
self._loss = loss
else:
if loss.lower() == 'l1':
if loss.lower() == "l1":
self._loss = L1Loss()
elif loss.lower() == 'l2':
elif loss.lower() == "l2":
self._loss = L2Loss()
elif loss.lower() == 'cross_entropy':
elif loss.lower() == "cross_entropy":
self._loss = CrossEntropyLoss()
elif loss.lower() == 'cross_entropy_sigmoid':
elif loss.lower() == "cross_entropy_sigmoid":
self._loss = CrossEntropySigmoidLoss()
else:
raise QiskitMachineLearningError(f'Unknown loss {loss}!')
raise QiskitMachineLearningError(f"Unknown loss {loss}!")

self._one_hot = one_hot
self._optimizer = optimizer
Expand All @@ -85,27 +93,27 @@ def __init__(self, neural_network: NeuralNetwork,

@property
def neural_network(self):
""" Returns the underlying neural network."""
"""Returns the underlying neural network."""
return self._neural_network

@property
def loss(self):
""" Returns the underlying neural network."""
"""Returns the underlying neural network."""
return self._loss

@property
def one_hot(self):
""" Returns the underlying neural network."""
"""Returns the underlying neural network."""
return self._one_hot

@property
def warm_start(self) -> bool:
""" Returns the warm start flag."""
"""Returns the warm start flag."""
return self._warm_start

@warm_start.setter
def warm_start(self, warm_start: bool) -> None:
""" Sets the warm start flag."""
"""Sets the warm start flag."""
self._warm_start = warm_start

def fit(self, X: np.ndarray, y: np.ndarray): # pylint: disable=invalid-name
Expand All @@ -127,7 +135,8 @@ def fit(self, X: np.ndarray, y: np.ndarray): # pylint: disable=invalid-name

if len(y.shape) != 1 or len(np.unique(y)) != 2:
raise QiskitMachineLearningError(
f"Current settings only applicable to binary classification! Got labels: {y}")
f"Current settings only applicable to binary classification! Got labels: {y}"
)

def objective(w):

Expand Down Expand Up @@ -166,7 +175,10 @@ def objective_grad(w):
# TODO: do batch eval
y_predict = self._neural_network.forward(x, w)
_, weight_prob_grad = self._neural_network.backward(x, w)
grad += self._loss.gradient(y_predict[0], y_target) @ weight_prob_grad[0, :]
grad += (
self._loss.gradient(y_predict[0], y_target)
@ weight_prob_grad[0, :]
)
return grad

else:
Expand All @@ -186,17 +198,22 @@ def objective_grad(w):
# TODO: do batch eval
_, weight_prob_grad = self._neural_network.backward(x, w)
for i in range(num_classes):
grad += weight_prob_grad[
0, i, :].reshape(grad.shape) * self._loss(i, y_target)
grad += weight_prob_grad[0, i, :].reshape(
grad.shape
) * self._loss(i, y_target)
return grad

if self._warm_start and self._fit_result is not None:
initial_point = self._fit_result[0]
else:
initial_point = np.random.rand(self._neural_network.num_weights)

self._fit_result = self._optimizer.optimize(self._neural_network.num_weights, objective,
objective_grad, initial_point=initial_point)
self._fit_result = self._optimizer.optimize(
self._neural_network.num_weights,
objective,
objective_grad,
initial_point=initial_point,
)
return self

def predict(self, X: np.ndarray) -> np.ndarray: # pylint: disable=invalid-name
Expand All @@ -211,7 +228,9 @@ def predict(self, X: np.ndarray) -> np.ndarray: # pylint: disable=invalid-name
The predicted classes.
"""
if self._fit_result is None:
raise QiskitMachineLearningError('Model needs to be fit to some training data first!')
raise QiskitMachineLearningError(
"Model needs to be fit to some training data first!"
)
if self._neural_network.output_shape == (1,):
predict = np.sign(self._neural_network.forward(X, self._fit_result[0]))
else:
Expand Down
7 changes: 3 additions & 4 deletions qiskit_machine_learning/algorithms/classifiers/qsvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ class QSVC(SVC):
qsvc.predict(sample_test)
"""

def __init__(self, *args,
quantum_kernel: Optional[QuantumKernel] = None, **kwargs):
def __init__(self, *args, quantum_kernel: Optional[QuantumKernel] = None, **kwargs):
"""
Args:
quantum_kernel: QuantumKernel to be used for classification.
Expand All @@ -55,11 +54,11 @@ def __init__(self, *args,

@property
def quantum_kernel(self) -> QuantumKernel:
""" Returns quantum kernel """
"""Returns quantum kernel"""
return self._quantum_kernel

@quantum_kernel.setter
def quantum_kernel(self, quantum_kernel: QuantumKernel):
""" Sets quantum kernel """
"""Sets quantum kernel"""
self._quantum_kernel = quantum_kernel
self.kernel = self._quantum_kernel.evaluate
Loading