Generative Adversarial Networks (GANs) for CIFAR10, undesired visualisation output - generative-adversarial-network

I have a GAN to recreate CIFAR10 and I have achieved desired losses after 100 epochs. However I am facing issue in generating the GAN images. Following is my visualisation code for the output.
##########################
### VISUALIZATION
##########################
model.eval()
# Make new images
z = torch.zeros((5, LATENT_DIM)).uniform_(-1.0, 1.0).to(device)
plt.plot(z[1,:].to(torch.device('cpu')).detach())
#generated_features = model.generator_forward(z)
imgs = generated_features.view(-1,32,32)
fig, axes = plt.subplots(nrows=1, ncols=5, figsize=(20, 2.5))
for i, ax in enumerate(axes):
axes[i].imshow(imgs[i].to(torch.device('cpu')).detach())
Here is my code
https://colab.research.google.com/drive/1Y3aJAxaxjviIBm47VVohtxYIU0e7ZUN2?usp=sharing
Thank you in advance!

Related

Combining forest plot and traffic light plot in meta-analysis using R

The software Revman produces a combination of forest plots and traffic light plots in meta-analyses (see e.g. doi: http://dx.doi.org/10.1136/bmjopen-2018-024444, Fig. 3). I am using the package meta fot meta-analysis and robvis for risk of bias. Here is some simple code using example data from the packages:
#creating a forest plot
library(meta)
m <- metacont(n.amlo, mean.amlo, sqrt(var.amlo),
n.plac, mean.plac, sqrt(var.plac),
data = amlodipine, studlab = study)
forest(m)
#creating a risk of bias traffic light plot
library(robvis)
rob_traffic_light(data_rob2, tool = "ROB2")
The important thing is that the rows (i.e. each single study) from the forest plot and the rows from the risk of bias plot are aligned. The problem with using packages such as gridExtra is that you have to play around with the alignment and size or the plots until it fits. My question is if there is a good workaround in R to get plots that are similar to the Revman-plots. The result should look like the figure below.
Here are some ideas to start building your plot.
library(meta)
data(amlodipine)
m <- metacont(n.amlo, mean.amlo, sqrt(var.amlo),
n.plac, mean.plac, sqrt(var.plac),
data = amlodipine, studlab = study)
library(ggplotify)
p1 <- as.ggplot(~forest(m), scale = 1, hjust = 0, vjust = 0)
library(robvis)
p2 <- rob_traffic_light(data_rob2, tool = "ROB2")
library(patchwork)
graphics.off()
dev.new(width=15,height=6)
wrap_plots(p1, p2, widths=c(9,2), heights=c(15,1))

How to incresase igraph distance for each edge in R?

I have a CSV file need to draw a graph.
The graph contains nodes and edges.
Therefore, I used the following code to do it.
start.time <- Sys.time()
#Loading Packages
library(igraph)
library(readr)
library(haven)
#import data
df = read.csv('../../Pre_Draw_Graph_for_R.csv', header = TRUE, encoding = 'UTF-8')
#Creating an iGraph Style Edge List
df_Edge_List <- df
#Creating Graph
df_graph = graph.data.frame(df_Edge_List, directed = TRUE)
#df Network: First Try
#Layout Options
set.seed(3500)
layout1 <- layout.fruchterman.reingold(df_graph)
#Node or vertex Options: Color
V(df_graph)$color <- "yellow"
V(df_graph)[degree(df_graph, mode = "in") > 500]$color <- "red"
#Edge Options: Size
E(df_graph)$color <- "grey"
#Plotting
plot(df_graph, vertex.label=NA)
#plot(df_graph)
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
I can output the following result, but the result has some problems. It shows that every node is very crowded.
I hope to increase the graph distance, but I used a lot of methods already. I cannot fix the problem. I hope to get the following result, but I cannot do it now. I want to make it clear to see the graph.
I used the following to show dput result.
dput(df_graph, file = "G.R")
Due to the data is too big, I used google link to share it
https://drive.google.com/file/d/1wdF8ZKFde8bDSrFrN9e9KfD3tm6dN_s0/view?usp=sharing
Can anyone help me? Thanks
You can get most of the way to a nice graph with a few simple changes. First, change the vertex labeling to numbers as in your second graph. Also, use layout_components so that the components are separated from each other.
library(igraph)
set.seed(1234)
LOC = layout_components(df_graph)
plot(df_graph, layout=LOC, vertex.label=1:vcount(df_graph))
This is OK, but the arrows are a mess. There are two reasons for that: the arrow heads are too big and most (all?) vertices have loops back to themselves. Let's remove the loops and reduce the size of the arrows.
This looks a lot more useable. If you want anything nicer, you will need to start moving around badly placed vertices by hand. That is a lot more work, but you get a nicer picture.
LOC[ 5,] = c(-1.5,-5)
LOC[ 9,] = c(-3,-2)
LOC[16,] = c(-3,14)
LOC[21,] = c(-3,18)
LOC[25,] = c(9,18)
LOC[29,] = c(-9,18)
LOC[35,] = c(-6,15)
LOC[30,] = c(-9,12)
LOC[31,] = c(-6,18)
LOC[37,] = c(1,14)
LOC[38,] = c(-9,15)
LOC[44,] = c(1,18)
plot(DFGS, layout=LOC, vertex.label=1:vcount(df_graph),
edge.arrow.size = 0.5)
More could be done with the hand-editing, but I will leave that to you.

get results of principal Component Analysis in R

I want to get the results of PC1 and PC2 to plot courbe of both in the same graph with tableau desktop.
How to do?
data = read.csv(file="data.csv",header=TRUE, sep=";")
data.active <- data[, 1:30]
library(factoextra)
res.pca <- prcomp(data.active,center = TRUE, scale. = TRUE)
fviz_eig(res.pca)
I think you need to write a csv with the results in between R and Tableau. The code for that is written bellow :
# Principal Components Analysis
res.pca <- stats::prcomp(iris[,-5],center = TRUE, scale. = TRUE)
# Choose number of dimension kept
factoextra::fviz_eig(res.pca)
# Some visualisation
factoextra::fviz_pca_var(res.pca)
factoextra::fviz_pca_ind(res.pca)
factoextra::fviz_pca_biplot(res.pca)
# access transformed points
str(res.pca)
res.pca$x
# save points in csv to use outside of R
utils::write.csv(x = res.pca$x, file = "path/data_pca.csv")
# Load your data and do graphs the usual way with tableau
I used ?prcomp to find the data in the result, you may also push further your analysis and use some nice graphics (biplots of individual / variable, clustering, ...) with R (and import only images in Tableau) using : link

Interactive plot: Manipulate contents of a ggplot2 plot with a sliding bar

Edit: Thank you to Javier for his suggestion. I forgot to mention that I would like to incorporate this interactive plot into a report / dashboard, so something that works with a HTML document from RMarkdown would be ideal, but a dashboard solution would also be fine.
Consider the following plots; the red line represents the actual data, while the green line plots predictions generated by a model:
The predictions of two different models are displayed; one trained over the first 100 hours, and the other over the first 216 hours. Predictions are then generated for the unseen data-points, then plotted.
What I would like to do, is train n models, eg. one every 12 hours in an expanding window fashion. After having done this, I would like to present the results in an interactive fashion where the user can click/slide something to move the vertical line back and forth, thereby changing which model's predictions are displayed. The point would be to intuitively show the effect of different training lengths.
I'm new to shiny and interactive plots in R; can this be done without too much trouble?
You can with the manipulate package for quick interactive plots. Shiny requires more fine-tuning and it is more time-consuming.
Here is a reproducible example for you to test out:
This creates the slider bar:
library(manipulate)
manipulate(plot(1:x), x = slider(1, 100))
Put your code here for the creation of the interactive plot:
manipulate(
plot(cars, xlim = c(0, x.max), type = type, ann = label),
x.max = slider(10, 25, step=5, initial = 25),
type = picker("Points" = "p", "Line" = "l", "Step" = "s"),
label = checkbox(TRUE, "Draw Labels"))
Check out the CRAN manipulate package for more information:
https://cran.r-project.org/web/packages/manipulate/index.html
I was able to do this with the example at the bottom of this link.
library(shiny)
sliderInput("n", "Training length:", 100, min=24, max= 11*24)
renderPlot({
plotPredictCurve(data= df, trainLength= input$n)
})

Knn Regression in R

I am investigating Knn regression methods and later Kernel Smoothing.
I wish to demonstrate these methods using plots in R. I have generated a data set using the following code:
x = runif(100,0,pi)
e = rnorm(100,0,0.1)
y = sin(x)+e
I have been trying to follow a description of how to use "knn.reg" in 9.2 here:
https://daviddalpiaz.github.io/r4sl/k-nearest-neighbors.html#regression
grid2=data.frame(x)
knn10 = FNN::knn.reg(train = x, test = grid2, y = y, k = 10)
My predicted values seem reasonable to me but when I try to plot a line with them on top of my x~y plot I don't get what I'm hoping for.
plot(x,y)
lines(grid2$x,knn10$pred)
I feel like I'm missing something obvious and would really appreciate any help or advice you can offer, thank you for your time.
You just need to sort the x values before plotting the lines.
plot(x,y)
ORD = order(grid2$x)
lines(grid2$x[ORD],knn10$pred[ORD])

Resources