こすたろーんエンジニアの試行錯誤部屋

作成物の備忘録を書いていきますー

【pytest】assert文と組み合わせた基本的な使い方

python単体テストができるpytestを試してみました
このブログは備忘録です

目次

スポンサーリンク

この記事でわかること

pytestの基本的な使い方

1.実行環境

Jetson Xavier NX
ubuntu18.04
docker
python3.x

2.必要なモジュールをインストール

pip install pytest pytest-cov

3.ファイルとディレクトリを作成

以下のようにファイルとディレクトリを作成します
pytestディレクトリ:テストコード一式を格納
test_function.py:functionのテストコード
(ファイルの先頭にtestをつけるとpytestコマンド実行時に自動でtestが付いたファイルを探して実行してくれます)
function:テスト対象の関数を記述

workspace
├──  pytest/
│    ├── __init__.py
│    └──  test_function.py
│
├── __init__.py
└── function.py

4.function.pyとtest_function.pyにコードを記述

今回はpytestの公式ページにあるコードを流用します

function.py

def inc(x):
    return x + 1

test_function.py

from .. import function
# import function
def test_answer():
    assert function.inc(4) == 5 #←テストが通るように設定

5.テスト実行

function.pyが格納されているディレクトリで以下コマンドを実行します

pytest

実行結果は以下になります

=============================test session starts  =======================================
platform linux -- Python 3.7.16, pytest-7.2.1, pluggy-1.0.0
rootdir: /workspace
plugins: cov-4.0.0, flake8-1.1.1
collected 1 item

pytest/test_function.py .
=============================1 passed in 0.05s =======================================

異常時は以下になります

=============================FAILURES =======================================
_______________________________________________ test_answer _______________________________________

    def test_answer():
>       assert function.inc(3) == 5
E       assert 4 == 5
E        +  where 4 = <function inc at 0x7fafe5e7a0>(3)
E        +    where <function inc at 0x7fafe5e7a0> = function.inc

pytest/test_function.py:6: AssertionError
=============================short test summary info =======================================
FAILED pytest/test_function.py::test_answer - assert 4 == 5
============================= 1 failed in 0.13s ============================================

6. カバレッジ計測

コマンド実行時に以下オプションを受けるとカバレッジ計測できます

pytest --cov .
=============================test session starts  =======================================
platform linux -- Python 3.7.16, pytest-7.2.1, pluggy-1.0.0
rootdir: /workspace
plugins: cov-4.0.0, flake8-1.1.1
collected 1 item

pytest/test_function.py .                                                                                                                                                                                                             [100%]

---------- coverage: platform linux, python 3.7.16-final-0 -----------
Name                      Stmts   Miss  Cover
---------------------------------------------
__init__.py                   0      0   100%
function.py                   2      0   100%
pytest/__init__.py            0      0   100%
pytest/test_function.py       3      0   100%
---------------------------------------------
TOTAL                         5      0   100%


=============================1 passed in 0.15s =======================================

スポンサーリンク

deeplearning関連記事

technoxs-stacker.hatenablog.com technoxs-stacker.hatenablog.com technoxs-stacker.hatenablog.com

参考

pyteyon.hatenablog.com docs.pytest.org

Batch setting of multiple arguments in abseil with flagfile

contents

スポンサーリンク

abstract

How to process arguments using abseil and text files

requirement

Jetson Xavier NX
ubuntu18.04
docker
python3.x
pytorch
->The pytrorch environment on Jetson Xavier NX is shown below.
technoxs-stacker.hatenablog.com

2.procedure

2.1 Write argument settings in a text file
2.2 Specify text file at python runtime

2.1 Write argument settings in a text file

--arch=resnet50
--gpu=0
--batch_size=8
--print_freq=10
--pred_dim=256

2.2 Specify text file at python runtime

CUDA_VISIBLE_DEVICES=0 python3 main_simsiam_single.py --flagfile ./config/simsiam.txt

スポンサーリンク

参考

abseil.io xvideos.hatenablog.com github.com

Build mysql environment with jetsonNX and docker

To learn about databases, we built a mysql environment
This is a memorandum.

contents

スポンサーリンク

abstract

how to build mysql environment with jetsonNX and docker

1.crate a docker file

FROM ubuntu/mysql:8.0-20.04_beta

# Time Zone
ENV TZ Asia/Tokyo

RUN apt update

2.run docker container

Build docker image and start mysql after launching container.

sudo docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=[your_password] mysql
sudo docker exec -it mysql mysql -u root -p

->You will be asked for your password, so log in with the password you set during the docker build.

If the following is displayed, startup is complete

スポンサーリンク

参考

hub.docker.com timesaving.hatenablog.com

【jupyter lab】dockerコンテナで立ち上げたjupyter labのパスワード変更

スポンサーリンク

以前にJetson Xavier NXとDockerでjupyter notebookの環境構築を行いました
technoxs-stacker.hatenablog.com

このままではパスワードがデフォルトのままなので、今回はパスワードの変更を行います

目次

スポンサーリンク

この記事でわかること

dockerコンテナで立ち上げたjupyter labのパスワード変更方法

1.実行環境

Jetson Xavier NX
ubuntu18.04
docker
python3.x

2.手順

1.docker containerを起動

sudo docker run -it --rm --runtime nvidia --network host jupyter/base-notebook:9e63909e0317

2.パスワード変更のコマンドを実行する

jupyter notebook password

->パスワードを聞かれるので任意の値を入力する

3.ブラウザでアクセスする
container立ち上げ時に表示されるURを使って、jupyterへアクセスする
->ログインパスワードは設定した値を入力する

スポンサーリンク

参考

qiita.com

Building a jupyterlab environment that we can use pytorch in using Jetson Xavier NX and docker

I previously created a jupyterlab environment using an existing docker image.
technoxs-stacker.hatenablog.com

I thought I might run pytrorch on jupyterlab in the future, so I created an image with jupyterlab installed based on the previous docker image.

contents

スポンサーリンク

abstract

how to building a jupyterlab environment that we can use pytorch in using Jetson Xavier NX and docker.

1.requirement

Jetson Xavier NX
ubuntu18.04
docker
python3.x

2.Creating a Dockerfile

FROM nvcr.io/nvidia/l4t-ml:r32.5.0-py3
RUN apt-get update && apt-get upgrade -y && apt-get clean
RUN apt-get -y install vim

RUN pip3 install --upgrade pip
RUN pip3 install --ignore-installed PyYAML
RUN pip3 install jupyterlab

ARG USERNAME=user
ARG GROUPNAME=user
ARG UID=1000
ARG GID=1000
ARG PASSWORD=xxxxxxxx
RUN groupadd -g $GID $GROUPNAME && \
    useradd -m -s /bin/bash -u $UID -g $GID -G sudo $USERNAME && \
    echo $USERNAME:$PASSWORD | chpasswd && \
    echo "$USERNAME   ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
USER $USERNAME

3.Creation of image

Create an image with the following command.

sudo docker build . -t xxxx

4.docker container startup

sudo docker run -v path/to/mount/:/mount/name/ -it --rm -p port:port --gpus all --name image_name  xxxx

some of the options used in this project are described
->Please refer to docker's official website for more information.

-v : Specify the directory you want to mount -p : Specify the port connecting the container to the machine --name : Specify the name of the container xxxx : Specify the created image

5.Starting jupyterlab

jupyter notebook --port [port number] --allow-root --ip 0.0.0.0

6.reference

qiita.com

qiita.com

スポンサーリンク

【mysql】コマンドでCREATE,INSERTまでやってみた

この前mysqlの環境を構築しました
technoxs-stacker.hatenablog.com

今回は作成したdbでテーブルを作成しデータを追加するところまでやってみました
このブログは備忘録です

目次

スポンサーリンク

この記事でわかること

mysqlでテーブル作成からデータ追加する方法

1.db作成

お試し用dbを作成します

1.1 rootユーザでmysqlのdocker containerへ入る

sudo docker exec -it docker_image_name mysql -u root -p

-docker_image_name:作成したmysql docker imageを指定

1.2 お試しdbを作成

CREATE DATABASE yourdb;

-yourdb:db名(部分は適当に書き換えてください)

2.ユーザ作成から権限付与

前回の環境構築ではrootユーザで操作を行っていましたが、今回はお試し用のユーザで操作をしていきます

2.1 ユーザ作成

CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'password';

user_nameとpasswordは任意の値に書き換えてください

2.2 権限付与

GRANT ALL PRIVILEGES ON yourdb.* TO 'user_name'@localhost;

付与できているかは以下のコマンドで確認します

show grants for 'user_name'@'localhost';

3.作成したユーザでdbへログイン

3.1 mysqlのdocker container起動&dbログイン

sudo docker exec -it docker_image_name mysql -u user_name -p yourdb

docker_image_name:作成したmysql docker imageを指定
user_name:作成したユーザ

4.テーブル作成

CREATE TABLE otameshi(
  id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(10) DEFAULT 'no_name',
  age INT(3)
  );

今回はidとname、ageを項目にしてます
以下コマンドでカラム値を取得して確認します

DESC otameshi;

5.テーブルへデータ追加

INSERT INTO otameshi(name, age) VALUES('taro', 10);
INSERT INTO otameshi(name, age) VALUES('jiro', 40);
INSERT INTO otameshi(name, age) VALUES('goro', 50);
INSERT INTO otameshi(name, age) VALUES('anko', 10);

以下コマンドでデータ追加できたか確認

SELECT * FROM otameshi;

スポンサーリンク

参考

ssabcire.hatenablog.com charlie1012.hatenablog.jp www.sejuku.net

How to handle command line arguments in metaflow

I have built a metaflow environment before. I wanted to run metaflow by passing arguments. so I looked into it and tried it out.

This is a memorandum.
※See below for environment construction
technoxs-stacker.hatenablog.com

contents

スポンサーリンク

abstract

How to handle command line arguments in metaflow

1.Code modifications

modify the hello world code as follows.

from metaflow import FlowSpec, step, Parameter

class HelloFlow(FlowSpec):
    """
    A flow where Metaflow prints 'Hi'.
    Run this flow to validate that Metaflow is installed correctly.
    """
    strat_msg = Parameter('strat_msg',
                          help='strat messege.',
                          type=str,
                          required=True)
    lr = Parameter('lr',
                   help='Learning rate',
                   default=0.01,
                   type=float)
    batch_size = Parameter('batch_size',
                           help='batch size',
                           default=128,
                           type=int)

    @step
    def start(self):
        """
        This is the 'start' step. All flows must have a step named 'start' that
        is the first step in the flow.
        """
        print('Metaflow says:  %s' % self.strat_msg)
        self.next(self.hello)

    @step
    def hello(self):
        """
        A step for metaflow to introduce itself.
        """
        print('learning rate is %f' % self.lr)
        print('batch size is %d' % self.batch_size)
        self.next(self.end)

    @step
    def end(self):
        """
        This is the 'end' step. All flows must have an 'end' step, which is the
        last step in the flow.
        """
        print("HelloFlow is all done.")


if __name__ == '__main__':
    HelloFlow()

2.memo on the parameter class

name contents example
name parameter name strat_msg
default default value default='hoge'
type parameter type(str, float, int, bool) type=str
help help messege help='hugahuga'
required optional(True/False) required=True

スポンサーリンク

reference

docs.metaflow.org docs.metaflow.org