plt.show() not showing images - python

My code is as follow:
import torch
import torchvision
import torchvision.transforms as transforms
import numpy
import matplotlib
import matplotlib.pyplot as plt
torch.set_printoptions(linewidth=120)
train_set = torchvision.datasets.FashionMNIST(
root='./data/FashionMNIST',
train=True,
download=True,
transform=transforms.Compose([
transforms.ToTensor()
])
)
train_loader = torch.utils.data.DataLoader(
train_set, batch_size=10
)
sample = next(iter(train_set))
image, label = sample
plt.imshow(image.squeeze(), cmap='gray')
plt.show()
print(f"label:{label}")
I try to print an image via matploblib.pylot but nothing happens.
Plus, I'm doing this on my linux server, while the same code works quite well locally on my vscode.

As an alternative to viewing your matplolib window remotely, you can always save your plot as an image file and copy it to your local machine. This is as simple as using plt.savefig
plt.save(f'label:{label}.png')

Related

tqdm.notebook progress bar is not running

I am running a model using tqdm.notebook to check the progress using python3.8. However, the progress bar is not running though the generation works okay.
It just shows this on and on.
Here is my following code, and the model I'm running.
import numpy as np
import tensorflow as tf
from midi_ddsp.utils.midi_synthesis_utils import synthesize_mono_midi, conditioning_df_to_audio
from midi_ddsp.utils.inference_utils import get_process_group
from midi_ddsp.midi_ddsp_synthesize import load_pretrained_model
from midi_ddsp.data_handling.instrument_name_utils import INST_NAME_TO_ID_DICT
from tqdm.notebook import tqdm
# -----MIDI Synthesis-----
midi_file = '/Users/midi-ddsp/midi_example/ode_to_joy.mid'
# Load pre-trained model
synthesis_generator, expression_generator = load_pretrained_model()
# Synthesize with violin:
instrument_name = 'violin'
instrument_id = INST_NAME_TO_ID_DICT[instrument_name]
# Run model prediction
midi_audio, midi_control_params, midi_synth_params, conditioning_df = synthesize_mono_midi(synthesis_generator,
expression_generator,
midi_file, instrument_id,
output_dir=None)
synthesized_audio = midi_audio # The synthesized audio
conditioning_df_changed = conditioning_df.copy()
idk what's the problem. Hope someone can tell me. I appreciate it!

How can I plot my trained model result on video using Detectron2?

I am new on using Detectron2. I want to load the video from local drive. And then, do detection using my trained model using Detectron2's VideoVisualizer.
I tried to find a tutorial about this. But it does not exist. Could you please what do I do?
Thank you
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import tqdm
import cv2
# import some common detectron2 utilities
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.video_visualizer import VideoVisualizer
from detectron2.utils.visualizer import ColorMode, Visualizer
from detectron2.data import MetadataCatalog
import time
video = cv2.VideoCapture('gdrive/My Drive/video.mp4')
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
cfg.OUTPUT_DIR = 'gdrive/My Drive/mask_rcnn/'
cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7 # set threshold for this model
predictor = DefaultPredictor(cfg)
v = VideoVisualizer(MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), ColorMode.IMAGE)
First, check the following tutorial (you can skip training parts if you don't want to train on your own data).
https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=Vk4gID50K03a
Then, look at the following code to inference on video.
https://github.com/facebookresearch/detectron2/blob/master/demo/demo.py

Cvlib not showing boxes, labels and confidence

I am trying to replicate a simple object detection that I found in on website.
import cv2
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox
im = cv2.imread('downloads.jpeg')
bbox, label, conf = cv.detect_common_objects(im)
output_image = draw_bbox(im, bbox, label, conf)
plt.imshow(output_image)
plt.show()
All required libraries are installed and there are no errors running the code. However, it does not show the output image with the boxes, labels and confidence. How do I fix it?
#After loading an image use an assert:
img = cv2.imread('downloads.jpeg')
assert not isinstance(img,type(None)), 'image not found'

Python - dot file to png file not found error

I am trying to convert dot file into a png or jpeg file where I can view the Random Forest Tree. I am following this tutorial: https://towardsdatascience.com/how-to-visualize-a-decision-tree-from-a-random-forest-in-python-using-scikit-learn-38ad2d75f21c.
I am getting error FileNotFoundError: [WinError 2] The system cannot find the file specified
I can see that tree.dot is there and I am able to open it. Trying to find why it is not reading it? Thanks.
from sklearn.datasets import load_iris
iris = load_iris()
# Model (can also use single decision tree)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10)
# Train
model.fit(iris.data, iris.target)
# Extract single tree
estimator = model.estimators_[5]
from sklearn.tree import export_graphviz
# Export as dot file
export_graphviz(estimator, out_file='tree.dot',
feature_names = iris.feature_names,
class_names = iris.target_names,
rounded = True, proportion = False,
precision = 2, filled = True)
<<error occurs here>>
# Convert to png using system command (requires Graphviz)
from subprocess import call
call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])
# Display in jupyter notebook
from IPython.display import Image
Image(filename = 'tree.png')
I ran through docker - ubuntu image and ran: RUN apt-get install graphviz -y in the Dockerfile. It started to work. Then used dot -Tpng tree.dot -o tree.png

Random Forest on Tensorflow at Google Cloud Datalab restarting kernel (Code not working)

I am using the data from the following Kaggle competition to train Random Forest on Tensorflow - https://www.kaggle.com/c/santander-product-recommendation
The code was working fine a day ago but now whenever I run the training code for the Random Forest: I get the following message (This is not an error message on the code but for the jupyter kernel):
The kernel appears to have died. It will restart automatically.
I am using the following code:
import tensorflow as tf
import numpy as np
import pandas as pd
import math
import os
from glob import glob
import google.datalab.bigquery as bq
print('Libraries Imported')
trainingdata = bq.Query('SELECT * FROM `kagglesantander.training`')
train_dataset = trainingdata.execute(output_options=bq.QueryOutput.dataframe()).result()
print('Train Data Fetched')
X = train_dataset.iloc[:,1:-1]
y = train_dataset.iloc[:,-1]
x_train = X.astype(np.float32).values
y_train = y.astype(np.float32).values
print('Data Prepared')
params = tf.contrib.tensor_forest.python.tensor_forest.ForestHParams(
num_classes=1, num_features=369, num_trees = 10).fill()
print("Params =")
print(vars(params))
# Remove previous checkpoints so that we can re-run this step if necessary.
for f in glob("./ModelTrain/*"):
os.remove(f)
classifier = tf.contrib.tensor_forest.client.random_forest.TensorForestEstimator(
params, model_dir="./ModelTrain/")
classifier.fit(x=x_train, y=y_train)
print('Forest Trained')
The error is happening due to the line:
classifier.fit(x=x_train, y=y_train)
As I tried the code without the line and it was working fine

Categories

Resources