numpy - simple way to check if object is numpy float array - numpy

Question
Is there a better/simpler way to check if an object is numpy float array?
import numpy as np
isinstance(x, np.ndarray) and issubclass(x.dtype.type, np.floating)

Related

'numpy.dtype' object has no attribute 'base_dtype' in keras

I have below code which I am trying to understand keras mean and want to get pooled_grads print. While printing I am getting below error
import numpy as np
import tensorflow as tf
arr3 = np.array([ [
[1,2,3],
[4,5,6]
],
[
[1,2,3],
[4,5,6]
],
[
[1,2,3],
[4,5,6]
]
]
)
#print("Arr shape", arr3.shape)
import keras.backend as K
import numpy as np
pooled_grads = K.mean(arr3, axis=(0, 1, 2))
print("------------------------")
print(pooled_grads)
I am getting below error
AttributeError: 'numpy.dtype' object has no attribute 'base_dtype'
Most Keras backend functions expect Keras tensors as inputs. If you want to use a NumPy array as input, convert it to a tensor first, for example with K.constant:
pooled_grads = K.mean(K.constant(arr3), axis=(0, 1, 2))
Note that pooled_grads here will be another tensor, so printing it will not give you the value directly, but just a reference to the tensor object. In order to get the value of the tensor, you can use for example K.get_value:
print(K.get_value(pooled_grads))
# 3.5

Why I can't draw a chart? TypeError: unhashable type: 'numpy.ndarray'

I want to see the results of the regression with the graph. But it turns out a blank chart.
I use also not dataframe just values. but the result was same. And the dataset includes 537577 rows
TypeError: unhashable type: 'numpy.ndarray'
#1. kütüphaneker
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.formula.api as sm
# 2. veri ön işleme
veriler = pd.read_csv("BlackFriday.csv")
print(veriler)
#eksikveriler
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values="NaN", strategy="mean", axis=0)
pro2 = veriler.iloc[:,9:11].values
pro2 = imputer.fit_transform(pro2)
print(veriler)
#test-eğitim bölme
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(s,y,test_size=0.33,
random_state=0)
from sklearn.linear_model import LinearRegression
lin_reg=LinearRegression()
lin_reg.fit(s.values,y.values)
plt.scatter(s.values,y.values)
plt.plot(s,lin_reg.predict(s.values))
try this:
plt.scatter([s.values],[y.values])
shuld work with lists

Tensorflow Tensor out of CSV has no size?

I just can't get any dimensions (size, lenght) out of this damn tensor "datatens". here is the code and the error message:
import tensorflow as tf
import numpy as np
import tflearn
import pandas as pd
from tensorflow import keras
file = 'some.csv'
record_defaults = [tf.float64]*18
from tflearn.data_utils import load_csv
data , label = load_csv(file, target_column=0,has_header=True,
categorical_labels=True, n_classes=50)
datatens = tf.data.Dataset.from_tensor_slices((data,label))
print(datatens.get_shape().as_list())
ERROR:
<TensorSliceDataset shapes: ((17,), (50,)), types: (tf.string, tf.float64)>
Traceback (most recent call last):
File "basic_class.m", line 44, in <module>
print(datatens.get_shape().as_list())
AttributeError: 'TensorSliceDataset' object has no attribute 'get_shape'
FOLLOWUP:
after getting eager execution running im curious, why my tensor is integer instead of float. here is the output of the advised code.
CODE:
print(tf.shape(data))
print(tf.shape(label))
OUTPUT:
Tensor("Shape:0", shape=(2,), dtype=int32)
Tensor("Shape_1:0", shape=(2,), dtype=int32)
When you call tf.data.Dataset.from_tensor_slices, you get a dataset, not a tensor. A dataset is essentially a container of tensors, and you can access its tensors in a few ways.
The simplest way is to call the dataset's make_one_shot_iterator method. This returns an iterator that cycles through the tensors. The best documentation on datasets and iterators is here.
Are you sure you want to call tf.data.Dataset.from_tensor_slices? Aren't data and label already tensors?
EDIT:
If you want to validate the tensor containing labels, try this code:
import tensorflow as tf
import numpy as np
import tflearn
import pandas as pd
from tensorflow import keras
from tflearn.data_utils import load_csv
tf.enable_eager_execution()
file = 'some.csv'
record_defaults = [tf.float64]*18
data, label = load_csv(file, target_column=0,has_header=True,
categorical_labels=True, n_classes=50)
print(tf.shape(label))
Enabling eager execution is important because it lets you access the tensor without having to create and run a session.

How to display MXNet NDArray as image in Jupyter Notebook?

I have an MXNet NDArray that has image data in it. How do I render the NDArray as image in Jupyter Notebook?
type(data)
mxnet.ndarray.ndarray.NDArray
data.shape
(3, 759, 1012)
Here is how to do it:
Convert the MXNet NDArray to numpy array.
Transpose the array to move channel to last dimension.
Convert the array to uint8 (0 to 255).
Render the array using matplotlib.
Here is the code:
import mxnet as mx
import numpy as np
from matplotlib import pyplot as plt
def render_as_image(a):
img = a.asnumpy() # convert to numpy array
img = img.transpose((1, 2, 0)) # Move channel to the last dimension
img = img.astype(np.uint8) # use uint8 (0-255)
plt.imshow(img)
plt.show()
You can then render the array by calling render_as_image.
render_as_image(data)
To display an image or any other plot using Matplotlib first you need to convert MXNet NDArray to NumPy array.
For example, a is your MXNet NDArray to convert it into Numpy we will do this b = a.asnumpy(). Now you can plot/show this b using Matplotlib.

how to send values to function using feed_dict in tensorflow?

I'm beginner in tensorflow and i'm working on a project which i want to send values to a placeholder and use this placeholder in a function so i will simplify what i want.
This is a simple code
import tensorflow as tf
import glob
from PIL import Image
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
x = tf.placeholder(dtype=tf.float32,shape=[1])
def fun():
print(x)
return x
with tf.Session() as sess:
sess.run(fun(),feed_dict={x:[5.]})
I want to use X value inside the function but when i print it i get the shape only however i used sess.run to run the function so that i expect to print the value not the shape but also when i use print(sess.run(x)) it give me error and say i must feed X with value so what am i missing ?
You should write it like that:
x = tf.placeholder(dtype=tf.float32,shape=[1])
def fun():
return x
with tf.Session() as sess:
y=sess.run(fun(),feed_dict={x:[5.]})
print(y)