对于想了解【Ubuntu18.0.4】树莓派4B安装tensorflow的读者,本文将提供新的信息,我们将详细介绍2.2.0、numpy、h5py、grpcio和scipy,并且为您提供关于"Valu
对于想了解【Ubuntu18.0.4】树莓派4B 安装 tensorflow的读者,本文将提供新的信息,我们将详细介绍2.2.0、numpy、h5py、grpcio和scipy,并且为您提供关于"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类、AttributeError: type object ‘h5py.h5.H5PYConfig‘ has no attribute ‘__reduce_cython__‘的解决方案、h5py.File 读取文件报错、h5py,一个无敌的 Python 库!的有价值信息。
本文目录一览:- 【Ubuntu18.0.4】树莓派4B 安装 tensorflow(2.2.0)、numpy、h5py、grpcio和scipy(树莓派4b安装ubuntu16)
- "ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类
- AttributeError: type object ‘h5py.h5.H5PYConfig‘ has no attribute ‘__reduce_cython__‘的解决方案
- h5py.File 读取文件报错
- h5py,一个无敌的 Python 库!
【Ubuntu18.0.4】树莓派4B 安装 tensorflow(2.2.0)、numpy、h5py、grpcio和scipy(树莓派4b安装ubuntu16)
补充于2021-05-09
补充的原因时发现我的同学看这个教程都。。。。
所以,你懂的
如果你的系统是树莓派的官方镜像的话,很不幸,你是一个32位系统,即armv7l
这个时候你要安装tensorflow的话(前提是用系统自带的3.7),就我下面放的地址里面下载tensorflow-2.4.0-cp37-none-linux_armv7l.whl
,这很重要,因为树莓派官方的那个系统版本是armv7l
,而下面的教程用的是buntu
64
位系统,是aarch64
操作系统版本 ubuntu18.0.4
机器树莓派4B
目标安装 tensorflow
先看下面连接文章,下载到你需要的tensorflow
树莓派4B安装Tensorflow(Python3.5和3.7下分别进行安装)
下载的版本需要和你的机器、操作系统和python版本 三者对应
在安装tensorflow之前,需要安装一些工具,再安装一些依赖库
首先安装
sudo apt-get install libhdf5-dev
然后安装cython(不是cpython)
sudo pip install Cython
和wheel
sudo pip install wheel
准备工作已经做好
temsorflow源代码下载地址
接下来可以直接sudo pip install tensorflow-2.2.0-cp37-none-linux_aarch64.whl
pip会自动解决tensorflow的依赖库,但是其中scipy和h5py会比较缓慢
keras-preprocessing, gast, absl-py, grpcio, h5py, opt-einsum, tensorflow-estimator, termcolor, protobuf, tensorboard-plugin-wit, wheel, pyasn1, rsa, cachetools, pyasn1-modules, google-auth, oauthlib, requests-oauthlib, google-auth-oauthlib, zipp, importlib-metadata, markdown, werkzeug, tensorboard, wrapt, astunparse, google-pasta, tensorflow
这些是sudo pip install tensorflow-2.2.0-cp37-none-linux_aarch64.whl命令运行的时候检查并安装的依赖库,
如果安装的时候卡住,退出手动安装一下
sudo pip install xxxx
安装完成后
运行下面代码
import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation=''relu''),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=''softmax'')
])
model.compile(optimizer=''adam'',
loss=''sparse_categorical_crossentropy'',
metrics=[''accuracy''])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
如果输出正常,说明tensorflow基本功能已经ok
"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类
如何解决"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类
我一直在研究用于图像分类的 CNN,但我一直遇到同样的错误,我的数据正在加载到数据帧中,但我无法将其转换为张量以将其输入 CNN。如您所见,我使用此代码将图片加载到数据框中:
for i in range(len(merged)):
full_path = merged.iloc[i][''Image Path Rel'']
filename = full_path[-22:-1] + ''G''
try:
img = img_to_array(load_img(''D:/Serengeti_Data/Compressed/Compressed/'' + filename,target_size=(32,32,3)))
except:
img = np.zeros((32,3),dtype=np.float32)
images = images.append({''Capture Id'' : merged.iloc[i][''Capture Id''],''Image'' : img},ignore_index = True)
else:
images = images.append({''Capture Id'' : merged.iloc[i][''Capture Id''],ignore_index = True)
然后,一旦我使用 load_img()
和 img_to_array()
加载了图像,我进行了重塑以获得所需的 (32,3) 形状。还通过将 Image 列除以 255 来标准化这些值。
然后我这样做是为了尝试将其转换为张量:
train_tf = tf.data.Dataset.from_tensor_slices(images[''Image''])
# Also tried this,but didn''t got the same results:
# train_tf = tf.convert_to_tensor(train_df[''Image''])
但不断收到错误:
ValueError: 无法将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)
我也尝试跳过它并立即尝试适应我们的模型,但得到了完全相同的错误:
trying_df = pd.DataFrame(images[''Image''])
target_df = pd.DataFrame(targets)
animal_model = models.Sequential()
animal_model.add(layers.Conv2D(30,kernel_size = (3,padding = ''valid'',activation = ''relu'',input_shape =(32,3)))
animal_model.add(layers.MaxPooling2D(pool_size=(1,1)))
animal_model.add(layers.Conv2D(60,kernel_size=(1,1),activation = ''relu''))
animal_model.add(layers.Flatten())
animal_model.add(layers.Dense(100,activation = ''relu''))
animal_model.add(layers.Dense(10,activation = ''softmax''))
## compiler to model
animal_model.compile(loss = ''categorical_crossentropy'',metrics = [''accuracy''],optimizer =''adam'')
## training the model
animal_model.fit(trying_df,target_df,batch_size = 128,epochs = 15)
animal_model.summary()
TensorFlow 版本:2.4.1
Numpy 版本:1.19.5
熊猫版本:1.0.1
解决方法
为了加载图像,您可以使用以下代码:
image = cv2.imread(filename)
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
为了调整图像的大小和缩放比例,最好让模型“嵌入”预处理功能。
IMG_SIZE = 180
resize_and_rescale = tf.keras.Sequential([
layers.experimental.preprocessing.Resizing(IMG_SIZE,IMG_SIZE),layers.experimental.preprocessing.Rescaling(1./255)
])
model = tf.keras.Sequential(
[
resize_and_rescale,layers.Conv2D(32,3,activation="relu"),layers.MaxPooling2D(),layers.Conv2D(64,layers.Conv2D(128,layers.Flatten(),layers.Dense(128,layers.Dense(len(class_names),activation="softmax"),]
)
model.compile(
optimizer="adam",loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=["accuracy"],)
注意:
处理图像时使用 tf.Data
而不是 numpy 数组。您可以使用以下代码作为示例:
https://github.com/alessiosavi/tensorflow-face-recognition/blob/90d4acbea8f79539826b50c82a63a7c151441a1a/dense_embedding.py#L155
AttributeError: type object ‘h5py.h5.H5PYConfig‘ has no attribute ‘__reduce_cython__‘的解决方案
1 问题描述
程序运行时候报错:
AttributeError: type object ''h5py.h5.H5PYConfig'' has no attribute ''__reduce_cython__''
2 解决方案——降低h5py的版本
原来的版本是2.10.0,降低到2.8.0即可。
先卸载原有的h5py,然后重新安装低版本的h5py。
pip uninstall h5py
pip install h5py==2.8.0
踩坑归纳:这个h5py我都重装了无数次了,从2.10,2.8,2.7,2.6,2.5,我几乎都试过了一遍,但是都没有解决。而在网络上寻找解决方案的过程中,很多的朋友都采用了2.8.0解决了问题。
于是我反复重装2.8.0,直到,出现很长的安装计划这个,才算是安装完成。
程序运行时候的问题也变成了:ImportError: attempted relative import with no known parent package
h5py.File 读取文件报错
代码:
f = h5py.File(''xxx/G2.h5'', ''r'')
错误:
OSError: Unable to open file (unable to lock file, errno = 11, error message = ''Resource temporarily unavailable'')
一般 OSError 都是文件路径的问题,但此处不同。
解决办法:(linux下打开终端)
cp xxx/G2.h5 ~
并重新修改文件路径:
f = h5py.File(''~/G2.h5'', ''r'')
个人认为原因可能是文件权限的问题。
h5py,一个无敌的 Python 库!
大家好,我是涛哥,本文内容来自 涛哥聊Python ,转载请标原创。
今天为大家分享一个无敌的 Python 库 - h5py。
Github地址:https://github.com/h5py/h5py
在科学计算和数据分析中,大规模数据集的存储和管理是一个重要的问题。HDF5(Hierarchical Data Format version 5)是一种用于存储和组织大型数据集的文件格式。Python 的 h5py
库是一个用于与 HDF5 文件交互的接口,它结合了 HDF5 的强大功能和 Python 的易用性,使得处理大型数据集变得更加方便和高效。本文将详细介绍 h5py
库,包括其安装方法、主要特性、基本和高级功能,以及实际应用场景,帮助全面了解并掌握该库的使用。
安装
要使用 h5py
库,首先需要安装它。可以通过 pip 工具方便地进行安装。
以下是安装步骤:
pip install h5py
安装完成后,可以通过导入 h5py
库来验证是否安装成功:
import h5py
print("h5py库安装成功!")
特性
- 高效的数据存储和读取:支持高效地存储和读取大型数据集。
- 层次化数据结构:支持创建复杂的层次化数据结构,类似于文件系统。
- 多种数据类型:支持多种数据类型,包括标量、数组、表格等。
- 并发访问:支持多进程和多线程并发访问。
- 兼容性强:与其他科学计算库如 NumPy、Pandas 无缝集成。
基本功能
创建和写入HDF5文件
使用 h5py
库,可以方便地创建和写入 HDF5 文件。
以下是一个示例:
import h5py
import numpy as np
# 创建HDF5文件
with h5py.File(''example.h5'', ''w'') as f:
# 创建数据集
dset = f.create_dataset(''dataset'', data=np.arange(100))
print("HDF5文件创建并写入数据成功!")
读取HDF5文件
使用 h5py
库,可以方便地读取 HDF5 文件。
以下是一个示例:
import h5py
# 读取HDF5文件
with h5py.File(''example.h5'', ''r'') as f:
# 读取数据集
data = f[''dataset''][:]
print("读取的数据:", data)
创建和读取属性
h5py
库支持为数据集和组创建和读取属性。
以下是一个示例:
import h5py
# 创建HDF5文件并添加属性
with h5py.File(''example.h5'', ''w'') as f:
dset = f.create_dataset(''dataset'', data=np.arange(100))
dset.attrs[''description''] = ''This is a dataset containing integers from 0 to 99.''
print("属性添加成功!")
# 读取HDF5文件和属性
with h5py.File(''example.h5'', ''r'') as f:
dset = f[''dataset'']
description = dset.attrs[''description'']
print("读取的属性:", description)
创建组和层次化结构
h5py
库支持创建组和复杂的层次化数据结构。
以下是一个示例:
import h5py
# 创建HDF5文件并添加组
with h5py.File(''example.h5'', ''w'') as f:
grp = f.create_group(''my_group'')
grp.create_dataset(''dataset_in_group'', data=np.arange(50))
print("组和数据集创建成功!")
# 读取组和数据集
with h5py.File(''example.h5'', ''r'') as f:
data = f[''my_group/dataset_in_group''][:]
print("读取的数据:", data)
高级功能
压缩和过滤
h5py
库支持对数据集进行压缩和过滤,以节省存储空间和提高数据访问效率。
以下是一个示例:
import h5py
import numpy as np
# 创建HDF5文件并添加压缩的数据集
with h5py.File(''compressed_example.h5'', ''w'') as f:
dset = f.create_dataset(''compressed_dataset'', data=np.arange(1000), compression=''gzip'', compression_opts=9)
print("压缩数据集创建成功!")
# 读取压缩数据集
with h5py.File(''compressed_example.h5'', ''r'') as f:
data = f[''compressed_dataset''][:]
print("读取的压缩数据:", data)
分块存储
h5py
库支持对大数据集进行分块存储,以提高数据访问效率。
以下是一个示例:
import h5py
import numpy as np
# 创建HDF5文件并添加分块存储的数据集
with h5py.File(''chunked_example.h5'', ''w'') as f:
dset = f.create_dataset(''chunked_dataset'', data=np.arange(10000), chunks=(1000,))
print("分块存储数据集创建成功!")
# 读取分块存储数据集
with h5py.File(''chunked_example.h5'', ''r'') as f:
data = f[''chunked_dataset''][:]
print("读取的分块存储数据:", data)
并发访问
h5py
库支持多进程和多线程并发访问,以下是一个示例:
import h5py
import numpy as np
from multiprocessing import Process
def write_data(filename, dataset_name, data):
with h5py.File(filename, ''a'') as f:
dset = f.create_dataset(dataset_name, data=data)
print(f"数据写入 {dataset_name} 成功!")
def read_data(filename, dataset_name):
with h5py.File(filename, ''r'') as f:
data = f[dataset_name][:]
print(f"读取的数据 {dataset_name}:", data)
# 创建HDF5文件并进行并发写入和读取
filename = ''concurrent_example.h5''
processes = []
for i in range(5):
p = Process(target=write_data, args=(filename, f''dataset_{i}'', np.arange(1000) * i))
processes.append(p)
p.start()
for p in processes:
p.join()
# 并发读取数据
for i in range(5):
p = Process(target=read_data, args=(filename, f''dataset_{i}''))
p.start()
p.join()
实际应用场景
科学计算数据存储
在科学计算中,通常需要存储大量的实验数据和计算结果,可以使用 h5py
库高效地存储和管理这些数据。
import h5py
import numpy as np
# 模拟实验数据
experiment_data = np.random.rand(1000, 1000)
# 创建HDF5文件并存储实验数据
with h5py.File(''scientific_data.h5'', ''w'') as f:
dset = f.create_dataset(''experiment_data'', data=experiment_data)
print("实验数据存储成功!")
# 读取实验数据
with h5py.File(''scientific_data.h5'', ''r'') as f:
data = f[''experiment_data''][:]
print("读取的实验数据:", data)
机器学习模型存储
在机器学习中,训练好的模型通常需要保存以便后续使用,可以使用 h5py
库高效地存储和读取模型参数。
import h5py
import numpy as np
# 模拟训练好的模型参数
model_weights = {''layer1'': np.random.rand(100, 100), ''layer2'': np.random.rand(100, 10)}
# 创建HDF5文件并存储模型参数
with h5py.File(''model_weights.h5'', ''w'') as f:
for layer, weights in model_weights.items():
f.create_dataset(layer, data=weights)
print("模型参数存储成功!")
# 读取模型参数
with h5py.File(''model_weights.h5'', ''r'') as f:
layer1_weights = f[''layer1''][:]
layer2_weights = f[''layer2''][:]
print("读取的模型参数:")
print("layer1:", layer
1_weights)
print("layer2:", layer2_weights)
数据分析和可视化
在数据分析和可视化过程中,经常需要处理大规模数据,可以使用 h5py
库高效地存储和读取数据。
import h5py
import numpy as np
import matplotlib.pyplot as plt
# 生成大规模数据
data = np.random.rand(10000, 2)
# 创建HDF5文件并存储数据
with h5py.File(''large_data.h5'', ''w'') as f:
f.create_dataset(''large_dataset'', data=data)
print("大规模数据存储成功!")
# 读取数据并进行可视化
with h5py.File(''large_data.h5'', ''r'') as f:
data = f[''large_dataset''][:]
plt.scatter(data[:, 0], data[:, 1], s=1)
plt.title(''Large Dataset Visualization'')
plt.xlabel(''X-axis'')
plt.ylabel(''Y-axis'')
plt.show()
时间序列数据存储
在金融、气象等领域,经常需要处理时间序列数据,可以使用 h5py
库高效地存储和读取时间序列数据。
import h5py
import numpy as np
import pandas as pd
# 生成时间序列数据
dates = pd.date_range(''20230101'', periods=1000)
values = np.random.rand(1000)
# 创建HDF5文件并存储时间序列数据
with h5py.File(''timeseries_data.h5'', ''w'') as f:
f.create_dataset(''dates'', data=dates.astype(''S''))
f.create_dataset(''values'', data=values)
print("时间序列数据存储成功!")
# 读取时间序列数据
with h5py.File(''timeseries_data.h5'', ''r'') as f:
dates = f[''dates''][:].astype(''U'')
values = f[''values''][:]
timeseries_data = pd.Series(values, index=pd.to_datetime(dates))
print("读取的时间序列数据:")
print(timeseries_data)
总结
h5py
库是一个功能强大且易于使用的工具,能够帮助开发者高效地处理和管理大规模数据集。通过支持高效的数据存储和读取、层次化数据结构、多种数据类型、并发访问和与其他科学计算库的兼容性,h5py
库能够满足各种复杂的数据处理需求。本文详细介绍了 h5py
库的安装方法、主要特性、基本和高级功能,以及实际应用场景。希望本文能帮助大家全面掌握 h5py
库的使用,并在实际项目中发挥其优势。
今天关于【Ubuntu18.0.4】树莓派4B 安装 tensorflow和2.2.0、numpy、h5py、grpcio和scipy的讲解已经结束,谢谢您的阅读,如果想了解更多关于"ValueError: Failed to convert a NumPy array to an Tensor (Unsupported object type numpy.ndarray). 在 TensorFlow CNN 中进行图像分类、AttributeError: type object ‘h5py.h5.H5PYConfig‘ has no attribute ‘__reduce_cython__‘的解决方案、h5py.File 读取文件报错、h5py,一个无敌的 Python 库!的相关知识,请在本站搜索。
本文标签: