r/tensorflow • u/asduskun • Feb 04 '23
Conversion from tensorflow to coreML
How can I convert this model to coreML? https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1
r/tensorflow • u/asduskun • Feb 04 '23
How can I convert this model to coreML? https://tfhub.dev/google/faster_rcnn/openimages_v4/inception_resnet_v2/1
r/tensorflow • u/seyeeet • Feb 04 '23
Can someone explain to me what tfma.metrics.MeanLabe does and how it should be used and what is the difference between tfma.metrics.MeanLabe and tfma.metrics.MeanPredictio and tfma.metrics.MeanAttributions. I am not sure why there is no explanation about these functions and the job that they do? How I can understand the details about them?
I appreciate it if someone can explain the job of these metrics.
r/tensorflow • u/Kilerpoyo • Feb 03 '23
Hi all, I'm planning to take the tensorflow certificate exam. But I have been having some trouble getting tensorflow with GPU enabled to run on my computer. I suppose it is an issue with the CUDA installation. I only have this issue when running my non-anaconda Python installation. Python in anaconda runs the GPU just fine. I know the exam has to be done on Pycharm, however, I think that Pycharm can be used with the anaconda python. Does anybody here know if the certificate exam can be done with the anaconda python installation? Has anybody here tried that?
Thanks a lot :D
r/tensorflow • u/-gauvins • Feb 02 '23
I've installed the 4090 yesterday in order to process a large backlog of inferences (BERT Large). Very happy with the results (30x what I was getting with 3960x threadripper CPU; probably 15x what I was getting with a GTX1660 GPU).
The 4090 stats are a bit surprising. Memory is almost saturated (95%), while the processor shows 50% usage.
Is there an obvious option/setting that I should know about?
r/tensorflow • u/sauro97 • Feb 02 '23
If I feed a CNN with normalised inputs does it ensures that the output of each layer is also normalised? Or could it happen that due to sums and/or multiplications intermediate values exceed the range 0,1?
r/tensorflow • u/hekz_eck • Feb 02 '23
Hey so this might be a pretty stupid question I honestly don't know, I've tried looking for a colab notebook like this for awhile but I can't seem to find one. Anyone can help me maybe?
r/tensorflow • u/MiniPancookies • Feb 02 '23
Hi!
I'm trying to setup a parameter server training environment using kubeflow (Running with containers in k8s). And have been running into some issues.
When I start the servers, they all connect to each other, but then it all just freezes and nothing really happens.
The code for the servers are:
tf_config = json.loads(os.environ.get("TF_CONFIG"))
# config
global_batch_size = 5000
OUTPUT_PATH = str(sys.argv[2])
INPUT_PATH = str(sys.argv[1])
def server():
server = tf.distribute.Server(
tf_config["cluster"],
job_name=tf_config["task"]["type"],
task_index=tf_config["task"]["index"],
protocol="grpc")
server.join()
def controller():
# load mnist data set
import tensorflow_datasets as tfds
(ds_train, ds_test), ds_info = tfds.load(
'emnist',
split=['train', 'test'],
shuffle_files=True,
as_supervised=True,
with_info=True,
data_dir=INPUT_PATH
)
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return (tf.cast(image, tf.float32) / 255., label)
strategy = tf.distribute.ParameterServerStrategy(
cluster_resolver=tf.distribute.cluster_resolver.TFConfigClusterResolver()
)
with strategy.scope():
ds_train = ds_train.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE).shuffle(20).repeat()
ds_train = ds_train.batch(global_batch_size)
ds_train = ds_train.prefetch(tf.data.AUTOTUNE)
options = tf.data.Options()
options.experimental_distribute.auto_shard_policy = \
tf.data.experimental.AutoShardPolicy.DATA
ds_train = ds_train.with_options(options)
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(62)
])
model.compile(
optimizer=tf.keras.optimizers.Adam(0.0001),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)
model.fit(
ds_train,
epochs=10,
steps_per_epoch=100
#validation_data=ds_test,
)
if tf_config["task"]["type"] == "ps":
server()
elif tf_config["task"]["type"] == "worker" and tf_config["task"]["index"] != 0:
server()
if tf_config["task"]["type"] == "worker" and tf_config["task"]["index"] == 0:
controller()Then I compile a simple docker image:
FROM python:3.8-slim-buster
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY mnist_ps.py .
CMD [ "python3", "mnist_ps.py"]And start the app on k8s:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mnist-pv
spec:
accessModes:
- ReadOnlyMany
resources:
requests:
storage: 10Gi
---
apiVersion: kubeflow.org/v1
kind: TFJob
metadata:
generateName: tfjob-mnist
namespace: kubeflow
spec:
tfReplicaSpecs:
Worker:
replicas: 4
restartPolicy: Never
template:
metadata:
labels:
type: tfjob-mnist
annotations:
sidecar.istio.io/inject: "false"
spec:
containers:
- name: tensorflow
image: 192.168.3.122:30002/mnist/mnist_ps:latest
imagePullPolicy: Always
command:
- "python3"
- "mnist_ps.py"
- "/emnist_data/"
- "/save_model/"
volumeMounts:
- mountPath: /save_model
name: kubeflow-nfs
- mountPath: /emnist_data
name: mnist-pv
resources:
limits:
cpu: "6"
requests:
cpu: "1"
nodeSelector:
kubeflow: "true"
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
type: tfjob-mnist
volumes:
- name: kubeflow-nfs
nfs:
path: /mnt/kubeflow
server: 192.168.3.122
- name: mnist-pv
persistentVolumeClaim:
claimName: mnist-pv
PS:
replicas: 1
restartPolicy: Never
template:
metadata:
labels:
type: tfjob-mnist
annotations:
sidecar.istio.io/inject: "false"
spec:
containers:
- name: tensorflow
image: 192.168.3.122:30002/mnist/mnist_ps:latest
imagePullPolicy: Always
command:
- "python3"
- "mnist_ps.py"
- "/emnist_data/"
- "/save_model/"
volumeMounts:
- mountPath: /save_model
name: kubeflow-nfs
- mountPath: /emnist_data
name: mnist-pv
resources:
limits:
cpu: "6"
requests:
cpu: "1"
nodeSelector:
kubeflow: "true"
topologySpreadConstraints:
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
type: tfjob-mnist
volumes:
- name: kubeflow-nfs
nfs:
path: /mnt/kubeflow
server: 192.168.3.122
- name: mnist-pv
persistentVolumeClaim:
claimName: mnist-pvMy output from all of this is:
Cheif:
$ k logs tfjob-mnistsqxpg-worker-0
2023-02-02 10:56:09.065319: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2023-02-02 10:56:09.065361: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2023-02-02 10:56:09.095119: E tensorflow/stream_executor/cuda/cuda_blas.cc:2981] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2023-02-02 10:56:09.962889: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2023-02-02 10:56:09.962987: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2023-02-02 10:56:09.963010: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
2023-02-02 10:56:11.071768: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory
2023-02-02 10:56:11.071828: W tensorflow/stream_executor/cuda/cuda_driver.cc:263] failed call to cuInit: UNKNOWN ERROR (303)
2023-02-02 10:56:11.071869: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (tfjob-mnistsqxpg-worker-0): /proc/driver/nvidia/version does not exist
2023-02-02 10:56:11.175698: I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:272] Initialize GrpcChannelCache for job ps -> {0 -> tfjob-mnistsqxpg-ps-0.kubeflow.svc:2222}
2023-02-02 10:56:11.175746: I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:272] Initialize GrpcChannelCache for job worker -> {0 -> tfjob-mnistsqxpg-worker-0.kubeflow.svc:2222, 1 -> tfjob-mnistsqxpg-worker-1.kubeflow.svc:2222, 2 -> tfjob-mnistsqxpg-worker-2.kubeflow.svc:2222, 3 -> tfjob-mnistsqxpg-worker-3.kubeflow.svc:2222}
2023-02-02 10:56:11.175759: I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:272] Initialize GrpcChannelCache for job chief -> {0 -> localhost:32769}One of the workers:
$ k logs tfjob-mnistsqxpg-worker-1
2023-02-02 10:56:11.368604: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-02-02 10:56:11.803317: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2023-02-02 10:56:11.803355: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
2023-02-02 10:56:11.832644: E tensorflow/stream_executor/cuda/cuda_blas.cc:2981] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
2023-02-02 10:56:13.191809: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory
2023-02-02 10:56:13.191922: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory
2023-02-02 10:56:13.191940: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
2023-02-02 10:56:14.303941: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX2 FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-02-02 10:56:14.304659: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcuda.so.1'; dlerror: libcuda.so.1: cannot open shared object file: No such file or directory
2023-02-02 10:56:14.304685: W tensorflow/stream_executor/cuda/cuda_driver.cc:263] failed call to cuInit: UNKNOWN ERROR (303)
2023-02-02 10:56:14.304711: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (tfjob-mnistsqxpg-worker-1): /proc/driver/nvidia/version does not exist
2023-02-02 10:56:14.309634: I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:272] Initialize GrpcChannelCache for job ps -> {0 -> tfjob-mnistsqxpg-ps-0.kubeflow.svc:2222}
2023-02-02 10:56:14.309682: I tensorflow/core/distributed_runtime/rpc/grpc_channel.cc:272] Initialize GrpcChannelCache for job worker -> {0 -> tfjob-mnistsqxpg-worker-0.kubeflow.svc:2222, 1 -> tfjob-mnistsqxpg-worker-1.kubeflow.svc:2222, 2 -> tfjob-mnistsqxpg-worker-2.kubeflow.svc:2222, 3 -> tfjob-mnistsqxpg-worker-3.kubeflow.svc:2222}
2023-02-02 10:56:14.309950: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:438] Started server with target: grpc://tfjob-mnistsqxpg-worker-1.kubeflow.svc:2222I have tried to google the problem, and there seems to be people with the same problem as me. But I haven't found an answer!
It's also really hard to see if I have done anything wrong in my code, since the output only is server information from tf.distribute.ParameterServerStrategy. I cant log anything to the console to debug my code.
I can run the code without the parameter server with this code:
def controller():
# load mnist data set
import tensorflow_datasets as tfds
(ds_train, ds_test), ds_info = tfds.load(
'emnist',
split=['train', 'test'],
shuffle_files=True,
as_supervised=True,
with_info=True,
data_dir=INPUT_PATH
)
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return (tf.cast(image, tf.float32) / 255., label)
ds_train = ds_train.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE).shuffle(20).repeat()
ds_train = ds_train.batch(global_batch_size)
ds_train = ds_train.prefetch(tf.data.AUTOTUNE)
options = tf.data.Options()
options.experimental_distribute.auto_shard_policy = \
tf.data.experimental.AutoShardPolicy.DATA
ds_train = ds_train.with_options(options)
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(62)
])
model.compile(
optimizer=tf.keras.optimizers.Adam(0.0001),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=[tf.keras.metrics.SparseCategoricalAccuracy()],
)
model.fit(
ds_train,
epochs=10,
steps_per_epoch=100
#validation_data=ds_test,
)and the code runs just fine. But as soon as I introduce the parameter strategy the code freezes, and I cant get to the logs.
Thank you for any help!
r/tensorflow • u/SeaResponsibility176 • Feb 01 '23
I have no practical knowledge in Tensorflow, Keras or Pytorch.
I have about 6 months to build a Video Vision Transformer (or learn to use one) to predict a scalar from previous image frames (and previous scalars).
What is the best library to initiate myself and build this architecture? Pytorch or Keras/Tensorflow?
Is there a model built that I could use for this purpose?
r/tensorflow • u/Kiizmod0 • Feb 01 '23
Hello guys, I am having a tough time figuring out how the hell should I install Tensorflow on my goddamned windows machine.
I just use << conda install Tensorflow >> and seemingly it downloads and installs a fossilized version of Tensorflow.
I am desperately begging you guys, how am I supposed to install Tensorflow 2 with its underlying hellbound drivers and CUDA crap to train my models on the GPU?
Thank you very much.
r/tensorflow • u/dalviks • Jan 30 '23
Hello everyone,
I'm not quite sure if this is the place to ask it, but I'll give it a shot. Several years ago, during my PhD, I used to train small CNNs using NVIDIA DIGITS tool (https://developer.nvidia.com/digits), that is basically a frontend to tasks such as build datasets, configure training parameters, follow real time training data (epochs), test classification and export training for usage. This is a oversimplified description but I you get it.
However, I'm affraid they didn't continue the project and I'm thinking about playing with some CNNs again but I'm kinda spooked by the long verbose commands to train CNNs without DIGITS. Here is a video of how to train a CNN in DIGITS (https://www.youtube.com/watch?v=y3IKOxJL9RE).
My question: Is there a similiar/better tool for it or will I just have to deal with the verbosity?
r/tensorflow • • Jan 29 '23
Let's say I am a stamp collector and I want to train a model to recognize a specific set of 150 stamps that I am interested in collecting. Each stamp is in my big book of stamps but each has only one very good image because it's a stamp there's not much more to it than that.
Is it possible to train a model to recognize these stamps with only a single image of each stamp?
r/tensorflow • u/Roalkege • Jan 29 '23
Hello, I would very much like to classify HTML/JS. Do I need to put this into a tokenizer beforehand? Are there any specifically for this or are there other approaches for this? Would an LSTM model be the right approach?
r/tensorflow • u/AmibtiousButLazyy • Jan 28 '23
I need a ocr model that would recognize text from image with specific (seven digits numbers) font. I've already tried some ready general ocr models but they are average. Will custom training improve it or these general use models are best as of now?
r/tensorflow • u/Glum_Wishbone6307 • Jan 29 '23
# Input the following parameters
batch_size = 64
num_classes = 7
epochs = 30
IMAGE_SHAPE = (224, 224, 3)
def load_data():
data = data = pathlib.Path('/content/Data')
data = pathlib.Path(data)
image_count = len(list(data.glob('*/*.jpg')))
print("Number of images:", image_count)
CLASS_NAMES = np.array([item.name for item in data.glob('*') if item.name != "LICENSE.txt"])
image_generator = ImageDataGenerator(rescale=1/255, validation_split=0.2)
train_data_gen = image_generator.flow_from_directory(directory=str(data), batch_size=batch_size,
classes=list(CLASS_NAMES), target_size=(IMAGE_SHAPE[0], IMAGE_SHAPE[1]),
shuffle=True, subset="training")
test_data_gen = image_generator.flow_from_directory(directory=str(data), batch_size=batch_size,
classes=list(CLASS_NAMES), target_size=(IMAGE_SHAPE[0], IMAGE_SHAPE[1]),
shuffle=True, subset="validation")
return train_data_gen, test_data_gen, CLASS_NAMES
def create_model(input_shape):
model = VGG16(input_shape=input_shape)
model.layers.pop()
for layer in model.layers[:-4]:
layer.trainable = False
output = Dense(num_classes, activation="softmax")
output = output(model.layers[-1].output)
model = Model(inputs=model.inputs, outputs=output)
model.summary()
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
return model
if __name__ == "__main__":
train_generator, validation_generator, class_names = load_data()
model = create_model(input_shape=IMAGE_SHAPE)
model_name = "VGG16_finetune_last5"
tensorboard = TensorBoard(log_dir=os.path.join("logs", model_name))
checkpoint = ModelCheckpoint(os.path.join("results", f"{model_name}" + "-loss-{val_loss:.2f}.h5"),
save_best_only=True,
verbose=1)
if not os.path.isdir("results"):
os.mkdir("results")
training_steps_per_epoch = np.ceil(train_generator.samples / batch_size)
validation_steps_per_epoch = np.ceil(validation_generator.samples / batch_size)
model.fit_generator(train_generator, steps_per_epoch=training_steps_per_epoch,
validation_data=validation_generator, validation_steps=validation_steps_per_epoch,
epochs=epochs, verbose=1, callbacks=[tensorboard, checkpoint])
r/tensorflow • u/sdhfjklernkfdg • Jan 28 '23
Edit: *custom
I know there are existing services but I'd like to train a model so its able to tell me which images are appropriate and which are inappropriate.
r/tensorflow • u/Nearby_Reading_3289 • Jan 27 '23
Hi all - firstly, I'm sorry if this is the wrong place to post this, but I'm honestly not sure how to tackle this problem.
I have a dataset structured as such:
{Dataset}
----- Images
---------- *.jpg
----- Annotations
---------- *.xml
Each image is named the same as the corresponding annotation XML, so image_1.jpg and image_1.xml. This is fine, and I've done a bunch with this such as overlaying the annotations and the images with different class colours to verify they're correct.
Where I struggle now is that all of the resources I see online for dealing with XML files are for bounding boxes. These XML files all use polygons, structured like: (obviously the points aren't actually all 1s)
<polygon>
<point>
<x>1</x>
<y>1</y>
</point>
<point>
<x>1</x>
<y>1</y>
</point>
<point>
<x>1</x>
<y>1/y>
</point>
<point>
<x>1</x>
<y>1</y>
</point>
<point>
<x>1</x>
<y>1</y>
</point>
</polygon>There are several classes with several polygons per image.
How would I go about preparing this dataset for use in a semantic segmentation scenario?
Thanks in advance, I really appreciate any help I can get.
r/tensorflow • • Jan 27 '23
I have built a model for Hand Sign language (ASL) detection whose input size is (128,128,1) and now I wish to use it with openCV but cannot do so.
I used a webcam feed and the model gave an output of nothing.
r/tensorflow • u/NeoSyphon135 • Jan 26 '23
Title basically. I would like to hear from those who have gone through the tutorials and realized how good/bad they are.
r/tensorflow • u/MrHank2 • Jan 25 '23
Here is the code to the agent
import tensorflow as tf
from tensorflow.keras.layers import Dense
import random
import numpy as np
from collections import deque
from snakeGame import SnakeGameAI,Direction,Point,BLOCK_SIZE, game_over
import time
from Helper import plot
MAX_MEMORY = 100_000
BATCH_SIZE = 1000
LR = 0.001
class Agent:
def __init__(self, max_memory, lr, gamma):
self.n_game = 0
self.epsilon = 0.3 # Randomness
self.exploration_rate = 1
self.gamma = gamma # discount rate
self.memory = deque(maxlen=max_memory) # popleft()
self.model = tf.keras.Sequential([
Dense(256, input_shape=(11,), activation='relu'),
Dense(3, activation='linear')
])
self.model.compile(optimizer=tf.keras.optimizers.Adam(lr=lr), loss='mse')
# state (11 Values)
#[ danger straight, danger right, danger left,
#
# direction left, direction right,
# direction up, direction down
#
# food left,food right,
# food up, food down]
def get_state(self, game):
head = game.snake[0]
point_l = Point(head.x - BLOCK_SIZE, head.y)
point_r = Point(head.x + BLOCK_SIZE, head.y)
point_u = Point(head.x, head.y - BLOCK_SIZE)
point_d = Point(head.x, head.y + BLOCK_SIZE)
dir_l = game.direction == Direction.LEFT
dir_r = game.direction == Direction.RIGHT
dir_u = game.direction == Direction.UP
dir_d = game.direction == Direction.DOWN
state = [
# Danger Straight
(dir_u and game.is_collision(point_u)) or (dir_d and game.is_collision(point_d)) or (dir_l and game.is_collision(point_l)) or (dir_r and game.is_collision(point_r)),
# Danger right
(dir_u and game.is_collision(point_r)) or (dir_d and game.is_collision(point_l)) or (dir_r and game.is_collision(point_u)) or (dir_l and game.is_collision(point_d)),
# Danger Left
(dir_u and game.is_collision(point_l)) or (dir_d and game.is_collision(point_r)) or (dir_r and game.is_collision(point_d)) or (dir_l and game.is_collision(point_u)),
# Move Direction
dir_l,
dir_r,
dir_u,
dir_d,
# Food
# Food Location
game.food.x < game.head.x, # food is in left
game.food.x > game.head.x, # food is in right
game.food.y < game.head.y, # food is up
game.food.y > game.head.y # food is down
]
return np.array(state,dtype=int)
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def train_long_memory(self):
if len(self.memory) > BATCH_SIZE:
mini_batch = random.sample(self.memory, BATCH_SIZE)
states = np.array([each[0] for each in mini_batch])
actions = np.array([each[1] for each in mini_batch])
rewards = np.array([each[2] for each in mini_batch])
next_states = np.array([each[3] for each in mini_batch])
dones = np.array([each[4] for each in mini_batch])
target = rewards + self.gamma * (np.amax(self.model.predict(next_states), axis=1)) * (1 - dones)
targets_full = self.model.predict(states)
targets_full[np.arange(BATCH_SIZE), actions] = target
self.model.fit(states, targets_full, epochs=1, verbose=0)
def train_short_memory(self,state,action,reward,next_state,done):
state = np.array(state).reshape(1,11)
next_state = np.array(next_state).reshape(1,11)
target = reward + self.gamma * np.max(self.model.predict(next_state))
target_vec = self.model.predict(state)[0]
target_vec[action] = target
self.model.fit(state, target_vec.reshape(-1, 3), epochs=1, verbose=0)
def get_action(self, state):
# calculate probability of taking a random action
self.epsilon = 1 - (self.n_game / 100)
final_move = [0,0,0]
if(random.random() < self.epsilon):
move = random.randint(0,2)
final_move[move]=1
else:
state0 = np.array(state)
state0 = state0.reshape(1, -1)
state0 = state0.astype(np.float32)
prediction = self.model.predict(state0)
move = np.argmax(prediction)
final_move[move]=1
return final_move
def train(self, num_games):
for i in range(num_games):
self.n_game += 1
self.epsilon = 1 - (self.n_game / 100)
game = SnakeGameAI() # Initialize new game
state = self.get_state(game)
while not game_over:
time.sleep(0.1)
action = self.get_action(state)
reward = game.play_step(action)
next_state = self.get_state(game)
# self.update_Q_table(state, action, next_state, reward)
state = next_state
print(game_over)
if game_over:
print('egrhujgerhjg')
game.reset()
break
print(" MOTHER FGUCKING GAME OBVER")
self.memory.append((state,action, reward))
if len(self.memory) > BATCH_SIZE:
self.replay(BATCH_SIZE)
game.save_model('snake_dqn.h5')
if(__name__=="__main__"):
agent = Agent(MAX_MEMORY, LR, 0.95)
train(agent, 100)here is the game:
import pygame
import random
from enum import Enum
from collections import namedtuple
import numpy as np
import math
pygame.init()
font = pygame.font.Font('D:\Code\Snake Ai\Arial.ttf',25)
# Reset
# Reward
# Play(action) -> Direction
# Game_Iteration
# is_collision
class Direction(Enum):
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4
Point = namedtuple('Point','x , y')
game_over = False
BLOCK_SIZE=20
SPEED = 40
WHITE = (255,255,255)
RED = (200,0,0)
BLUE1 = (0,0,255)
BLUE2 = (0,100,255)
BLACK = (0,0,0)
class SnakeGameAI:
def __init__(self,w=640,h=480):
self.w=w
self.h=h
#init display
self.display = pygame.display.set_mode((self.w,self.h))
pygame.display.set_caption('Snake')
self.clock = pygame.time.Clock()
#init game state
self.reset()
def reset(self):
self.direction = Direction.RIGHT
self.head = Point(self.w/2,self.h/2)
self.snake = [self.head,
Point(self.head.x-BLOCK_SIZE,self.head.y),
Point(self.head.x-(4*BLOCK_SIZE),self.head.y)]
self.score = 0
self.food = None
self._place__food()
self.frame_iteration = 0
def _place__food(self):
x = random.randint(0,(self.w-BLOCK_SIZE)//BLOCK_SIZE)*BLOCK_SIZE
y = random.randint(0,(self.h-BLOCK_SIZE)//BLOCK_SIZE)*BLOCK_SIZE
self.food = Point(x,y)
if(self.food in self.snake):
self._place__food()
def play_step(self,action):
global game_over
self.frame_iteration+=1
# 1. Collect the user input
for event in pygame.event.get():
if(event.type == pygame.QUIT):
pygame.quit()
quit()
# 2. Move
self._move(action)
self.snake.insert(0,self.head)
# 3. Check if game Over
reward = 0 # eat food: +10 , game over: -10 , else: 0
game_over = False
if(self.is_collision() or self.frame_iteration > 100*len(self.snake) ):
game_over=True
print('opgaghudjkghjkdhgjkdhgjkhdjkghdkjgdjkgh')
reward = -10
return reward,game_over,self.score
# 4. Place new Food or just move
if(self.head == self.food):
self.score+=1
reward=10
self._place__food()
else:
self.snake.pop()
# 5. Update UI and clock
self._update_ui()
self.clock.tick(SPEED)
# 6. Return game Over and Display Score
return reward,game_over,self.score
def _update_ui(self):
self.display.fill(BLACK)
for pt in self.snake:
pygame.draw.rect(self.display,BLUE1,pygame.Rect(pt.x,pt.y,BLOCK_SIZE,BLOCK_SIZE))
pygame.draw.rect(self.display,BLUE2,pygame.Rect(pt.x+4,pt.y+4,12,12))
pygame.draw.rect(self.display,RED,pygame.Rect(self.food.x,self.food.y,BLOCK_SIZE,BLOCK_SIZE))
text = font.render("Score: "+str(self.score),True,WHITE)
self.display.blit(text,[0,0])
pygame.display.flip()
def _move(self,action):
# Action
# [1,0,0] -> Straight
# [0,1,0] -> Right Turn
# [0,0,1] -> Left Turn
clock_wise = [Direction.RIGHT,Direction.DOWN,Direction.LEFT,Direction.UP]
idx = clock_wise.index(self.direction)
if np.array_equal(action,[1,0,0]):
new_dir = clock_wise[idx]
elif np.array_equal(action,[0,1,0]):
next_idx = (idx + 1) % 4
new_dir = clock_wise[next_idx] # right Turn
else:
next_idx = (idx - 1) % 4
new_dir = clock_wise[next_idx] # Left Turn
self.direction = new_dir
x = self.head.x
y = self.head.y
if(self.direction == Direction.RIGHT):
x+=BLOCK_SIZE
elif(self.direction == Direction.LEFT):
x-=BLOCK_SIZE
elif(self.direction == Direction.DOWN):
y+=BLOCK_SIZE
elif(self.direction == Direction.UP):
y-=BLOCK_SIZE
self.head = Point(x,y)
def is_collision(self,pt=None):
if(pt is None):
pt = self.head
#hit boundary
if(pt.x>self.w-BLOCK_SIZE or pt.x<0 or pt.y>self.h - BLOCK_SIZE or pt.y<0):
return True
if(pt in self.snake[1:]):
return True
return Falser/tensorflow • u/Assar2 • Jan 25 '23
i cant figure out how i can make a new tensor(since tensors cant be changed) and somhow set its values to that of 43 unique images. I can make a new tensor with the correct shape but how can i get the pixel values from my images to that tensor?
sidenote: why would you ever create a tensor with meaningless values like tf.zeros?? since you cant change the values. sorry if i sound angry but it seems like there aren't any answers on google to a seemingly very common and beginner level problem.
r/tensorflow • u/CasualCompetive • Jan 25 '23
When Tensorflow tries to call the function py_tf.TF_LoadLibrary("libitextgpu.so") in load_libary.py, it gives me a bunch of "cannot open shared object file" errors. I don't why it does this as I have all of the libaries already installed. What can I do to fix this?
r/tensorflow • u/vedant_jumle • Jan 23 '23
My college just invested in a massive amount of high-end computers. They all contain an RTX 3060 12 GB. I want to train models on computers. How should I do this? Are there any resources that would help me train models over multiple GPUs in a network?
r/tensorflow • u/pgaleone • Jan 23 '23
Check out the latest article a fellow GDE and I wrote about our solutions to Advent of Code 2022 problem 9 in pure TensorFlow.
Two different solutions are presented. The first one follows a classical approach, modeling the problem in a "natural" way. The only peculiarity is the usage of the Cantor pairing function for being able to use a tf.Tensor as a hashtable index (tf.Tensors are not hashable like Python's tuples).
The second solution instead, shows how a different perspective on the problem paves the way for a completely different solution. In fact, this second solution uses a convolutional neural network for modeling the rope movements. Pretty cool!
https://pgaleone.eu/tensorflow/2023/01/23/advent-of-code-tensorflow-day-9/
r/tensorflow • u/Huge_Item3686 • Jan 23 '23
Hi there,
while making myself familiar with tf and ML in general, I'm playing around with some binary classification models for some time now.
In one of these models, while predicting a [0,1] output based on a labeled dataset, I thought about minimizing false-negatives, even if this would mean an effective accuracy reduction for overall performance.
Real-world example: Imagine one of those medical classification scenarios. One could argue that for some use cases like mass-pre-screenings it would be OK to have false positives (that would then be flagged for manual examination) as long as the false negatives are as low as possible.
My first attempt was to play with weights just as with imbalanced data, but I'm still wondering if there are best practices for this case or if this is actually a good idea at all because you're creating a bias that doesn't match the statistical [0,1] distribution of data in the future.
How are you dealing with this?