AI摘要:本文主要介绍了Python编程语言中的一些常用库和函数,包括TensorFlow、Pandas、NumPy等。首先,通过代码展示了如何使用这些库进行文件读取、数据可视化等操作。接着,介绍了Python中的all()和any()函数,这两个函数用于对可迭代对象中的元素进行布尔值判断。然后,详细讲解了如何使用TensorFlow动态给变量赋值。此外,还介绍了如何使用conda创建和管理Python虚拟环境。最后,探讨了Pandas中获取行数、列数和元素总数的方法,以及使用GPU进行计算的相关操作。

Powered by AISummary.
# %%
import os,sys
import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# %%
print(tf.__version__)

# %%
current_dir_path = os.getcwd()
current_dir_path


# %%
csv_files = []
for roots, dirs, files in os.walk(current_dir_path): 
    for file in files:
        # print(file)
        if file.endswith(".csv"):
            csv_files.append(os.path.join(roots, file))
            print(os.path.join(roots,file))


# %%
current_dirs_name = os.listdir(current_dir_path)
current_dirs_name


# %%
csv_files


# %%
data = pd.read_csv(csv_files[0])
data_keys = data.keys()


# %%
data_keys


# %%
pld = pd.DataFrame(data,columns=['median_income','population'])

# %%
plt.scatter(pld['median_income'],pld['population'],c='red')

# %%

all()和any()

语法 :any(iterable)

对于迭代中的任何 x,如果 bool(x) 是 True,返回 True。
如果迭代是空,返回 False。
any() 函数将一个可迭代对象作为参数,只要该可迭代对象中至少有一项为 True,就返回 True。

语法:all(iterable)

如果 bool(x) 对于可迭代对象中的所有值 x 为 True,则返回 True。
如果可迭代对象为空,则返回 True。
all() 函数接受一个可迭代对象作为参数,仅当可迭代对象中的所有项的计算结果为 True,或可迭代对象为空时才返回 True。在所有其他情况下,all() 函数返回 False。

Tensorflow

动态的给变量tf.Variable赋值

如果只需要给Variable赋值一次,可以通过assign这样进行赋值。

x = tf.Variable(0)
y = tf.assign(x,1)

使用conda

conda命令的使用方式都是一致的,首先可以先创建虚拟环境,例如Python3.9的环境:
conda create -n Python39 python=3.9

创建完成后激活(也可以配置到bashrc中默认激活)
conda activate Python39

激活python3.9
source /home/yokay/miniconda3/bin/activate
释放python3.9
conda deactivate

Pandas获取行数,列数和元素总数(大小)

pandas.DataFrame

显示行数,列数等:df.info()
获取行数:len(df)
获取列数:len(df.columns)
获取行数和列数:df.shape
获取元素总数(大小):df.size
指定index时的注意事项:如果使用set_index()方法将数据列指定为索引,则该列将从数据主体中删除(值属性),因此不会计入列数。

pandas.Series

获取元素总数(大小):len(s),s.size

使用GPU运行

  1. tf.config.list_physical_devices('GPU')获取GPU信息:PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')

得到GPU的编号为0

  1. CUDA_VISIBLE_DEVICES=0 python3 main.py

扩维度和换维度

np.expand_dims

(360,480)——>(1,360,380):np.expand_dims(a, axis=0)

(360,480)——>(360,380,1):np.expand_dims(a, axis=-1)

np.transpose

(1,360,380)——>(360,1,380):np.transpose(a, (1,0,2))

(1,360,380)——>(360,380,1):np.transpose(a, (1,2,0))

Last modification:April 25, 2024
文章免费,无需打赏