Assigning the result of corrplot to a variable - correlation

I am using the function corrplot from corrplot package to generate a plot of a correlation matrix created with cor.test (psych package).
When I try to save the result into a variable, the variable is NULL.
Anyone could advice, please?
library(corrplot)
library(psych)
library(ggpubr)
data(iris)
res_pearson.c_setosa<-iris%>%
filter(Species=="setosa")%>%
select(Sepal.Length:Petal.Width)%>%
corr.test(., y = NULL, use = "complete",method="pearson",adjust="bonferroni", alpha=.05,ci=TRUE,minlength=5)
corr.a<-corrplot(res_pearson.c_setosa$r[,1:3],
type="lower",
order="original",
p.mat = res_pearson.c_setosa$p[,1:3],
sig.level = 0.05,
insig = "blank",
col=col4(10),
tl.pos = "ld",
tl.cex = .8,
tl.srt=45,
tl.col = "black",
cl.cex = .8)+
my.theme #this is a theme() piece, but if I take this away, the result is a list rather than a plot

You can create your own function where you put recordPlot at the end to save the plot. After that you can save the output of the function in a variable. Here is a reproducible example:
library(corrplot)
library(psych)
library(ggpubr)
library(dplyr)
data(iris)
res_pearson.c_setosa<-iris%>%
filter(Species=="setosa")%>%
select(Sepal.Length:Petal.Width)%>%
corr.test(., y = NULL, use = "complete",method="pearson",adjust="bonferroni", alpha=.05,ci=TRUE,minlength=5)
your_function <- function(ff){
corr.a<-corrplot(ff$r[,1:3],
type="lower",
order="original",
p.mat = ff$p[,1:3],
sig.level = 0.05,
insig = "blank",
#col=col4(10),
tl.pos = "ld",
tl.cex = .8,
tl.srt=45,
tl.col = "black",
cl.cex = .8)
#my.theme #this is a theme() piece, but if I take this away, the result is a list rather than a plot
recordPlot() # save the latest plot
}
your_function(res_pearson.c_setosa)
p <- your_function(res_pearson.c_setosa)
p
Created on 2022-07-13 by the reprex package (v2.0.1)
As you can see, the variable p outputs the plot.

Related

Fine-tune a pre-trained model

I am new to transformer based models. I am trying to fine-tune the following model (https://huggingface.co/Chramer/remote-sensing-distilbert-cased) on my dataset. The code:
enter image description here
and I got the following error:
enter image description here
I will be thankful if anyone could help.
The preprocessing steps I followed:
input_ids_t = []
attention_masks_t = []
for sent in df_train['text_a']:
encoded_dict = tokenizer.encode_plus(
sent,
add_special_tokens = True,
max_length = 128,
pad_to_max_length = True,
return_attention_mask = True,
return_tensors = 'tf',
)
input_ids_t.append(encoded_dict['input_ids'])
attention_masks_t.append(encoded_dict['attention_mask'])
# Convert the lists into tensors.
input_ids_t = tf.concat(input_ids_t, axis=0)
attention_masks_t = tf.concat(attention_masks_t, axis=0)
labels_t = np.asarray(df_train['label'])
and i did the same for testing data. Then:
train_data = tf.data.Dataset.from_tensor_slices((input_ids_t,attention_masks_t,labels_t))
and the same for testing data
It sounds like you are feeding the transformer_model 1 input instead of 3. Try removing the square brackets around transformer_model([input_ids, input_mask, segment_ids])[0] so that it reads transformer_model(input_ids, input_mask, segment_ids)[0]. That way, the function will have 3 arguments and not just 1.

Error in (function (classes, fdef, mtable) unable to find an inherited method for function ‘krige’ for signature ‘"formula", "tbl_df"’

I have a strange Error and actually don't know how to solve it, even after checking other posts. Everything runs until the Kriging and then I receive the error: Error in (function (classes, fdef, mtable) unable to find an inherited method for function ‘krige’ for signature ‘"formula", "tbl_df"’
The strange thing is that everything worked a few days ago, I did not change anything in the code and now it doesn't run anymore. Some other posts related the problem with the Raster, but I could not find any discrepances. Is there something because of recent updates? I use for example the sp package.
Unfortunately I cannot provide the data I use, hopefully it can be solved without.
How can I solve the issue? Thank you in advance for the help.
homeDir = "D:/Folder/DataXYyear/"
y = 1992
Source = paste("Year", y, ".csv")
File = file.path(homeDir,Source)
GWMeas <- read_csv(File)
GWMeasX <- na.omit(GWMeas)
ggplot(
data = GWMeasX,
mapping = aes(x = X, y = Y, color = level)
) +
geom_point(size = 3) +
scale_color_viridis(option = "B") +
theme_classic()
GWMX_sf <- st_as_sf(GWMeasX, coords = c("X", "Y"), crs = 25832) %>%
cbind(st_coordinates(.))
v_emp_OK <- gstat::variogram(
level~1,
as(GWMX_sf, "Spatial") # switch from {sf} to {sp}
)
v_mod_OK <- automap::autofitVariogram(level~1, as(GWMX_sf, "Spatial"), model = "Sph")$var_model
GWMeasX %>% as.data.frame %>% glimpse
GW.vgm <- variogram(level~1, locations = ~X+Y, data = GWMeasX) # calculates sample variogram values
GW.fit <- fit.variogram(GW.vgm, model=vgm(model = "Gau")) # fit model
sf_GWlevel <- st_as_sf(GWMeasX, coords = c("X", "Y"), crs = 25833)
grd_sf <- sf_GWlevel %>%
st_bbox() %>%
st_as_sfc() %>%
st_make_grid(
cellsize = c(5000, 5000), # 5000m pixel size
what = "centers"
) %>%
st_as_sf() %>%
cbind(., st_coordinates(.))
grid <- as(grd_sf, "Spatial")
gridded(grid) <- TRUE
grid <- as(grid, "SpatialPixels")
createGrid <- function(XY.Spacing)
crs(grid) <- crs(GWMX_sf)
OK3 <- krige(formula = level~1, # variable to interpolate
data = GWMX_sf, # gauge data
newdata = grid, # grid to interpolate on
model = v_mod_OK, # variogram model to use
nmin = 4, # minimum number of points to use for the interpolation
nmax = 20, # maximum number of points to use for the interpolation
maxdist = 120e3 # maximum distance of points to use for the interpolation
)

How to adjust transparency (alpha) in seaborn swarmplot?

I have a swarmplot:
sns.swarmplot(y = "age gap corr", x = "cluster",
data = scatter_data, hue = 'group', dodge=True)
and I would like to adjust the transparency of the dots:
sns.swarmplot(y = "age gap corr", x = "cluster",
data = scatter_data, hue = 'group', dodge=True,
scatter_kws = {'alpha': 0.1})
sns.swarmplot(y = "age gap corr", x = "cluster",
data = scatter_data, hue = 'group', dodge=True,
plot_kws={'scatter_kws': {'alpha': 0.1}})
but neither of the above methods works.
any help is appreciated.
You can simply input the alpha argument directly in the swarmplot function:
import seaborn as sns
df = sns.load_dataset('diamonds').sample(1000)
sns.swarmplot(data=df, x='cut', y='carat', hue='color', alpha=0.5)
The documentation for swarmplot states
kwargs : key, value mappings
Other keyword arguments are passed through to matplotlib.axes.Axes.scatter().
Thus, you don't need to use scatter_kws={...}.
Compare this to, e.g., sns.lmplot, which states
{scatter,line}_kws : dictionaries
Additional keyword arguments to pass to plt.scatter and plt.plot.

Why spatial transformer network (STN) is not working on image

I am trying to subject a one image array to STN using code from https://github.com/kevinzakka/spatial-transformer-network :
def STNfn(x):
import tensorflow as tf
print(x.shape)
B,W,H,C = x.shape
# identity transform
initial = np.array([[1., 0, 0], [0, 1., 0]])
initial = initial.astype('float32').flatten()
# localization network
n_fc = 6
W_fc1 = tf.Variable(tf.zeros([H*W*C, n_fc]), name='W_fc1')
b_fc1 = tf.Variable(initial_value=initial, name='b_fc1')
h_fc1 = tf.matmul(tf.zeros([B, H*W*C]), W_fc1) + b_fc1
# spatial transformer layer
from stn import spatial_transformer_network as transformer
h_trans = transformer(x, h_fc1)
return h_trans
fname = 'testimage.jpg'
img = plt.imread(fname)
img = STNfn(np.array([img]))
However, I am getting following error:
TypeError: Input 'y' of 'Mul' Op has type uint8
that does not match type float32 of argument 'x'.
I have tried to replace float32 with np.uint8, but it does not help.
Where is the problem and how can it be solved?
n_fc = 6 has to be a float32 maybe? Not familar with Python, in Java it is like 6.0f for float and just 6 is integer.

My R function is returning an incorrect result when invoked by Renjin

If I invoke my R script's compute_score function in R studio, the geography score returned is 68.18, which is what I expect. However when I invoke the same function in Renjin it is returning 60.0, which is incorrect. I have used the exact same value for the function argument in both cases. Any idea what could be causing this? Is there any chance this could be a Renjin bug?
The end of my compute_score function looks like this...
compute_score <- function(CIF)
{
...
response = list(
geographyScore = as.numeric(geographyScore),
industryScore = as.numeric(industryScore),
productScore = as.numeric(productScore),
channelScore = as.numeric(channelScore),
clientTypeScore = as.numeric(clientTypeScore),
transactionScore = as.numeric(transactionScore),
tags = tags
)
return(response)
}
And I invoke it in my Java class using the following lines of code...
ScriptEngine engine = new RenjinScriptEngineFactory().getScriptEngine();
File file = new File(getClassLoader().getResource("sample_interface.R").getFile());
engine.eval(new java.io.FileReader(file));
ListVector resList = (ListVector) engine.eval("compute_score(" + buildRRequest(buildRequest(ACCOUNT_HOLDER, NP_RETAIL, ISO_SWISS, ISO_WESTERN_SAHARA, false)) + ")");
And this is what resList evaluates to when I check in Intellij debugger:
list(geographyScore = 60.0, industryScore = 75.0, productScore = 100.0, channelScore = 50.0, clientTypeScore = 25.0, transactionScore = 100.0, tags = list())
All the other fields return correctly other than geography, that should definitely be 68.18182, would someone have any idea why it isn't?
Just to remind you, passing in the exact same value when invoking the function in RStudio gives me 68.18182, invoking the same function with the same argument value using renjin's eval operation gives me a score of 60.0, at first glance it looks like it is rounding but Im not so sure, any help would be appreciated greatly.

Resources